Compare commits

...
Author SHA1 Message Date
J. Nick Koston 04aa0fccc6 [daly_bms][tuya] Start each daly request with an empty reader; hold tuya commands for the whole read 2026-11-18 21:22:16 -06:00
J. Nick Koston 0d4d3f9d86 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 21:21:20 -06:00
J. Nick Koston c90cf2c987 Add LengthFrameReader::reset for a new request/response exchange 2026-11-18 21:21:20 -06:00
J. Nick Koston 63fc52ed41 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 21:17:35 -06:00
J. Nick Koston 87be3320a3 Keep a partial frame left behind the frames an idle flush hands over 2026-11-18 21:15:58 -06:00
J. Nick Koston f6b19e3139 [tuya] Send queued commands past a kept partial frame once the line is quiet; update the pioneer_wt pause test 2026-11-18 21:05:49 -06:00
J. Nick Koston 80bb2c4f75 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 21:01:34 -06:00
J. Nick Koston 39fa5b1dd6 Keep a slow partial frame on an idle flush unless frames inside it are taken 2026-11-18 21:01:33 -06:00
J. Nick Koston 4998195f7e [pmsx003] Keep the wrong-type warning for a frame longer than the buffer 2026-11-18 20:00:45 -06:00
J. Nick Koston a51d880796 [pmsx003][apc1] Drop comments left from the removed gap constants 2026-11-18 19:59:46 -06:00
J. Nick Koston 96886c9178 Use the default gap, share the ld24xx headers, name offsets, fold the ld2450 noise tests 2026-11-18 19:38:50 -06:00
J. Nick Koston 037c6f6395 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 19:11:16 -06:00
J. Nick Koston d983659f32 Fix the MIN_LEN comment, keep the AGENTS.md I2C lines as on dev 2026-11-18 19:11:15 -06:00
J. Nick Koston d892a4598f Name length fields, test with the 250 ms default, tighten the ld2450 and ld2460 tests, group mr24hpc1 byte fields 2026-11-18 19:07:27 -06:00
J. Nick Koston d25e511e5e Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 19:06:44 -06:00
J. Nick Koston 837f2706b4 Run CheckedLength's check when documented, cover it in the fixed length check, test 16-bit little-endian lengths 2026-11-18 19:05:12 -06:00
J. Nick Koston c3d475876a Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 19:02:05 -06:00
J. Nick Koston d01835e824 Name the length field offset and trailer; wait 250 ms by default before giving up a frame 2026-11-18 19:01:55 -06:00
J. Nick Koston 7cc83ab11e Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 18:57:17 -06:00
J. Nick Koston 0b0bb23517 Name the length field position and the bytes after the payload 2026-11-18 18:57:16 -06:00
J. Nick Koston 00f4c3165d Move minimum lengths and header checks into the frame formats, add layout comments 2026-11-18 18:50:07 -06:00
J. Nick Koston 1cbe0dd624 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 18:45:15 -06:00
J. Nick Koston 4f8ca50ffe Add FrameMinLength and CheckedLength, tighten comments 2026-11-18 18:45:14 -06:00
J. Nick Koston 6c328fe6c4 Declare frame formats header first, with payload length rules 2026-11-18 18:40:04 -06:00
J. Nick Koston 8ceed2a7e8 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 18:36:15 -06:00
J. Nick Koston e009b526aa Wrap the bus helpers line 2026-11-18 18:36:00 -06:00
J. Nick Koston 29f751a8aa Put the header first in FrameFormat and add payload length rules 2026-11-18 18:35:48 -06:00
J. Nick Koston 3fe21d0ba0 [ld2460] Log a rejected frame at verbose level 2026-11-18 16:37:53 -06:00
J. Nick Koston 8bed96bf79 [ld2410][ld2412] Put the receive timestamp before the byte fields 2026-11-18 16:23:20 -06:00
J. Nick Koston c617c99c60 [pioneer_wt] Drop the comment left from the removed gap constant 2026-11-18 16:05:07 -06:00
J. Nick Koston e76d7b807c [ld2410][ld2412][ld2450][ld2410s] Hand malformed frames back for searching; keep fixture bytes inside the gap 2026-11-18 15:56:52 -06:00
J. Nick Koston ca0de4e3b4 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 15:38:08 -06:00
J. Nick Koston c1b0e3b7b6 Drop the read_frames return value, use feed_all in the custom rule test 2026-11-18 15:38:06 -06:00
J. Nick Koston 38a3aee1b7 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 15:30:06 -06:00
J. Nick Koston 38a90d244d Shorten comments 2026-11-18 15:30:05 -06:00
J. Nick Koston 5a46ae13d8 Shorten the reader comments 2026-11-18 15:30:04 -06:00
J. Nick Koston 9cb098b6ac Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 15:24:46 -06:00
J. Nick Koston 2e01654d39 Hold tuya commands while a frame logs, include what is used, keep the ld2410s continuation inside the gap 2026-11-18 15:24:45 -06:00
J. Nick Koston b338e0a2e3 Name the fixed length constant in upper case 2026-11-18 15:24:44 -06:00
J. Nick Koston e6151b8de1 Use the default gap, shrink the shelly_dimmer buffer, tidy up after review 2026-11-18 15:20:46 -06:00
J. Nick Koston 4cdb7c4c63 [ld2410][ld2412][ld2450][seeed_mr24hpc1] Read through read_frames so a stalled frame is given up 2026-11-18 15:20:43 -06:00
J. Nick Koston 38653974db Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 15:07:55 -06:00
J. Nick Koston fd330d8e23 Return frame lengths internally, limit the fixed length check to FrameFixedLength, return the byte count from read_frames 2026-11-18 15:07:42 -06:00
J. Nick Koston 93074d3d92 [seeed_mr60bha2][seeed_mr60fda2] Reject unknown types in the length rule, flush a stalled frame 2026-11-18 14:56:43 -06:00
J. Nick Koston 90146e7b72 Use read_frames for the idle flush in every reader 2026-11-18 14:56:36 -06:00
J. Nick Koston c7001c33a6 Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 14:50:11 -06:00
J. Nick Koston 3d067b9484 [uart] Add read_frames to feed a LengthFrameReader and flush a stalled frame 2026-11-18 14:50:01 -06:00
J. Nick Koston 4d28203063 State that a frame handler must not feed its own reader 2026-11-18 14:32:38 -06:00
J. Nick Koston ef6232571a Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 14:26:52 -06:00
J. Nick Koston f72ba983e9 Check fixed lengths against the header and N at compile time 2026-11-18 14:26:45 -06:00
J. Nick Koston 47f57f1723 [ld24xx] Include frame_reader.h where the reader is used 2026-11-18 14:25:24 -06:00
J. Nick Koston 9318cd782a [seeed_mr60bha2] Drop a bad header at once 2026-11-18 14:25:23 -06:00
J. Nick Koston a15b02a647 [seeed_mr60fda2] Drop a bad header at once, check the parameter reply length 2026-11-18 14:25:22 -06:00
J. Nick Koston b1ffe8690f [ld2460] Hand a frame back when its data does not fit, and flush a stalled partial frame after a pause 2026-11-18 14:25:21 -06:00
J. Nick Koston 739e2f106f Merge branch 'frame-reader-length-byte' into lfr-cleanup3 2026-11-18 14:21:09 -06:00
J. Nick Koston dcda93d7ca Reject one byte fixed frames at compile time, test replays that recover frames of another format 2026-11-18 14:20:13 -06:00
J. Nick Koston a15d2da270 Merge branch 'frame-reader-length-byte' into lfr-cleanup3
# Conflicts:
#	esphome/components/tuya/tuya.cpp
#	esphome/components/tuya/tuya.h
2026-11-18 13:51:30 -06:00
J. Nick Koston dde2bc4004 [ld2410s] Expect the colon separated hex log in the recovery test 2026-11-18 13:49:40 -06:00
J. Nick Koston d38437dedb [airton_serial] Check and handle a frame in one method 2026-11-18 13:44:57 -06:00
J. Nick Koston 0436eda0f8 Merge remote-tracking branch 'origin/dev' into frame-reader-length-byte 2026-11-18 13:44:52 -06:00
J. Nick Koston 3969df3ed7 [pmsx003] Read big-endian fields with encode_value 2026-11-18 13:44:43 -06:00
David WoodhouseandJ. Nick Koston 3c0905fb03 [tuya] Separate controller base class from UART implementation (#22291)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-18 19:44:33 +00:00
J. Nick Koston 414bc9c806 [apc1] Read big-endian fields with encode_value 2026-11-18 13:44:30 -06:00
J. Nick Koston bf79439362 Keep the reader's lower level private, drain with one replay call, position fields first 2026-11-18 13:43:17 -06:00
J. Nick Koston dba1402480 [ld2410s] Use the shared header size and the hex log macros 2026-11-18 13:43:03 -06:00
J. Nick Koston 54a588d154 [ld2460] Drop the test-only read hooks and build the query from the shared constants 2026-11-18 13:42:40 -06:00
J. Nick Koston 56a0d3e6b3 [ld2450] Drop the test-only read hooks and rename the periodic footer 2026-11-18 13:42:39 -06:00
J. Nick Koston e7b91adb6d [pioneer_wt] Check the frame length once before the checksum 2026-11-18 13:40:51 -06:00
J. Nick Koston a459f80efe [daly_bms] Read fixed 13 byte frames 2026-11-18 13:40:31 -06:00
J. Nick Koston 03d4ba97a2 [seeed_mr60bha2] Shrink the frame buffer to 128 bytes 2026-11-18 13:40:05 -06:00
J. Nick Koston 10e166dc7e [shelly_dimmer] Use a 255 byte reader and build the frame handler once per read 2026-11-18 13:39:57 -06:00
J. Nick Koston 4206665ad9 [tuya] Cap frames at 255 bytes like Tasmota 2026-11-18 13:39:37 -06:00
J. Nick Koston f62bc46eea [esp32_ble_server] Fix crash when an on_write lambda creates a service (#22877) 2026-11-18 13:38:24 -06:00
J. Nick Koston 3508113c61 Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 13:32:15 -06:00
J. Nick Koston a460fb50b4 Check that N holds every format's header and length field 2026-11-18 13:32:11 -06:00
J. Nick Koston 5b98c9c134 Build each frame handler once per read, feed ld2450 and ld2460 inline, stamp tuya once per pass 2026-11-18 13:27:30 -06:00
J. Nick Koston 7f30d135c7 Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 13:20:06 -06:00
J. Nick Koston 06ac99fe7b Test that an idle reader finds nothing in a frame it already handed over 2026-11-18 13:20:03 -06:00
J. Nick Koston d97af3b539 [ld2410s, ld2460] Check recovery after an oversized length instead of the removed logs 2026-11-18 13:12:35 -06:00
J. Nick Koston 3ced52a018 [ld24xx] Share the frame footers and footer check, drop the header checks the reader makes 2026-11-18 13:12:35 -06:00
J. Nick Koston f1ba9db67f [ld2460] Use the reader's frame handler 2026-11-18 13:12:35 -06:00
J. Nick Koston ecb6c5fb10 [ld2410s] Use the reader's frame handler 2026-11-18 13:12:35 -06:00
J. Nick Koston 44eb08c002 [ld2450] Use the reader's frame handler 2026-11-18 13:12:35 -06:00
J. Nick Koston 29dbefee56 [ld2412] Use the reader's frame handler 2026-11-18 13:12:34 -06:00
J. Nick Koston 62de684473 [ld2410] Use the reader's frame handler 2026-11-18 13:12:34 -06:00
J. Nick Koston 17e7e6acfd [daly_bms] Read frames with LengthFrameReader 2026-11-18 13:10:59 -06:00
J. Nick Koston 3b41980b69 [pmsx003] Use the reader's frame handler 2026-11-18 13:10:58 -06:00
J. Nick Koston ca66513783 [apc1] Use the reader's frame handler 2026-11-18 13:10:58 -06:00
J. Nick Koston cf871bc7b9 [tuya] Use the reader's frame handler, take frames up to 512 bytes 2026-11-18 13:10:58 -06:00
J. Nick Koston 6fbf57b747 [shelly_dimmer] Use the reader's frame handler 2026-11-18 13:10:58 -06:00
J. Nick Koston 24601231db [airton_serial] Use the reader's frame handler 2026-11-18 13:10:58 -06:00
J. Nick Koston 518e8e9a60 [pioneer_wt] Use the reader's frame handler 2026-11-18 13:10:58 -06:00
J. Nick Koston 749f632112 [seeed_mr60bha2] Use the reader's frame handler 2026-11-18 13:10:58 -06:00
J. Nick Koston cd25f87619 [seeed_mr60fda2] Use the reader's frame handler 2026-11-18 13:10:57 -06:00
J. Nick Koston 7fa2806227 [seeed_mr24hpc1] Use the reader's frame handler 2026-11-18 13:10:57 -06:00
J. Nick Koston ac6a48d650 Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 13:03:54 -06:00
J. Nick Koston 61b99d91bf Keep the frame end for a one-compare fast path, own the handle/resync loop, check formats differ 2026-11-18 13:02:59 -06:00
J. Nick Koston dd69a68531 [ld24xx] Remove the frame splitter the radars no longer use 2026-11-18 12:49:25 -06:00
J. Nick Koston 39bb0aa1bf [ld2410s] Read frames with LengthFrameReader 2026-11-18 12:49:24 -06:00
J. Nick Koston 8c03fc331c [ld2450] Read frames with LengthFrameReader 2026-11-18 12:49:24 -06:00
J. Nick Koston 1acbcdd015 [ld2412] Read frames with LengthFrameReader 2026-11-18 12:49:23 -06:00
J. Nick Koston 429aa69a4a [ld2410] Read frames with LengthFrameReader 2026-11-18 12:49:23 -06:00
J. Nick Koston f78b8167e4 [ld24xx] Add the LengthFrameReader formats of the radar frames 2026-11-18 12:49:23 -06:00
J. Nick Koston 1241599bbb [pmsx003] Read frames with LengthFrameReader 2026-11-18 12:49:14 -06:00
J. Nick Koston 117b9634b4 [apc1] Read frames with LengthFrameReader 2026-11-18 12:49:14 -06:00
J. Nick Koston 506f1c4821 [ld2460] Read frames with LengthFrameReader 2026-11-18 12:49:13 -06:00
J. Nick Koston d82342b81f [seeed_mr60bha2] Read frames with LengthFrameReader 2026-11-18 12:49:13 -06:00
J. Nick Koston 171c08442f [seeed_mr60fda2] Read frames with LengthFrameReader 2026-11-18 12:49:13 -06:00
J. Nick Koston 1beecc63c4 [seeed_mr24hpc1] Read frames with LengthFrameReader 2026-11-18 12:49:12 -06:00
J. Nick Koston d41625bd74 [tuya] Read frames with LengthFrameReader 2026-11-18 12:49:12 -06:00
J. Nick Koston b6843e022f Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 12:49:12 -06:00
J. Nick Koston 69a7f7a408 Handle a byte in the middle of a frame inline, keep the rest out of line 2026-11-18 12:48:37 -06:00
Jesse Hills d966ec6f71 Merge branch 'release' into dev 2026-11-19 07:43:24 +13:00
Jesse Hills 1feda1bcaa Merge pull request #22888 from esphome/bump-2026.11.0
2026.11.0
2026-11-19 07:42:57 +13:00
J. Nick Koston 5e24d3f6d5 Move pioneer_wt, airton_serial and shelly_dimmer to the FrameFormat API 2026-11-18 12:39:06 -06:00
J. Nick Koston 5e2f90af11 Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 12:36:45 -06:00
J. Nick Koston 9fb6cb4867 Merge remote-tracking branch 'origin/dev' into frame-reader-length-byte
# Conflicts:
#	AGENTS.md
2026-11-18 12:35:26 -06:00
J. Nick Koston e0a5fad2de Cover one or two byte lengths of either byte order, several frame formats and fixed frames; recover every frame held back 2026-11-18 12:35:00 -06:00
J. Nick Koston 00125a448d [ai] Add the cleanups reviews keep missing to AGENTS.md and the review skill (#22708) 2026-11-18 12:33:37 -06:00
J. Nick Koston 6d472f4954 [shelly_dimmer] Read frames with LengthFrameReader 2026-11-18 12:19:07 -06:00
J. Nick Koston 5bf30663b3 [airton_serial] Read frames with LengthFrameReader 2026-11-18 12:17:45 -06:00
J. Nick Koston 2827c1a07e Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 12:16:30 -06:00
J. Nick Koston d76c655553 Keep one copy of replay_() 2026-11-18 12:16:27 -06:00
J. Nick Koston 01765c6ba0 Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 12:15:52 -06:00
J. Nick Koston 8bb20f3ebf [pioneer_wt] Inline the per-byte reader call 2026-11-18 12:15:51 -06:00
J. Nick Koston 9bdd466e51 Make resync() harmless while idle, test a second resync() 2026-11-18 12:15:26 -06:00
Kevin Ahrendt 3fc8bcbd14 [audio] Bump microFLAC to v0.3.1 (#22878) 2026-11-18 13:10:09 -05:00
J. Nick Koston fad0b39f98 Merge branch 'frame-reader-length-byte' into length-frame-reader-callers 2026-11-18 12:03:27 -06:00
J. Nick Koston c803b7163a [pioneer_wt] Look for frames held back by a corrupt length after a pause 2026-11-18 12:03:26 -06:00
J. Nick Koston 03880d5ea6 Skip the empty replay on a noise byte and keep replay_() out of line 2026-11-18 12:03:23 -06:00
Jesse Hills 3b302d3821 Bump version to 2026.11.0 2026-11-19 07:01:16 +13:00
Keith Burzinski cd0258944d [light] Keep the colour of a dim addressable pixel (#22868) 2026-11-19 07:00:36 +13:00
Leandro 512d143a3a [mqtt] Connect as soon as the network is up, not 5 s after boot (#22871) 2026-11-19 06:59:16 +13:00
J. Nick Koston c27895a12b [pioneer_wt] Read frames with LengthFrameReader 2026-11-18 11:58:39 -06:00
Keith Burzinski 9898eb124a [light] Keep the colour of a dim addressable pixel (#22868) 2026-11-19 06:58:14 +13:00
J. Nick Koston 4a04c61ab5 Fold the length checks, resync a partial frame and return a frame found inside, add a benchmark 2026-11-18 11:56:49 -06:00
J. Nick Koston 2cd9ddf246 [core] Add LengthFrameReader for frames that give their own length 2026-11-18 11:51:59 -06:00
Kevin Ahrendt cac0e29421 [sendspin] Default static_delay_adjustable to true (#22872) 2026-11-18 11:51:00 -06:00
Leandro 791d6e15ee [mqtt] Connect as soon as the network is up, not 5 s after boot (#22871) 2026-11-18 11:11:03 -06:00
J. Nick Koston d2b505e76c [bmi270] Feed the watchdog during the config upload (#22862) 2026-11-18 11:08:24 -06:00
J. Nick Koston 0cca1f8c02 [bmi270] Keep the config file in flash on ESP8266, upload it without the heap and simplify the component (#22778) 2026-11-18 11:08:23 -06:00
Martin Klingensmith 3bcd0da1f4 [uart] Accept alternate hardware UART pins on LibreTiny (#22863) 2026-11-18 10:44:53 -06:00
Martin Klingensmith 3e54c5b46d [pioneer_wt] Add Pioneer WT mini split climate component (#22865) 2026-11-18 10:24:00 -06:00
J. Nick Koston e7f7fc162b [qwiic_pir] Set a warning on read failures instead of logging every loop (#22854) 2026-11-18 07:10:30 -05:00
rwrozelle b3474a1ed5 [ci] Add a silent failure review skill (#22846) 2026-11-17 22:33:16 -06:00
Jesse Hills 69037820fa Merge branch 'beta' into dev 2026-11-18 16:07:40 +13:00
Jesse Hills 6c28ef21d9 Merge pull request #22866 from esphome/bump-2026.11.0b7
2026.11.0b7
2026-11-18 16:07:21 +13:00
Jesse Hills ab6e3d9bf0 Bump version to 2026.11.0b7 2026-11-18 15:35:39 +13:00
J. Nick Koston 10ef6e371b [i2c] Stop bus recovery clock pulses once SDA is released (#22852) 2026-11-18 15:35:35 +13:00
J. Nick Koston c84cd04cf7 [modem] Wait for registration before attaching and recover SIM7670 data mode and CMUX (#22816) 2026-11-18 15:35:35 +13:00
J. Nick Koston fb6d7bf265 [scd30] Stop overriding the I2C bus clock-stretch limit on ESP8266 (#22512) 2026-11-18 15:35:35 +13:00
David WoodhouseandJ. Nick Koston 3ad8e35be8 [mqtt] Don't start the broker lookup before the network is up (#22843)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-18 15:35:35 +13:00
Mattheinrichs 11f9f20b61 [cst816] Ignore idle 0xFF touch frames and invalid coordinates (#22435) 2026-11-18 15:35:28 +13:00
Jacopo Labardi b6d0961f25 [logger] Qualify the host clock function (#22838) 2026-11-18 15:31:22 +13:00
David Woodhouse 6046d067aa [climate] Don't fail on a platform entry that only holds nested climates (#22844) 2026-11-18 15:30:52 +13:00
Jonathan Swoboda 690c5f2fb6 [mlx90393] Enable the Wire library on ESP32 Arduino (#22801) 2026-11-18 15:30:52 +13:00
J. Nick Koston 654954f684 [api] Make the event order backpressure test wait until the pipe is full (#22112) 2026-11-18 15:30:44 +13:00
J. Nick Koston e5728407db [i2c] Stop bus recovery clock pulses once SDA is released (#22852) 2026-11-17 18:06:32 -06:00
J. Nick Koston 0cf5af743e [modem] Wait for registration before attaching and recover SIM7670 data mode and CMUX (#22816) 2026-11-17 18:05:44 -06:00
J. Nick Koston 7ffead44fe [scd30] Stop overriding the I2C bus clock-stretch limit on ESP8266 (#22512) 2026-11-17 18:25:29 -05:00
Andriy Malyshenko f2aadcf0b5 [pcm1863] Add PCM1863 stereo audio ADC component (#22794) 2026-11-17 15:18:48 -06:00
NonaSuomy d4d53aa965 [vl6180x] Add VL6180X I2C sensor component (#22689) 2026-11-17 15:16:22 -06:00
dependabot[bot] 735ba9c98a Bump smp from 4.2.0 to 4.3.0 (#22853) 2026-11-17 14:06:09 -06:00
tomaszduda23andClaude 141789d240 [debug] Fix the debug component on nRF54L boards (#22839)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 17:32:52 +01:00
Bascht74 c4df1b163c [uart] Fix undefined shift in the RP2 hardware UART pin check (#22841) 2026-11-17 09:54:29 -06:00
David WoodhouseandJ. Nick Koston 773afa0bb1 [mqtt] Don't start the broker lookup before the network is up (#22843)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-17 09:53:52 -06:00
tomaszduda23andClaude 9bf2bbc241 [nrf52] Store preferences in ZMS on nRF54L (#22840)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 18:21:54 +03:00
Mattheinrichs 84dea8078b [cst816] Ignore idle 0xFF touch frames and invalid coordinates (#22435) 2026-11-17 08:58:24 -06:00
Jacopo Labardi dbf6af2fd7 [logger] Qualify the host clock function (#22838) 2026-11-17 08:50:19 -06:00
David Woodhouse bc6fb7082f [climate] Don't fail on a platform entry that only holds nested climates (#22844) 2026-11-17 08:49:00 -06:00
tomaszduda23andClaude cfa27cea58 [npm1300] Fix the thermistor resistance error message (#22835)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 17:40:04 +03:00
rwrozelleandClaude Opus 5.5 5c061f9e1e [espidf] Hide the ccache binary in the forced-on, no-binary test (#22842)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:29:34 -05:00
Jesse Hills 34b24d0cf5 Merge branch 'beta' into dev 2026-11-17 22:25:16 +13:00
Jesse Hills e27614fda3 Merge pull request #22833 from esphome/bump-2026.11.0b6
2026.11.0b6
2026-11-17 22:24:55 +13:00
J. Nick Koston 8426d04138 [api] Make the event order backpressure test wait until the pipe is full (#22112) 2026-11-17 21:09:01 +13:00
641c8bedc9 [npm1300] Use datasheet defaults, require the thermistor setting for charging, fix charger status (#22769)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-17 09:00:10 +01:00
Jesse Hills 4a39ca1b71 Fix 2026-11-17 20:54:40 +13:00
Jesse Hills 4a218fdbd8 Remove extra test 2026-11-17 20:47:40 +13:00
Jesse Hills d8fc1cd214 Bump version to 2026.11.0b6 2026-11-17 18:54:23 +13:00
J. Nick Koston 1e030b7371 [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 18:54:20 +13:00
J. Nick Koston 3b113f2c39 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 18:54:20 +13:00
J. Nick Koston 73468592a9 [remote_base] Fix the Haier and Mirage remote_receiver binary sensors failing to compile 2026-11-17 18:54:06 +13:00
Jonathan Swoboda a1b456150d [esp32][libretiny] Make delay() wait at least the requested time (#22822) 2026-11-17 18:53:11 +13:00
J. Nick Koston 865a883abb [remote_base] Fix the canalsatld binary sensor and trigger build 2026-11-17 18:53:11 +13:00
J. Nick Koston 357a6717c8 [core] Release only the lwIP core lock a LwIPLock took (#22683) 2026-11-17 18:53:11 +13:00
J. Nick Koston bcb434e05e [esp32_ble] Stop Bluedroid re-running a failed queued MTU or execute write request (#22670) 2026-11-17 18:53:11 +13:00
J. Nick Koston fb65fcc5f6 [esp32_power_management] Clamp the tick step after light sleep so it cannot trip vTaskStepTick (#22637) 2026-11-17 18:53:11 +13:00
J. Nick Koston b5e379a9d4 [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog at 57600 baud (#22641) 2026-11-17 18:53:11 +13:00
J. Nick Kostonandpre-commit-ci-lite[bot] 05286dfd5d [api] Send queued entity states before DisconnectRequest on shutdown (#22625)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-17 18:53:11 +13:00
J. Nick Koston 36184f09aa [zephyr] Count micros() in microseconds and busy-wait in delayMicroseconds() (#22612) 2026-11-17 18:53:11 +13:00
Adam Matthews 449933891e [wifi] Clear the error flag when the adapter restart is skipped (#22797) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda a5bfa6dac3 [esp32_ble] Apply the Bluedroid workarounds to the ESP-IDF 6.1 releases that need them (#22806) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda 5aaa5b0552 [esp32_ble] Replace Bluedroid's sscanf callers on ESP-IDF 6 too (#22805) 2026-11-17 18:53:11 +13:00
J. Nick Koston 9ab090a818 [i2c] Refuse RP2040 writes larger than the Wire buffer instead of leaving the bus stuck (#22791) 2026-11-17 18:53:10 +13:00
J. Nick Koston 02d0bb56a6 [cc1101] Refuse begin_tx in packet mode (#22636) 2026-11-16 22:21:59 -06:00
185 changed files with 8277 additions and 3667 deletions

No files matched your search

+49 -1
View File
@@ -20,6 +20,9 @@ flagging in a review; read the matching skill for the detail behind any item.
Only raise findings that the diff actually introduces or changes. Do not ask for
drive-by cleanup of pre-existing code the PR did not touch.
For error paths that fail without telling the user (early returns, swallowed
errors, ignored results), the `silent-failure-review` skill has its own checklist.
## Scope: shared code does not ride a component PR
Check the file list first. A PR titled for one component (`[ld2450] ...`) must
@@ -117,7 +120,7 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| hand-written `set_x_sensor()` plus `x_sensor_` member | `SUB_SENSOR(x)`, `SUB_BINARY_SENSOR`, `SUB_TEXT_SENSOR`, `SUB_SWITCH`, ... |
| `if CONF_X in config: s = await sensor.new_sensor(config[CONF_X])` plus setter | `sensors = sensor.sub_sensors(config)` then `await sensors(CONF_X, hub.set_x_sensor)` |
| hand-written `{"a": MyEnum.MY_ENUM_A, ...}` dict | `MyEnum.options("a", "b", prefix="MY_ENUM_")` |
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>` |
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>`, `LengthFrameReader<N, FrameFormat<...>...>` |
| hand-rolled CRC, checksum or bit loop | `crc8`, `crc16`, `xor_bytes`, `sum16_bytes`, `encode_uint16`, ... (`esphome/core/helpers.h`) |
| integer split into buffer bytes by hand (`buf[0] = v >> 8; buf[1] = v;`) | `put_be16`/`24`/`32`, `put_le16`, `put_le32` (`esphome/core/helpers.h`) |
| bare `mark_failed()`, or `ESP_LOGE` then `mark_failed()` | `this->mark_failed(LOG_STR("reason"))` or `LOG_STR(ESP_LOG_MSG_COMM_FAIL)` |
@@ -125,6 +128,51 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| action or condition class that only forwards to the parent | `register_apply_action` / `register_apply_condition` |
| enum-to-string `switch` returning literals | `PROGMEM_STRING_TABLE` with `get_log_str` / `get_progmem_str` |
| `if (x := config.get(CONF_X)) is not None: cg.add(var.set_x(x))` | `cg.add_optional(var.set_x, config.get(CONF_X))`, when the setter takes the value unchanged |
| `x = (x & ~mask) \| (on ? mask : 0)` or a bit-reversal loop | `assign_bits(x, mask, on)`, `reverse_bits(x)` (`esphome/core/helpers.h`) |
| `x < lo ? lo : (x > hi ? hi : x)` | `std::clamp(x, lo, hi)` |
| I2C read, mask, write by hand; private 16-bit register byte helpers | `update_register`, `update_register16`, `read_byte_reg16`, `write_byte_reg16` |
| custom validator that checks which keys are set, or one schema with model checks | `cv.has_exactly_one_key`, `cv.has_at_most_one_key`, `cv.Inclusive`/`cv.Exclusive`, `cv.typed_schema` per model |
## Cleanups automated reviews keep missing
Multi-pass cleanup reviews of contributor PRs find these again and again, and single-pass reviews
almost never flag them. Look for each one explicitly; the matching `AGENTS.md` section 4 entry has the
detail.
- **Copies within the PR** (the most common finding): two functions, branches, platform files or tests
that differ in a constant or two. Ask for one helper, loop or table.
- **State that copies other state:** a `write_pending_` bool beside a timer (use the return value of
`cancel_timeout(ID)`), a `has_x_` bool beside `x_` (use `NAN` or a sentinel), an enum that can be worked
out from stored fields.
- **Dead guards:** null checks on members codegen always sets, `is_failed()` checks in `loop()`, range
checks the schema already enforces, `default:` in a `switch` over every value of an `enum class` the
component sets itself (not one cast from bus data), calls that set a member to its default
(`set_cs_pin(nullptr)`).
- **Member layout:** field order that leaves padding, `int`/`uint32_t` for values that fit a `uint8_t`,
an `enum class` without `: uint8_t`, several `bool` members that could share a byte. Each costs RAM per
instance.
- **C++ work that belongs in codegen:** scaling, clamping, checksums or register bytes computed at boot
from config values; ask for the plain value from `to_code`.
- **Two `switch` ladders for one mapping:** encode and decode of the same value pairs should share one
`static constexpr` table (`PROGMEM` on ESP8266).
- **Compile-time constants:** `static const` or `#define` with a constant value (use `static constexpr`),
constant tables not in `PROGMEM`, unused constants.
- **Code for one model or feature compiled into every build:** ask for a `cg.add_define()` emitted only
when the config uses it, with the runtime check inside the `#ifdef`.
- **Failure handling:** `mark_failed()` outside `setup()` (runtime failures set a warning that the next
success clears), an error enum that only picks a log message.
- **Logging** that does not follow https://developers.esphome.io/architecture/logging/: `ESP_LOGD` on every
reading, "Setting up" or "initialized" lines in `setup()`, a `dump_config()` made of single-line
`ESP_LOGCONFIG` calls where related lines fit one call, a name helper that returns `const char *` instead
of `const LogString *`.
- **Leaf classes** that are not `final`.
- **Unused helpers, includes and imports** left behind; lint does not catch most of them.
- **Comments that restate the code** or tell its history: a block comment that walks through the next
ten lines, a docstring that repeats the signature, a derivation that a one-line note plus a datasheet
section would cover.
- **Tests:** near-identical test functions that differ only in inputs (ask for `pytest.mark.parametrize`
or a table-driven gtest), tests that repeat another test, test YAML that sets options to their defaults.
## Python conventions
@@ -0,0 +1,71 @@
---
name: silent-failure-review
description: Find code paths in a branch's diff that fail without telling the user - early returns, swallowed errors, ignored return values, half-done cleanup, and checks that are only safe under an unstated assumption. Use when asked for a silent failure review or before pushing a PR for review.
---
# Silent failure review
Report only. Do not edit files.
## Scope
The diff of the checked-out branch against its base. Fetch the base first (`git fetch upstream dev`, or
`git fetch origin dev` when there is no `upstream` remote); a stale base pulls in commits the branch only merged.
Then run `git merge-base upstream/dev HEAD` (or `origin/dev`) on its own. If it fails or prints nothing (often a
shallow clone; `git fetch --unshallow` fixes that), say the review could not run and stop; never report "no
findings" then. Diff against that commit with `git diff <base>`. The diff includes uncommitted changes but not
untracked files, so also read in full every file `git status --porcelain --untracked-files=all` lists as `??`.
Use another branch only if the user names one. If neither remote exists, say so and stop. Read each changed
function in full, and its callers, not just the hunks. When a failure depends on how a library call behaves,
read that library's code too.
## What to look for
1. **Early returns and skips:** a `return` or `continue` taken before a check or a fetch. Name the assumption
it relies on and the case that breaks it (a later release, a lost file, an older install).
2. **Swallowed errors:** `except` that logs, passes or returns a default; `OSError` tolerated where the next
step needs the file. In C++: an error code mapped to a default, or a status flag that is never set.
3. **Ignored results:** a `False`, `None`, exit code, `bool` or `ErrorCode` that the caller does not check.
4. **Half-done state:** a failure between two writes that leaves a marker, stamp, lock or filter saying
something is done when it is not; cleanup missing on an error path.
5. **Stale stored state:** markers, stamps or saved preferences (NVS, flash) written by an older version that
the new code trusts.
6. **Unclear late failure:** an error that surfaces later (CMake, compile, boot) instead of where it starts,
with a message that does not point back to the cause.
7. **Defaults standing in for errors:** `x or default`, `.get(key, default)` or an empty object takes the
place of a value that is missing or could not be read, and the code carries on as if it were real.
8. **Unwatched work:** a thread, task or subprocess is started and nothing ever looks at how it ended.
9. **Wrong value on an error branch:** the error is detected, but the branch returns success, `None` or the
wrong code instead of passing it on.
10. **State reset or skipped:** for each counter, flag, retry or timeout the diff adds or changes, find every
place that writes it, and check that no path resets or skips it before it can do its job.
11. **Boundaries:** length and buffer comparisons (`>=` against `>`, `len` against `len + 1`), the exact-fit
case and the empty case.
12. **Unjudged results:** a test or script that prints a result but never fails on it.
Moved code counts too: if the original had the same flaw, say so, but still report it. Report only flaws in
changed or moved lines; unchanged callers are context. If the branch has an open PR (`gh pr view --json number`
finds it), read its reviews (`gh pr view <n> --comments` and
`gh api --paginate repos/esphome/esphome/pulls/<n>/comments`) and skip what they already raised.
Before reporting a candidate, follow it to the line that proves it and quote that line. If you cannot
confirm it, drop it or mark it as likely.
## Skip
- Code that ignores a failure and has a comment explaining why.
- Tests that provoke an error and check for it.
- Optional tidy-up steps (removing a temp file, say) that may fail with only a log line.
## Report
One entry per finding, most severe first:
- **HIGH / MEDIUM / LOW** - one-line title, `file:line`. HIGH: wrong result or lost data. MEDIUM: a
misleading or delayed failure. LOW: affects only logs or diagnostics.
- **Confidence:** confirmed, or likely and why it could not be confirmed.
- **Risk:** the concrete input or state, and what the user sees.
- **Fix:** the smallest change.
- **Test:** the test that fails before the fix, or for on-device code, the steps to reproduce it on a board.
No findings: say so in one line. Keep the report short; no summary of what the PR does.
+30 -2
View File
@@ -66,6 +66,8 @@ file does, and it is the authority when they disagree. The most useful starting
* `breaking-changes`: what is public API, deprecation patterns and migration notes.
* `pr-workflow`, `code-review`, `hardware-test`, `display-test`: creating PRs, reviewing them, and testing
on real boards and panels.
* `silent-failure-review`: code paths in a branch's diff that fail without telling the user, checked
before a PR goes up for review.
* **Formatting:**
* **Python:** Uses `ruff` for linting and formatting. Configuration is in `pyproject.toml`.
@@ -244,7 +246,11 @@ file does, and it is the authority when they disagree. The most useful starting
`time::decode_bcd_calendar<LAYOUT>` and `encode_bcd_calendar<LAYOUT>` with `EPSON_BCD_CALENDAR`,
`DS_BCD_CALENDAR` or `PCF_BCD_CALENDAR`.
* **Bus helpers:** UART drains with `read_available(on_byte)` and `discard_available()`, text lines with
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`; I2C has `update_register`,
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`, frames that give their own length
with `LengthFrameReader<N, FrameFormat<FrameHeader<...>, PayloadLengthU16LE<LengthField{...}>>...>` fed by
`read_frames(reader, handler, now, last_rx)`, which also gives up a frame stalled by a corrupt length;
I2C has `update_register`,
`update_register16`, `read_byte_reg16` and `write_byte_reg16` for 16-bit register addresses,
`write_registers` (PROGMEM `I2CRegValue` table), `check_chip_id` and `read_bytes_16_le`.
`if (!this->status_comm_result(ok)) return;` sets or clears the warning; an earlier step of a multi-step
poll uses `status_comm_check(ok)`, which only sets it, so the last step must clear it; in `setup()`,
@@ -309,6 +315,27 @@ file does, and it is the authority when they disagree. The most useful starting
text::Text *source_{nullptr};
};
```
* **No state that copies other state:** a flag that mirrors a timer, a `has_x_` bool beside `x_`, or an enum
that can be worked out from fields already stored is a second source of truth. Use the source:
`pending = this->cancel_timeout(ID)`, an unset value of `NAN` or an out-of-range sentinel.
* **No dead guards:** do not check what the caller or core already guarantees: a member that codegen always
sets, `is_failed()` in `loop()` (core stops calling it), a value the config validation already limits, a
`default:` in a `switch` over every value of an `enum class` the component sets itself (keep it when the
value is cast from bus data).
* **Member layout:** order fields so the compiler adds no padding (usually largest first), store small codes
as `uint8_t`, declare `enum class X : uint8_t`, and pack flags into one byte.
* **Work out constants in Python:** math that only depends on the configuration (register bytes, scale
factors, thresholds, checksums) is done in `to_code` and passed as a plain value, not done in C++ at
boot.
* **One table for both directions:** a value that is encoded and decoded through the same mapping uses one
`static constexpr` (`PROGMEM` on ESP8266) table of `{value, code}` pairs, not two `switch` ladders.
* **Logging:** follow https://developers.esphome.io/architecture/logging/ for log levels and `dump_config()`.
In short: a reading is logged with `ESP_LOGV`, not `ESP_LOGD` on every update; `setup()` logs no
"Setting up" or "initialized" line (core logs setup); `dump_config()` combines related lines into one
`ESP_LOGCONFIG` call, within the 512-byte log buffer.
* **Leaf classes are `final`:** a component or entity class nothing derives from is declared `final`.
* **No copies within the PR:** two functions, branches or platform files that differ in a constant or two
become one helper, loop or table; helpers, includes and imports nothing uses are deleted.
* **Component Code Generation:** every component's `__init__.py` defines `DOMAIN` (its own name, checked by
CI). Hub entities go in platform files (`sensor.py`, ...) that take the hub's id, not under the hub's own
@@ -355,7 +382,8 @@ file does, and it is the authority when they disagree. The most useful starting
`script/test_build_components -c <component>`. Never define buses directly in test YAML: include the
shared packages from `tests/test_build_components/common/` with dict-style `packages:`. Test file naming,
`validate.*.yaml` config-only tests, CI grouping, C++ unit tests and integration tests are in the
`component-tests` skill.
`component-tests` skill. Tests that differ only in their inputs are one `pytest.mark.parametrize` test
or a table-driven gtest.
* **Debugging and Troubleshooting:**
* **Debug Tools:**
+4
View File
@@ -489,10 +489,12 @@ esphome/components/pca9505/* @ajfriesen @ssieb
esphome/components/pca9554/* @bdraco @clydebarrow @hwstar
esphome/components/pcf85063/* @brogon
esphome/components/pcf8563/* @KoenBreeman
esphome/components/pcm1863/* @anabolyc
esphome/components/pcm5122/* @remcom
esphome/components/pd_pioneer_ir/* @martinsah
esphome/components/pi4ioe5v6408/* @jesserockz
esphome/components/pid/* @OttoWinter
esphome/components/pioneer_wt/* @martinsah
esphome/components/pipsolar/* @andreashergert1984
esphome/components/pixoo/* @jesserockz
esphome/components/pm1006/* @habbie
@@ -699,6 +701,7 @@ esphome/components/toshiba/* @kbx81
esphome/components/touchscreen/* @jesserockz @nielsnl68
esphome/components/tsl2591/* @wjcarpenter
esphome/components/tt21100/* @kroimon
esphome/components/tuya/* @dwmw2 @ssieb
esphome/components/tuya/binary_sensor/* @jesserockz
esphome/components/tuya/climate/* @jesserockz
esphome/components/tuya/number/* @frankiboy1
@@ -735,6 +738,7 @@ esphome/components/veml7700/* @latonita
esphome/components/version/* @esphome/core
esphome/components/vevor_dtx/* @Bofr5555
esphome/components/vl53l1x/* @will-tm
esphome/components/vl6180x/* @NonaSuomy
esphome/components/vnc/* @MindFreeze
esphome/components/voice_assistant/* @jesserockz @kahrendt
esphome/components/wake_on_lan/* @clydebarrow @willwill2will54
@@ -2,7 +2,6 @@
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iterator>
#include "esphome/core/application.h"
@@ -14,13 +13,6 @@ namespace esphome::airton_serial {
ESPHOME_LOG_TAG(TAG, "airton_serial.climate");
static constexpr uint8_t SYNC_BYTE = 0x7A;
static constexpr uint8_t LENGTH_POS = 4;
static constexpr uint8_t OPCODE_POS = 7;
static constexpr uint8_t MIN_FRAME_LEN = OPCODE_POS + 1 + 2; // Up to the opcode, then the CRC
// A partial frame left this long without a new byte is not a frame start.
static constexpr uint32_t FRAME_GAP_MS = 50;
static constexpr uint8_t ADDR_MODULE = 0x21;
static constexpr uint8_t ADDR_DISPLAY = 0xD1;
static constexpr uint8_t ADDR_BOARD = 0xD5;
@@ -121,58 +113,15 @@ void AirtonSerialClimate::setup() {
void AirtonSerialClimate::loop() {
const uint32_t now = App.get_loop_component_start_time();
bool received = false;
this->read_available([this, &received](uint8_t byte) {
received = true;
this->handle_byte_(byte);
});
if (received) {
this->last_rx_ms_ = now;
} else if (this->rx_pos_ > 0 && now - this->last_rx_ms_ >= FRAME_GAP_MS) {
// A corrupt length can hold back complete frames behind it; look for them in what is buffered.
while (this->rx_pos_ > 0)
this->drop_first_byte_();
auto accept = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames(this->reader_, accept, now, this->last_rx_ms_);
}
bool AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
if (crc16(data, len - 2) != encode_uint16(data[len - 2], data[len - 1])) {
ESP_LOGW(TAG, "Bad CRC on %u-byte frame", static_cast<unsigned>(len));
return false;
}
}
void AirtonSerialClimate::handle_byte_(uint8_t byte) {
// Bytes are checked as they arrive, so rx_pos_ stays below the longest frame length.
this->rx_buffer_[this->rx_pos_++] = byte;
this->scan_buffer_();
}
void AirtonSerialClimate::drop_first_byte_() {
this->rx_pos_--;
std::memmove(this->rx_buffer_.data(), this->rx_buffer_.data() + 1, this->rx_pos_);
this->scan_buffer_();
}
void AirtonSerialClimate::scan_buffer_() {
const uint8_t *buf = this->rx_buffer_.data();
while (this->rx_pos_ > 0) {
uint8_t drop = 1;
if (buf[0] == SYNC_BYTE && (this->rx_pos_ < 2 || buf[1] == SYNC_BYTE)) {
if (this->rx_pos_ <= LENGTH_POS)
return;
const uint8_t len = buf[LENGTH_POS];
if (len >= MIN_FRAME_LEN && len <= MAX_FRAME_LEN) {
if (this->rx_pos_ < len)
return;
if (crc16(buf, len - 2) == encode_uint16(buf[len - 2], buf[len - 1])) {
this->handle_frame_(buf, len);
drop = len;
} else {
ESP_LOGW(TAG, "Bad CRC on %u-byte frame", len);
}
}
}
// Not a frame start, or a bad frame: look for the next start after its first byte.
this->rx_pos_ -= drop;
std::memmove(this->rx_buffer_.data(), buf + drop, this->rx_pos_);
}
}
void AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
const uint8_t opcode = data[OPCODE_POS];
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
if (opcode == OP_A3_STATE || opcode == OP_AC_POLL) {
@@ -181,7 +130,7 @@ void AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
}
#endif
if (data[3] != ADDR_MODULE)
return;
return true;
if (data[2] == ADDR_BOARD) {
if (len == 34 && opcode == OP_A3_STATE) {
this->handle_a3_(data);
@@ -191,6 +140,7 @@ void AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
} else if (data[2] == ADDR_DISPLAY && len == 13 && opcode == OP_A4_ACK) {
ESP_LOGD(TAG, "A4 acknowledgement from display");
}
return true;
}
void AirtonSerialClimate::handle_a3_(const uint8_t *data) {
@@ -1,12 +1,12 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include "esphome/components/climate/climate.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/component.h"
#include "esphome/core/frame_reader.h"
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor_with_dedup.h"
@@ -24,6 +24,9 @@ static constexpr uint8_t FLAG_HEALTH = 0x10;
static constexpr uint8_t FLAG_SLEEP = 0x02;
static constexpr uint8_t FLAG_ECO = 0x01;
static constexpr uint8_t SYNC_BYTE = 0x7A;
static constexpr uint8_t LENGTH_POS = 4;
static constexpr uint8_t OPCODE_POS = 7;
static constexpr uint8_t MAX_FRAME_LEN = 64;
/// Climate on the Airton serial bus. The ESP takes the place of the original Wi-Fi module (address 0x21):
@@ -61,16 +64,17 @@ class AirtonSerialClimate final : public uart::UARTDevice, public climate::Clima
bool can_send_command_();
void send_command_();
void write_frame_(uint8_t *frame, size_t len);
void handle_byte_(uint8_t byte);
void drop_first_byte_();
void scan_buffer_();
void handle_frame_(const uint8_t *data, size_t len);
/// Returns false for a frame that fails the CRC
bool handle_frame_(const uint8_t *data, size_t len);
void handle_a3_(const uint8_t *data);
void handle_ac_(const uint8_t *data);
void publish_settings_();
std::array<uint8_t, MAX_FRAME_LEN> rx_buffer_;
uint8_t rx_pos_{0};
// 7A 7A, ..., whole-frame length at 4, opcode, ..., CRC (2); the shortest runs up to the opcode
LengthFrameReader<MAX_FRAME_LEN,
FrameFormat<FrameHeader<SYNC_BYTE, SYNC_BYTE>, FrameLengthU8<LengthField{.offset = LENGTH_POS}>,
FrameMinLength<OPCODE_POS + 3>>>
reader_;
uint8_t flags_{FLAG_DISPLAY};
bool state_received_{false};
uint8_t swing_{0}; // Raw swing byte
+39 -88
View File
@@ -5,6 +5,7 @@
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include <array>
#include <cinttypes>
#include <cmath>
@@ -25,8 +26,6 @@ static constexpr uint32_t APC1_COLD_BOOT_INIT_DELAY_MS = 2000;
static constexpr uint32_t APC1_INIT_RETRY_INTERVAL_MS = 10000;
// Active mode streams a frame every second; this long without one means the sensor stopped
static constexpr uint32_t APC1_NO_DATA_TIMEOUT_MS = 15000;
// Drop a partial frame when the bytes stop mid-way
static constexpr uint32_t APC1_RX_IDLE_TIMEOUT_MS = 200;
void APC1Component::setup() {
if (this->set_pin_ != nullptr) {
@@ -99,80 +98,40 @@ void APC1Component::loop() {
}
}
if (this->rx_index_ > 0 && now - this->last_transmission_ > APC1_RX_IDLE_TIMEOUT_MS) {
ESP_LOGV(TAG, "Timed out waiting for data, resetting buffer");
this->rx_index_ = 0;
}
this->read_available([this, now](uint8_t byte) {
this->last_transmission_ = now;
if (this->rx_index_ == 0) {
if (byte == APC1_HEADER_1) {
this->rx_buffer_[this->rx_index_++] = byte;
}
return;
}
if (this->rx_index_ == 1) {
if (byte == APC1_HEADER_2) {
this->rx_buffer_[this->rx_index_++] = byte;
} else if (byte != APC1_HEADER_1) {
this->rx_index_ = 0;
}
return;
}
this->rx_buffer_[this->rx_index_++] = byte;
if (this->rx_index_ < APC1_FRAME_HEADER_SIZE) {
return;
}
// The payload carries at least the checksum and must fit the buffer; checking it before the sum keeps a
// corrupt length from wrapping the total and walking past the buffer
const uint16_t payload_len = encode_uint16(this->rx_buffer_[2], this->rx_buffer_[3]);
if (payload_len < 2 || payload_len > this->rx_buffer_.size() - APC1_FRAME_HEADER_SIZE) {
ESP_LOGW(TAG, "Invalid frame length: %u", payload_len);
this->rx_index_ = 0;
return;
}
const uint8_t total_len = payload_len + APC1_FRAME_HEADER_SIZE;
if (this->rx_index_ == total_len) {
this->parse_frame_(total_len);
this->rx_index_ = 0;
}
});
auto handle = [this](const uint8_t *frame, size_t len) { return this->parse_frame_(frame, len); };
this->read_frames(this->reader_, handle, now, this->last_transmission_);
}
void APC1Component::parse_frame_(uint16_t total_len) {
uint16_t expected_checksum = encode_uint16(this->rx_buffer_[total_len - 2], this->rx_buffer_[total_len - 1]);
uint16_t calculated_checksum = sum16_bytes(this->rx_buffer_.data(), total_len - 2);
bool APC1Component::parse_frame_(const uint8_t *frame, uint8_t total_len) {
uint16_t expected_checksum = encode_uint16(frame[total_len - 2], frame[total_len - 1]);
uint16_t calculated_checksum = sum16_bytes(frame, total_len - 2);
if (expected_checksum != calculated_checksum) {
ESP_LOGW(TAG, "APC1 checksum mismatch: calculated 0x%04X != expected 0x%04X", calculated_checksum,
expected_checksum);
return;
return false;
}
if (total_len == APC1_FRAME_SIZE_MEASUREMENT) {
this->parse_measurement_frame_();
this->parse_measurement_frame_(frame);
} else if (total_len == APC1_FRAME_SIZE_DEVICE_INFO) {
this->parse_device_info_frame_();
this->parse_device_info_frame_(frame);
} else if (total_len == APC1_FRAME_SIZE_COMMAND_RESPONSE) {
ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", this->rx_buffer_[4], this->rx_buffer_[5]);
ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", frame[4], frame[5]);
} else {
ESP_LOGD(TAG, "Received frame of unknown length %u", total_len);
}
return true;
}
// One message per error bit, bit 0 first
PROGMEM_STRING_TABLE(ErrorStrings, "Fan restart error (too many restarts)", "Fan speed low", "Photodiode fault",
"Fan stopped / startup error", "Laser fault", "VOC sensor fault", "RHT sensor fault");
void APC1Component::parse_measurement_frame_() {
void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
const uint32_t now = App.get_loop_component_start_time();
this->last_valid_frame_ = now;
uint8_t error_code = this->rx_buffer_[APC1_MEASUREMENT_OFFSET_ERROR_CODE];
uint8_t error_code = frame[APC1_MEASUREMENT_OFFSET_ERROR_CODE];
if (error_code != this->last_error_code_) {
if (error_code != 0) {
for (uint8_t bit = 0; bit < ErrorStrings::COUNT; bit++) {
@@ -189,7 +148,7 @@ void APC1Component::parse_measurement_frame_() {
PUBLISH_STATE(this->error_code_sensor_, error_code);
}
uint8_t aqi = this->rx_buffer_[APC1_MEASUREMENT_OFFSET_AQI];
uint8_t aqi = frame[APC1_MEASUREMENT_OFFSET_AQI];
if (aqi == 0) {
if (!this->gas_warming_up_) {
this->gas_warming_up_ = true;
@@ -203,38 +162,31 @@ void APC1Component::parse_measurement_frame_() {
// Measurement payload data (bytes 4-57): big-endian sensor readings.
// The values below feed the debug summary, so they are always decoded; every
// other reading is only decoded when its sensor is configured.
const auto u16 = [this](uint8_t offset) {
return encode_uint16(this->rx_buffer_[offset], this->rx_buffer_[offset + 1]);
};
const auto u32 = [this](uint8_t offset) {
return encode_uint32(this->rx_buffer_[offset], this->rx_buffer_[offset + 1], this->rx_buffer_[offset + 2],
this->rx_buffer_[offset + 3]);
};
uint16_t pm_1_0 = u16(10);
uint16_t pm_2_5 = u16(12);
uint16_t pm_10_0 = u16(14);
uint16_t tvoc = u16(28);
uint16_t eco2 = u16(30);
float temp_comp = static_cast<int16_t>(u16(34)) / 10.0f;
float hum_comp = u16(36) / 10.0f;
uint16_t pm_1_0 = encode_value<uint16_t>(frame + 10);
uint16_t pm_2_5 = encode_value<uint16_t>(frame + 12);
uint16_t pm_10_0 = encode_value<uint16_t>(frame + 14);
uint16_t tvoc = encode_value<uint16_t>(frame + 28);
uint16_t eco2 = encode_value<uint16_t>(frame + 30);
float temp_comp = encode_value<int16_t>(frame + 34) / 10.0f;
float hum_comp = encode_value<uint16_t>(frame + 36) / 10.0f;
ESP_LOGD(TAG, "APC1: PM1.0: %u, PM2.5: %u, PM10: %u, TVOC: %u, eCO2: %u, AQI: %u, Temp: %.1f°C, Hum: %.1f%%", pm_1_0,
pm_2_5, pm_10_0, tvoc, eco2, aqi, temp_comp, hum_comp);
PUBLISH_STATE(this->pm_1_0_std_sensor_, u16(4));
PUBLISH_STATE(this->pm_2_5_std_sensor_, u16(6));
PUBLISH_STATE(this->pm_10_0_std_sensor_, u16(8));
PUBLISH_STATE(this->pm_1_0_std_sensor_, encode_value<uint16_t>(frame + 4));
PUBLISH_STATE(this->pm_2_5_std_sensor_, encode_value<uint16_t>(frame + 6));
PUBLISH_STATE(this->pm_10_0_std_sensor_, encode_value<uint16_t>(frame + 8));
PUBLISH_STATE(this->pm_1_0_sensor_, pm_1_0);
PUBLISH_STATE(this->pm_2_5_sensor_, pm_2_5);
PUBLISH_STATE(this->pm_10_0_sensor_, pm_10_0);
PUBLISH_STATE(this->pm_0_3um_sensor_, u16(16));
PUBLISH_STATE(this->pm_0_5um_sensor_, u16(18));
PUBLISH_STATE(this->pm_1_0um_sensor_, u16(20));
PUBLISH_STATE(this->pm_2_5um_sensor_, u16(22));
PUBLISH_STATE(this->pm_5_0um_sensor_, u16(24));
PUBLISH_STATE(this->pm_10_0um_sensor_, u16(26));
PUBLISH_STATE(this->pm_0_3um_sensor_, encode_value<uint16_t>(frame + 16));
PUBLISH_STATE(this->pm_0_5um_sensor_, encode_value<uint16_t>(frame + 18));
PUBLISH_STATE(this->pm_1_0um_sensor_, encode_value<uint16_t>(frame + 20));
PUBLISH_STATE(this->pm_2_5um_sensor_, encode_value<uint16_t>(frame + 22));
PUBLISH_STATE(this->pm_5_0um_sensor_, encode_value<uint16_t>(frame + 24));
PUBLISH_STATE(this->pm_10_0um_sensor_, encode_value<uint16_t>(frame + 26));
PUBLISH_STATE(this->tvoc_sensor_, tvoc);
PUBLISH_STATE(this->eco2_sensor_, eco2);
@@ -243,20 +195,19 @@ void APC1Component::parse_measurement_frame_() {
PUBLISH_STATE(this->temperature_sensor_, temp_comp);
PUBLISH_STATE(this->humidity_sensor_, hum_comp);
PUBLISH_STATE(this->raw_temperature_sensor_, static_cast<int16_t>(u16(38)) / 10.0f);
PUBLISH_STATE(this->raw_humidity_sensor_, u16(40) / 10.0f);
PUBLISH_STATE(this->raw_temperature_sensor_, encode_value<int16_t>(frame + 38) / 10.0f);
PUBLISH_STATE(this->raw_humidity_sensor_, encode_value<uint16_t>(frame + 40) / 10.0f);
PUBLISH_STATE(this->rs0_sensor_, u32(42));
PUBLISH_STATE(this->rs2_sensor_, u32(50));
PUBLISH_STATE(this->rs3_sensor_, u32(54));
PUBLISH_STATE(this->rs0_sensor_, encode_value<uint32_t>(frame + 42));
PUBLISH_STATE(this->rs2_sensor_, encode_value<uint32_t>(frame + 50));
PUBLISH_STATE(this->rs3_sensor_, encode_value<uint32_t>(frame + 54));
}
void APC1Component::parse_device_info_frame_() {
const uint8_t *serial = this->rx_buffer_.data() + APC1_DEVICE_INFO_OFFSET_SERIAL;
uint16_t fw_version =
encode_uint16(this->rx_buffer_[APC1_DEVICE_INFO_OFFSET_FW], this->rx_buffer_[APC1_DEVICE_INFO_OFFSET_FW + 1]);
void APC1Component::parse_device_info_frame_(const uint8_t *frame) {
const uint8_t *serial = frame + APC1_DEVICE_INFO_OFFSET_SERIAL;
uint16_t fw_version = encode_uint16(frame[APC1_DEVICE_INFO_OFFSET_FW], frame[APC1_DEVICE_INFO_OFFSET_FW + 1]);
ESP_LOGI(TAG, "APC1: Module: %.6s, Serial: %08" PRIX32 "%08" PRIX32 ", Firmware: 0x%04X (%u)",
reinterpret_cast<const char *>(this->rx_buffer_.data() + APC1_DEVICE_INFO_OFFSET_MODULE),
reinterpret_cast<const char *>(frame + APC1_DEVICE_INFO_OFFSET_MODULE),
encode_uint32(serial[0], serial[1], serial[2], serial[3]),
encode_uint32(serial[4], serial[5], serial[6], serial[7]), fw_version, fw_version);
}
+10 -7
View File
@@ -1,12 +1,11 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/hal.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
#include <array>
namespace esphome::apc1 {
static constexpr uint8_t APC1_HEADER_1 = 0x42;
@@ -79,17 +78,21 @@ class APC1Component final : public uart::UARTDevice, public Component {
void initialize_device_();
/// Restarts the no-data watchdog so a mode change gets the same grace period as a cold boot
void arm_watchdog_();
void parse_frame_(uint16_t total_len);
void parse_measurement_frame_();
void parse_device_info_frame_();
/// Returns false for a frame that fails the checksum
bool parse_frame_(const uint8_t *frame, uint8_t total_len);
void parse_measurement_frame_(const uint8_t *frame);
void parse_device_info_frame_(const uint8_t *frame);
GPIOPin *set_pin_{nullptr};
GPIOPin *reset_pin_{nullptr};
uint32_t last_transmission_{0};
uint32_t last_valid_frame_{0};
uint32_t last_init_attempt_{0};
std::array<uint8_t, APC1_FRAME_SIZE_MEASUREMENT> rx_buffer_{};
uint8_t rx_index_{0};
// 42 4D, payload length (2, BE), payload ending in its checksum (2)
LengthFrameReader<APC1_FRAME_SIZE_MEASUREMENT,
FrameFormat<FrameHeader<APC1_HEADER_1, APC1_HEADER_2>, PayloadLengthU16BE<LengthField{.offset = 2}>,
FrameMinLength<APC1_FRAME_HEADER_SIZE + 2>>>
reader_;
uint8_t last_error_code_{0xFF};
bool active_mode_{true};
bool idle_{false};
+1 -1
View File
@@ -385,7 +385,7 @@ async def to_code(config: ConfigType) -> None:
# Adds a define and IDF component for legacy `audio_decoder.cpp`.
if data.flac_support:
cg.add_define("USE_AUDIO_FLAC_SUPPORT")
add_idf_component(name="esphome/micro-flac", ref="0.3.0")
add_idf_component(name="esphome/micro-flac", ref="0.3.1")
_emit_memory_pair(
data.flac.buffer_memory,
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
+70 -136
View File
@@ -1,5 +1,6 @@
#include "bmi270.h"
#include "bmi270_config.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include "esphome/core/progmem.h"
@@ -21,48 +22,40 @@ static constexpr size_t MAX_I2C_BUFFER_SIZE = 32;
static constexpr size_t MAX_I2C_BUFFER_SIZE = 256;
#endif
// Configuration blob upload
// The BMI270 requires a firmware config blob to be written to its internal
// memory after every power-on before sensors can be used.
bool BMI270Component::load_config_file_() {
// 1. Disable advanced power-save so the config port is accessible
// The config port is only reachable with advanced power save off
if (!this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_ADV_POWER_SAVE_OFF))
return false;
delay(1);
// 2. Prepare config load: write 0x00 to INIT_CTRL to start
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_START))
return false;
// 3. Burst-write the config in pages
const uint8_t *cfg = BMI270_CONFIG_FILE;
constexpr size_t cfg_len = sizeof(BMI270_CONFIG_FILE);
// The register byte goes first, so each burst is copied once and sent with write()
uint8_t buf[1 + MAX_I2C_BUFFER_SIZE];
buf[0] = BMI270_REG_INIT_DATA;
size_t index = 0;
while (index != cfg_len) {
// Set the page address in INIT_ADDR registers
uint8_t addr_lsb = (uint8_t) ((index / 2) & 0x0F);
uint8_t addr_msb = (uint8_t) ((index / 2) >> 4);
if (!this->write_byte(BMI270_REG_INIT_ADDR_0, addr_lsb))
return false;
if (!this->write_byte(BMI270_REG_INIT_ADDR_0 + 1, addr_msb))
// INIT_ADDR_0 takes the word address bits 0-3 and INIT_ADDR_1 bits 4-11
const uint8_t addr[2] = {static_cast<uint8_t>((index / 2) & 0x0F), static_cast<uint8_t>((index / 2) >> 4)};
if (this->write_register(BMI270_REG_INIT_ADDR_0, addr, sizeof(addr)) != i2c::ERROR_OK)
return false;
// Write a burst of up to the maximum allowed size
size_t burst = clamp_at_most(cfg_len - index, MAX_I2C_BUFFER_SIZE);
if (this->write_register(BMI270_REG_INIT_DATA, cfg + index, burst) != i2c::ERROR_OK)
progmem_memcpy(buf + 1, BMI270_CONFIG_FILE + index, burst);
if (this->write(buf, burst + 1) != i2c::ERROR_OK)
return false;
index += burst;
// 256 bursts at 50 kHz, or through an I2C multiplexer, outlast the ESP8266 soft watchdog
App.feed_wdt();
}
// 4. Signal end of config load
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_DONE))
return false;
delay(20); // spec: wait ≥20 ms for init to complete
delay(20); // The datasheet asks for at least 20 ms before INTERNAL_STATUS is valid
// 5. Check INTERNAL_STATUS: bit[0:3] should be 0x01 ("initialisation OK")
uint8_t status = 0;
if (!this->read_byte(BMI270_REG_INTERNAL_STATUS, &status))
return false;
@@ -73,74 +66,52 @@ bool BMI270Component::load_config_file_() {
return true;
}
// setup() ─
void BMI270Component::setup() {
MotionComponent::setup();
// 1. Verify chip ID
if (!this->check_chip_id(this, BMI270_REG_CHIP_ID, BMI270_CHIP_ID_VALUE))
return;
// 2. Soft-reset via CMD register (0x7E = 0xB6)
if (!this->setup_check(this->write_byte(BMI270_REG_CMD, BMI270_CMD_SOFT_RESET)))
return;
delay(20);
// 4. Upload the configuration blob
if (!this->setup_check(load_config_file_(), LOG_STR("Config file upload failed")))
return;
ESP_LOGD(TAG, "Config blob uploaded ✓");
// 5. Configure accelerometer
// ACC_CONF: ODR | BWP(0x2 = normal avg4) | perf_mode(1)
uint8_t acc_conf =
(uint8_t) (accel_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf)))
return;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_RANGE, (uint8_t) accel_range_)))
if (!this->setup_check(this->load_config_file_(), LOG_STR("Config file upload failed")))
return;
// 6. Configure gyroscope
// GYR_CONF: ODR | BWP(0x2 = normal) | noise_perf(1) | filter_perf(1)
uint8_t gyr_conf = (uint8_t) (gyro_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_CONF, gyr_conf)))
return;
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_RANGE, (uint8_t) gyro_range_)))
return;
// 7. Enable accelerometer, gyroscope, and temperature sensor
// PWR_CTRL bits: temp_en[3] | gyr_en[2] | acc_en[1]
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
// Normal filter bandwidth; performance mode for the accelerometer, noise and filter performance for the gyroscope
const uint8_t acc_conf =
this->accel_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
const uint8_t gyr_conf = this->gyro_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf) &&
this->write_byte(BMI270_REG_ACC_RANGE, this->accel_range_) &&
this->write_byte(BMI270_REG_GYR_CONF, gyr_conf) &&
this->write_byte(BMI270_REG_GYR_RANGE, this->gyro_range_) &&
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
return;
delay(5);
// 8. Re-enable advanced power save (optional; keeps current low between reads)
// Disabled here for simplicity – leave in performance mode
// bit1 = fifo_self_wakeup
// Advanced power save stays off; FIFO self-wakeup on
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_FIFO_SELF_WAKEUP)))
return;
// 9. Optionally bring up whatever is wired to the aux interface.
// This is entirely additive: it is off by default, and failure only disables
// magnetometer reporting rather than the whole component.
#ifdef USE_BMI270_BMM150
// A missing magnetometer only disables magnetometer reporting
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
this->magnetometer_ready_ = this->setup_magnetometer_();
const LogString *failed_step = this->setup_magnetometer_();
this->magnetometer_ready_ = failed_step == nullptr;
if (!this->magnetometer_ready_) {
ESP_LOGW(TAG, "BMM150 magnetometer setup failed; continuing without it");
ESP_LOGW(TAG, "BMM150 magnetometer setup failed at %s; continuing without it", LOG_STR_ARG(failed_step));
}
}
#endif
ESP_LOGCONFIG(TAG, "BMI270 initialised successfully");
}
#ifdef USE_BMI270_BMM150
bool BMI270Component::wait_for_aux_idle_(uint32_t timeout_ms) {
// The STATUS aux-busy bit is set while an aux transaction is in flight. Aux transaction
// duration depends on the attached device's own timing, so poll with a bounded
// timeout instead of guessing a fixed delay.
static_assert(BMM150_TRIM_BLOCK_LEN == BMI270_AUX_DATA_LEN, "each trim block is one aux read");
bool BMI270Component::wait_for_aux_idle_() {
static constexpr uint32_t AUX_IDLE_TIMEOUT_MS = 20;
uint32_t start = millis();
while (true) {
uint8_t status = 0;
@@ -148,98 +119,63 @@ bool BMI270Component::wait_for_aux_idle_(uint32_t timeout_ms) {
return false;
if ((status & BMI270_STATUS_AUX_BUSY) == 0)
return true;
if (millis() - start >= timeout_ms)
if (millis() - start >= AUX_IDLE_TIMEOUT_MS)
return false;
delay(1);
}
}
bool BMI270Component::write_aux_register_(uint8_t reg, uint8_t value) {
if (!this->write_byte(BMI270_REG_AUX_WR_DATA, value))
return false;
if (!this->write_byte(BMI270_REG_AUX_WR_ADDR, reg))
return false;
return this->wait_for_aux_idle_(20);
return this->write_byte(BMI270_REG_AUX_WR_DATA, value) && this->write_byte(BMI270_REG_AUX_WR_ADDR, reg) &&
this->wait_for_aux_idle_();
}
bool BMI270Component::read_aux_block_(uint8_t reg, uint8_t *buf) {
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, reg))
return false;
if (!this->wait_for_aux_idle_(20))
return false;
return this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
return this->write_byte(BMI270_REG_AUX_RD_ADDR, reg) && this->wait_for_aux_idle_() &&
this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
}
bool BMI270Component::read_magnetometer_trim_() {
uint8_t regs[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, regs + i * BMM150_TRIM_BLOCK_LEN))
return false;
}
this->mag_trim_ = bmm150_parse_trim(regs);
return true;
}
bool BMI270Component::setup_magnetometer_() {
// Sequence adapted from the Bosch BMI270 aux-interface protocol: enable the secondary
// I2C master in manual mode, point it at the BMM150's address, power the BMM150 up
// and soft-reset it, verify its chip ID, read its factory trim values, put it in
// normal/30Hz mode, then switch the aux interface to auto-burst mode so BMI270 keeps
// AUX_X/Y/Z/R refreshed from the BMM150's data registers.
ESP_LOGD(TAG, "Setting up BMM150 magnetometer via BMI270 aux interface...");
if (!this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN))
return false;
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8))
return false;
if (!this->write_byte(BMI270_REG_AUX_DEV_ID, (uint8_t) (this->aux_device_address_ << 1)))
return false;
// Follows the Bosch BMI270 aux-interface sequence; ends in auto-burst mode, where the BMI270 keeps
// AUX_X/Y/Z/R filled from the BMM150's data registers
const LogString *BMI270Component::setup_magnetometer_() {
if (!(this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN) &&
this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8) &&
this->write_byte(BMI270_REG_AUX_DEV_ID, this->aux_device_address_ << 1)))
return LOG_STR("aux interface");
// Suspend -> sleep, then a soft reset so the BMM150 starts from a known state even if it
// stayed powered across a restart. The chip ID is only readable once the power bit is set.
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON)) {
ESP_LOGW(TAG, "BMM150 power-on write timed out");
return false;
}
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON))
return LOG_STR("power-on");
delay(BMM150_START_UP_TIME_MS);
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET)) {
ESP_LOGW(TAG, "BMM150 soft-reset write timed out");
return false;
}
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET))
return LOG_STR("soft reset");
delay(BMM150_SOFT_RESET_TIME_MS);
uint8_t chip_id[BMI270_AUX_DATA_LEN];
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id)) {
ESP_LOGW(TAG, "BMM150 chip-ID read failed");
return false;
}
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id))
return LOG_STR("chip ID read");
if (chip_id[0] != BMM150_CHIP_ID_VALUE) {
ESP_LOGW(TAG, "BMM150 not detected (chip ID 0x%02X, expected 0x%02X)", chip_id[0], BMM150_CHIP_ID_VALUE);
return false;
ESP_LOGW(TAG, "BMM150 chip ID 0x%02X, expected 0x%02X", chip_id[0], BMM150_CHIP_ID_VALUE);
return LOG_STR("chip ID check");
}
if (!this->read_magnetometer_trim_()) {
ESP_LOGW(TAG, "BMM150 trim data read failed");
return false;
uint8_t trim[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, trim + i * BMM150_TRIM_BLOCK_LEN))
return LOG_STR("trim read");
}
this->mag_trim_ = bmm150_parse_trim(trim);
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ)) {
ESP_LOGW(TAG, "BMM150 mode write timed out");
return false;
}
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ))
return LOG_STR("normal mode");
// Switch to auto-burst mode: BMI270 will keep polling 8 bytes from the BMM150's
// data registers (0x42) into its own AUX_X/Y/Z/R registers automatically.
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
BMI270_AUX_IF_CONF_RD_BURST_8))
return false;
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB))
return false;
if (!this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN))
return false;
ESP_LOGD(TAG, "BMM150 magnetometer ready");
return true;
if (!(this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
BMI270_AUX_IF_CONF_RD_BURST_8) &&
this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB) &&
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN)))
return LOG_STR("auto-burst mode");
return nullptr;
}
#endif // USE_BMI270_BMM150
@@ -249,9 +185,10 @@ void BMI270Component::dump_config() {
if (this->is_failed())
return;
ESP_LOGCONFIG(TAG, " Accel range : %s",
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)));
ESP_LOGCONFIG(TAG, " Gyro range : %s",
ESP_LOGCONFIG(TAG,
" Accel range : %s\n"
" Gyro range : %s",
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)),
LOG_STR_ARG(GyroRangeStrings::get_log_str(this->gyro_range_, GyroRangeStrings::LAST_INDEX)));
#ifdef USE_BMI270_BMM150
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
@@ -262,9 +199,6 @@ void BMI270Component::dump_config() {
MotionComponent::dump_config();
}
// update() ─
// Reads all 6 axes + temperature in one block
bool BMI270Component::update_data(motion::MotionData &data) {
if (this->is_failed())
return false;
+8 -24
View File
@@ -12,18 +12,15 @@
namespace esphome::bmi270 {
// Register map
static constexpr uint8_t BMI270_REG_CHIP_ID = 0x00;
static constexpr uint8_t BMI270_REG_ERR_REG = 0x02;
static constexpr uint8_t BMI270_REG_STATUS = 0x03;
static constexpr uint8_t BMI270_REG_DATA_8 = 0x0C; // ACC_X LSB
static constexpr uint8_t BMI270_REG_DATA_14 = 0x12; // GYR_X LSB
static constexpr uint8_t BMI270_REG_TEMP_0 = 0x22;
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23; // temperature (2 bytes big-endian ish)
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23;
static constexpr uint8_t REG_READ_LEN =
BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 +
1; // 0x23 - 0x0C + 1 = 0x18 bytes total for accel(6) + gyro(6) + temp(2) + padding(4)
// Accel, gyro, 10 unused bytes, then temperature: 0x0C to 0x23
static constexpr uint8_t REG_READ_LEN = BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 + 1;
static constexpr uint8_t BMI270_REG_PWR_CONF = 0x7C;
static constexpr uint8_t BMI270_REG_PWR_CTRL = 0x7D;
@@ -80,7 +77,6 @@ static constexpr uint8_t BMI270_AUX_IF_CONF_RD_BURST_8 = 0x03; // bits 1:0
static constexpr uint8_t BMI270_AUX_DATA_LEN = 8;
static_assert(BMI270_REG_AUX_X_LSB + BMI270_AUX_DATA_LEN == BMI270_REG_DATA_8, "aux data must precede accel data");
// Accelerometer range options
enum BMI270AccelRange : uint8_t {
BMI270_ACCEL_RANGE_2G = 0x00,
BMI270_ACCEL_RANGE_4G = 0x01,
@@ -88,7 +84,6 @@ enum BMI270AccelRange : uint8_t {
BMI270_ACCEL_RANGE_16G = 0x03,
};
// Accelerometer ODR options
enum BMI270AccelODR : uint8_t {
BMI270_ACCEL_ODR_12_5 = 0x05,
BMI270_ACCEL_ODR_25 = 0x06,
@@ -100,7 +95,6 @@ enum BMI270AccelODR : uint8_t {
BMI270_ACCEL_ODR_1600 = 0x0C,
};
// Gyroscope range options
enum BMI270GyroRange : uint8_t {
BMI270_GYRO_RANGE_2000 = 0x00,
BMI270_GYRO_RANGE_1000 = 0x01,
@@ -109,7 +103,6 @@ enum BMI270GyroRange : uint8_t {
BMI270_GYRO_RANGE_125 = 0x04,
};
// Gyroscope ODR options
enum BMI270GyroODR : uint8_t {
BMI270_GYRO_ODR_25 = 0x06,
BMI270_GYRO_ODR_50 = 0x07,
@@ -130,14 +123,11 @@ enum BMI270AuxDevice : uint8_t {
};
#endif
// Main component class
class BMI270Component final : public motion::MotionComponent, public i2c::I2CDevice {
public:
// Lifecycle
void setup() override;
void dump_config() override;
// Configuration setters
void set_accel_range(BMI270AccelRange r) { this->accel_range_ = r; }
void set_accel_odr(BMI270AccelODR o) { this->accel_odr_ = o; }
void set_gyro_range(BMI270GyroRange r) { this->gyro_range_ = r; }
@@ -153,21 +143,15 @@ class BMI270Component final : public motion::MotionComponent, public i2c::I2CDev
bool update_data(motion::MotionData &data) override;
bool load_config_file_();
#ifdef USE_BMI270_BMM150
// Brings up the BMM150 over the BMI270's aux interface. Optional: on failure this only
// disables magnetometer reporting, it does not fail the whole component (accel/gyro still work).
bool setup_magnetometer_();
// Blocking poll of the aux-transaction-busy bit; aux transaction time depends on the
// attached device, so this is bounded by retries/timeout rather than a fixed delay.
bool wait_for_aux_idle_(uint32_t timeout_ms);
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device.
// Returns the step that failed, or nullptr once the BMM150 is running
const LogString *setup_magnetometer_();
// Polls the aux busy bit, as the aux transaction time depends on the attached device
bool wait_for_aux_idle_();
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device
bool read_aux_block_(uint8_t reg, uint8_t *buf);
// Manual-mode aux write of one byte to `reg` on the aux device.
bool write_aux_register_(uint8_t reg, uint8_t value);
// Reads the BMM150 factory trim values used to compensate its samples.
bool read_magnetometer_trim_();
#endif
// Config
BMI270AccelRange accel_range_{BMI270_ACCEL_RANGE_4G};
BMI270AccelODR accel_odr_{BMI270_ACCEL_ODR_100};
BMI270GyroRange gyro_range_{BMI270_GYRO_RANGE_2000};
+2 -1
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cstdint>
#include "esphome/core/hal.h"
namespace esphome::bmi270 {
@@ -44,7 +45,7 @@ POSSIBILITY OF SUCH DAMAGE.
after every power cycle, before any sensor data can be read.
--------------------------------------------------------------------------- */
static constexpr uint8_t BMI270_CONFIG_FILE[] = {
static constexpr uint8_t BMI270_CONFIG_FILE[] PROGMEM = {
0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x3d, 0xb1, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x91, 0x03, 0x80, 0x2e, 0xbc,
0xb0, 0x80, 0x2e, 0xa3, 0x03, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x00, 0xb0, 0x50, 0x30, 0x21, 0x2e, 0x59, 0xf5,
0x10, 0x30, 0x21, 0x2e, 0x6a, 0xf5, 0x80, 0x2e, 0x3b, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x19, 0x01, 0x00, 0x22,
+16 -16
View File
@@ -3,11 +3,8 @@
#include <cstdint>
#include "esphome/core/helpers.h"
// BMM150 magnetometer definitions - the chip that can optionally be wired to the BMI270's
// auxiliary (secondary I2C master) interface. Lives in its own header/namespace because this
// is BMM150-specific driver knowledge, not BMI270 knowledge - it just can't be a standalone
// ESPHome component, since the BMM150 has no address of its own on the main I2C bus and is only
// reachable by having the BMI270 proxy register reads/writes through its aux interface.
// BMM150 magnetometer behind the BMI270's aux interface; it is not on the main I2C bus, so it is not
// its own component
namespace esphome::bmi270::bmm150 {
static constexpr uint8_t BMM150_DEFAULT_I2C_ADDRESS = 0x10;
@@ -64,20 +61,23 @@ inline uint16_t bmm150_trim_word(const uint8_t *regs, uint8_t reg) {
return encode_value_le<uint16_t>(&regs[offset]);
}
// A trim byte, addressed by its register
inline uint8_t bmm150_trim_byte(const uint8_t *regs, uint8_t reg) { return regs[reg - BMM150_REG_TRIM_START]; }
// Decodes the trim registers; `regs` holds the bytes of registers 0x5D onwards (at least 21).
inline BMM150Trim bmm150_parse_trim(const uint8_t *regs) {
BMM150Trim trim;
trim.x1 = static_cast<int8_t>(regs[BMM150_TRIM_X1 - BMM150_REG_TRIM_START]);
trim.y1 = static_cast<int8_t>(regs[BMM150_TRIM_Y1 - BMM150_REG_TRIM_START]);
trim.x1 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_X1));
trim.y1 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y1));
trim.z4 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z4));
trim.x2 = static_cast<int8_t>(regs[BMM150_TRIM_X2 - BMM150_REG_TRIM_START]);
trim.y2 = static_cast<int8_t>(regs[BMM150_TRIM_Y2 - BMM150_REG_TRIM_START]);
trim.x2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_X2));
trim.y2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y2));
trim.z2 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z2));
trim.z1 = bmm150_trim_word(regs, BMM150_TRIM_Z1);
trim.xyz1 = bmm150_trim_word(regs, BMM150_TRIM_XYZ1) & BMM150_TRIM_XYZ1_MASK;
trim.z3 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z3));
trim.xy2 = static_cast<int8_t>(regs[BMM150_TRIM_XY2 - BMM150_REG_TRIM_START]);
trim.xy1 = regs[BMM150_TRIM_XY1 - BMM150_REG_TRIM_START];
trim.xy2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_XY2));
trim.xy1 = bmm150_trim_byte(regs, BMM150_TRIM_XY1);
return trim;
}
@@ -108,11 +108,11 @@ inline float bmm150_compensate_z(const BMM150Trim &trim, int16_t raw, uint16_t r
// Converts 8 raw bytes from the BMM150 data registers (X, Y, Z, RHALL; 0x42-0x49) to compensated µT.
inline BMM150Data bmm150_convert(const BMM150Trim &trim, const uint8_t *raw) {
// X/Y are 13-bit (LSB byte bits 7:3), Z is 15-bit (bits 7:1), RHALL is 14-bit (bits 7:2).
int16_t x = (int16_t) (((int16_t) (int8_t) raw[1] * 32) | (raw[0] >> 3));
int16_t y = (int16_t) (((int16_t) (int8_t) raw[3] * 32) | (raw[2] >> 3));
int16_t z = (int16_t) (((int16_t) (int8_t) raw[5] * 128) | (raw[4] >> 1));
uint16_t rhall = (uint16_t) (((uint16_t) raw[7] << 6) | (raw[6] >> 2));
// Left-aligned in their 16-bit words: X/Y are 13-bit, Z is 15-bit, RHALL is 14-bit
const int16_t x = encode_value_le<int16_t>(&raw[0]) >> 3;
const int16_t y = encode_value_le<int16_t>(&raw[2]) >> 3;
const int16_t z = encode_value_le<int16_t>(&raw[4]) >> 1;
const uint16_t rhall = encode_value_le<uint16_t>(&raw[6]) >> 2;
return BMM150Data{
.x = bmm150_compensate_xy(trim, trim.x1, trim.x2, x, rhall),
.y = bmm150_compensate_xy(trim, trim.y1, trim.y2, y, rhall),
+28 -21
View File
@@ -17,6 +17,14 @@ DEPENDENCIES = ["i2c"]
CONF_AUX_ADDRESS = "aux_address"
CONF_AUX_DEVICE = "aux_device"
# to_code skips the setters at these values, so each must match its member default in bmi270.h
DEFAULT_ACCELEROMETER_RANGE = "4G"
DEFAULT_ACCELEROMETER_ODR = "100HZ"
DEFAULT_GYROSCOPE_RANGE = "2000DPS"
DEFAULT_GYROSCOPE_ODR = "200HZ"
# The BMM150's fixed address
DEFAULT_AUX_ADDRESS = 0x10
# Enum proxies (must match the C++ enum values exactly)
BMI270AuxDevice = bmi270_ns.enum("BMI270AuxDevice")
BMI270AccelRange = bmi270_ns.enum("BMI270AccelRange")
@@ -57,50 +65,49 @@ GYRO_ODR_OPTIONS = {
"3200HZ": BMI270GyroODR.BMI270_GYRO_ODR_3200,
}
# Top-level CONFIG_SCHEMA
CONFIG_SCHEMA = (
motion_schema(BMI270Component, has_accel=True, has_gyro=True)
.extend(
{
cv.Optional(CONF_ACCELEROMETER_RANGE, default="4G"): cv.enum(
ACCEL_RANGE_OPTIONS, upper=True
),
cv.Optional(CONF_ACCELEROMETER_ODR, default="100HZ"): cv.enum(
ACCEL_ODR_OPTIONS, upper=True
),
cv.Optional(CONF_GYROSCOPE_RANGE, default="2000DPS"): cv.enum(
cv.Optional(
CONF_ACCELEROMETER_RANGE, default=DEFAULT_ACCELEROMETER_RANGE
): cv.enum(ACCEL_RANGE_OPTIONS, upper=True),
cv.Optional(
CONF_ACCELEROMETER_ODR, default=DEFAULT_ACCELEROMETER_ODR
): cv.enum(ACCEL_ODR_OPTIONS, upper=True),
cv.Optional(CONF_GYROSCOPE_RANGE, default=DEFAULT_GYROSCOPE_RANGE): cv.enum(
GYRO_RANGE_OPTIONS, upper=True
),
cv.Optional(CONF_GYROSCOPE_ODR, default="200HZ"): cv.enum(
cv.Optional(CONF_GYROSCOPE_ODR, default=DEFAULT_GYROSCOPE_ODR): cv.enum(
GYRO_ODR_OPTIONS, upper=True
),
# Optional device wired to the BMI270's aux interface (not the main I2C bus).
# Defaults to NONE so existing configs/boards are unaffected.
cv.Optional(CONF_AUX_DEVICE, default="NONE"): cv.one_of(
"NONE", "BMM150", upper=True
),
# Default matches the BMM150's fixed I2C address; irrelevant when aux_device is NONE.
cv.Optional(CONF_AUX_ADDRESS, default=0x10): cv.i2c_address,
cv.Optional(CONF_AUX_ADDRESS, default=DEFAULT_AUX_ADDRESS): cv.i2c_address,
}
)
.extend(i2c.i2c_device_schema(0x68))
)
# Code generation
async def to_code(config: ConfigType) -> None:
var = await new_motion_component(config)
await i2c.register_i2c_device(var, config)
# Accelerometer sensors
# Hardware configuration
cg.add(var.set_accel_range(config[CONF_ACCELEROMETER_RANGE]))
cg.add(var.set_accel_odr(config[CONF_ACCELEROMETER_ODR]))
cg.add(var.set_gyro_range(config[CONF_GYROSCOPE_RANGE]))
cg.add(var.set_gyro_odr(config[CONF_GYROSCOPE_ODR]))
# The C++ members already hold the schema defaults
for key, default, setter in (
(CONF_ACCELEROMETER_RANGE, DEFAULT_ACCELEROMETER_RANGE, var.set_accel_range),
(CONF_ACCELEROMETER_ODR, DEFAULT_ACCELEROMETER_ODR, var.set_accel_odr),
(CONF_GYROSCOPE_RANGE, DEFAULT_GYROSCOPE_RANGE, var.set_gyro_range),
(CONF_GYROSCOPE_ODR, DEFAULT_GYROSCOPE_ODR, var.set_gyro_odr),
):
if config[key] != default:
cg.add(setter(config[key]))
# The aux interface code only compiles when some instance has a BMM150; the
# instance still records its own device, as another one may have none
if config[CONF_AUX_DEVICE] == "BMM150":
cg.add_define("USE_BMI270_BMM150")
cg.add(var.set_aux_device(BMI270AuxDevice.BMI270_AUX_DEVICE_BMM150))
cg.add(var.set_aux_device_address(config[CONF_AUX_ADDRESS]))
if (address := config[CONF_AUX_ADDRESS]) != DEFAULT_AUX_ADDRESS:
cg.add(var.set_aux_device_address(address))
+4 -10
View File
@@ -515,18 +515,12 @@ void CC1101Component::dump_config() {
}
void CC1101Component::begin_tx() {
this->wake_up();
// Read the mode before the PKTCTRL0 write below overwrites it in state_
const bool packet_mode = this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
// Ensure Packet Format is 3 (Async Serial)
this->write_(Register::PKTCTRL0, 0x32);
if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
ESP_LOGW(TAG, "begin_tx is for async serial mode; use send_packet in packet mode");
return;
}
ESP_LOGV(TAG, "Beginning TX sequence");
if (this->gdo0_pin_ != nullptr) {
// setup() only attaches the interrupt in packet mode. In async serial mode the pin may be
// shared with remote_receiver, and detaching here would remove the receiver's interrupt.
if (packet_mode) {
this->gdo0_pin_->detach_interrupt();
}
this->gdo0_pin_->pin_mode(gpio::FLAG_OUTPUT);
}
// Transition through IDLE to bypass CCA (Clear Channel Assessment) which can
@@ -63,13 +63,25 @@ void CST816Touchscreen::update_touches() {
uint8_t data[13];
if (!this->status_comm_result(this->read_bytes(REG_STATUS, data, sizeof data)))
return;
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
// The low nibble is the touch count. CST816/CST820 are single-touch;
// CST826/CST836 can report two points, but this driver only reads the first
// point. Some CST8xx controllers report an all-0xFF frame when idle or after
// disabling auto-sleep: the count lands above two and the coordinates are
// the 0xFFF sentinel, so both guards below reject it.
uint8_t num_of_touches = low_nibble(data[REG_TOUCH_NUM]);
if (num_of_touches == 0) {
return;
}
if (num_of_touches > 2) {
return;
}
uint16_t x = encode_uint16(low_nibble(data[REG_XPOS_HIGH]), data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(low_nibble(data[REG_YPOS_HIGH]), data[REG_YPOS_LOW]);
if (x == 0x0FFF || y == 0x0FFF) {
return;
}
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
this->add_raw_touch_position_(0, x, y);
}
+108 -138
View File
@@ -1,6 +1,5 @@
#include "daly_bms.h"
#include <algorithm>
#include <vector>
#include "esphome/core/application.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
@@ -9,7 +8,6 @@ namespace esphome::daly_bms {
ESPHOME_LOG_TAG(TAG, "daly_bms");
static const uint8_t DALY_FRAME_SIZE = 13;
static const uint8_t DALY_TEMPERATURE_OFFSET = 40;
static const uint16_t DALY_CURRENT_OFFSET = 30000;
@@ -48,14 +46,9 @@ void DalyBmsComponent::update() {
void DalyBmsComponent::loop() {
const uint32_t now = App.get_loop_component_start_time();
const size_t avail = this->available();
if (this->receiving_ && (now - this->last_transmission_ >= 200)) {
// last transmission too long ago. Reset RX index.
ESP_LOGW(TAG, "Last transmission too long ago. Reset RX index.");
this->data_.clear();
this->receiving_ = false;
}
if (this->response_complete_() && !this->receiving_ && avail == 0 &&
auto handle = [this](const uint8_t *frame, size_t /*len*/) { return this->handle_frame_(frame); };
this->read_frames(this->reader_, handle, now, this->last_transmission_);
if (this->response_complete_() && this->reader_.length() == 0 &&
(now - this->last_transmission_ >= DALY_RESPONSE_GAP_MS) && !this->trigger_next_) {
// response complete and nothing more on the line -> trigger next request without waiting for the timeout
this->last_transmission_ = now;
@@ -66,25 +59,6 @@ void DalyBmsComponent::loop() {
this->last_transmission_ = now;
this->trigger_next_ = true;
}
if (avail > 0)
this->last_transmission_ = now;
this->read_available(
[this](uint8_t c) {
if (!this->receiving_) {
if (c != 0xa5)
return;
this->receiving_ = true;
}
this->data_.push_back(c);
if (this->data_.size() == 4)
this->data_count_ = c;
if ((this->data_.size() > 4) and (data_.size() == this->data_count_ + 5)) {
this->decode_data_(this->data_);
this->data_.clear();
this->receiving_ = false;
}
},
avail);
if (!this->trigger_next_)
return;
@@ -105,6 +79,8 @@ void DalyBmsComponent::loop() {
this->last_transmission_ = now;
// the request IDs are consecutive, see DALY_REQUEST_BATTERY_LEVEL
this->last_request_ = DALY_REQUEST_BATTERY_LEVEL + this->next_request_++;
// A new request starts a new exchange; kept bytes of an earlier reply must not merge into this one
this->reader_.reset();
this->request_data_(this->last_request_);
}
@@ -143,128 +119,122 @@ void DalyBmsComponent::request_data_(uint8_t data_id) {
this->flush();
}
void DalyBmsComponent::decode_data_(std::vector<uint8_t> data) {
auto it = data.begin();
while ((it = std::find(it, data.end(), 0xA5)) != data.end()) {
if (data.end() - it >= DALY_FRAME_SIZE && it[1] == 0x01) {
const uint8_t checksum = sum_bytes(&*it, 12);
if (checksum == it[12]) {
// only a valid frame answering the last request counts; an echoed request or a late answer does not
if (it[2] == this->last_request_)
this->frames_received_++;
if (it[2] == DALY_REQUEST_STATUS) {
this->cell_frames_ = (it[4] + 2) / 3; // three cells per cell voltage frame
this->temperature_frames_ = std::max((it[5] + 6) / 7, 1);
}
switch (it[2]) {
bool DalyBmsComponent::handle_frame_(const uint8_t *frame) {
// Only BMS responses (address 0x01) with their 8 data bytes carry data; an echoed request is skipped like noise
if (frame[1] != 0x01 || frame[3] != 8)
return false;
if (sum_bytes(frame, DALY_FRAME_SIZE - 1) != frame[DALY_FRAME_SIZE - 1]) {
ESP_LOGW(TAG, "Checksum-Error on Packet %x", frame[4]);
return false;
}
// only an answer to the last request counts
if (frame[2] == this->last_request_)
this->frames_received_++;
if (frame[2] == DALY_REQUEST_STATUS) {
this->cell_frames_ = (frame[4] + 2) / 3; // three cells per cell voltage frame
this->temperature_frames_ = std::max((frame[5] + 6) / 7, 1);
}
switch (frame[2]) {
#ifdef USE_SENSOR
case DALY_REQUEST_BATTERY_LEVEL:
PUBLISH_STATE(this->voltage_sensor_, (float) encode_uint16(it[4], it[5]) / 10);
PUBLISH_STATE(this->current_sensor_, (float) (encode_uint16(it[8], it[9]) - DALY_CURRENT_OFFSET) / 10);
PUBLISH_STATE(this->battery_level_sensor_, (float) encode_uint16(it[10], it[11]) / 10);
break;
case DALY_REQUEST_BATTERY_LEVEL:
PUBLISH_STATE(this->voltage_sensor_, (float) encode_uint16(frame[4], frame[5]) / 10);
PUBLISH_STATE(this->current_sensor_, (float) (encode_uint16(frame[8], frame[9]) - DALY_CURRENT_OFFSET) / 10);
PUBLISH_STATE(this->battery_level_sensor_, (float) encode_uint16(frame[10], frame[11]) / 10);
break;
case DALY_REQUEST_MIN_MAX_VOLTAGE:
PUBLISH_STATE(this->max_cell_voltage_sensor_, (float) encode_uint16(it[4], it[5]) / 1000);
PUBLISH_STATE(this->max_cell_voltage_number_sensor_, it[6]);
PUBLISH_STATE(this->min_cell_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->min_cell_voltage_number_sensor_, it[9]);
break;
case DALY_REQUEST_MIN_MAX_VOLTAGE:
PUBLISH_STATE(this->max_cell_voltage_sensor_, (float) encode_uint16(frame[4], frame[5]) / 1000);
PUBLISH_STATE(this->max_cell_voltage_number_sensor_, frame[6]);
PUBLISH_STATE(this->min_cell_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->min_cell_voltage_number_sensor_, frame[9]);
break;
case DALY_REQUEST_MIN_MAX_TEMPERATURE:
PUBLISH_STATE(this->max_temperature_sensor_, it[4] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->max_temperature_probe_number_sensor_, it[5]);
PUBLISH_STATE(this->min_temperature_sensor_, it[6] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->min_temperature_probe_number_sensor_, it[7]);
break;
case DALY_REQUEST_MIN_MAX_TEMPERATURE:
PUBLISH_STATE(this->max_temperature_sensor_, frame[4] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->max_temperature_probe_number_sensor_, frame[5]);
PUBLISH_STATE(this->min_temperature_sensor_, frame[6] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->min_temperature_probe_number_sensor_, frame[7]);
break;
#endif
case DALY_REQUEST_MOS:
case DALY_REQUEST_MOS:
#ifdef USE_TEXT_SENSOR
if (this->status_text_sensor_ != nullptr) {
switch (it[4]) {
case 0:
this->status_text_sensor_->publish_state("Stationary");
break;
case 1:
this->status_text_sensor_->publish_state("Charging");
break;
case 2:
this->status_text_sensor_->publish_state("Discharging");
break;
default:
break;
}
}
#endif
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->charging_mos_enabled_binary_sensor_, it[5]);
PUBLISH_STATE(this->discharging_mos_enabled_binary_sensor_, it[6]);
#endif
#ifdef USE_SENSOR
PUBLISH_STATE(this->remaining_capacity_sensor_, (float) encode_uint32(it[8], it[9], it[10], it[11]) / 1000);
#endif
if (this->status_text_sensor_ != nullptr) {
switch (frame[4]) {
case 0:
this->status_text_sensor_->publish_state("Stationary");
break;
#ifdef USE_SENSOR
case DALY_REQUEST_STATUS:
PUBLISH_STATE(this->cells_number_sensor_, it[4]);
case 1:
this->status_text_sensor_->publish_state("Charging");
break;
case DALY_REQUEST_TEMPERATURE:
if (it[4] == 1) {
PUBLISH_STATE(this->temperature_1_sensor_, it[5] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->temperature_2_sensor_, it[6] - DALY_TEMPERATURE_OFFSET);
}
case 2:
this->status_text_sensor_->publish_state("Discharging");
break;
case DALY_REQUEST_CELL_VOLTAGE:
switch (it[4]) {
case 1:
PUBLISH_STATE(this->cell_1_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_2_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_3_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 2:
PUBLISH_STATE(this->cell_4_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_5_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_6_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 3:
PUBLISH_STATE(this->cell_7_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_8_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_9_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 4:
PUBLISH_STATE(this->cell_10_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_11_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_12_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 5:
PUBLISH_STATE(this->cell_13_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_14_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_15_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 6:
PUBLISH_STATE(this->cell_16_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_17_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_18_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
}
break;
#endif
default:
break;
}
} else {
ESP_LOGW(TAG, "Checksum-Error on Packet %x", it[4]);
}
std::advance(it, DALY_FRAME_SIZE);
} else {
std::advance(it, 1);
}
#endif
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->charging_mos_enabled_binary_sensor_, frame[5]);
PUBLISH_STATE(this->discharging_mos_enabled_binary_sensor_, frame[6]);
#endif
#ifdef USE_SENSOR
PUBLISH_STATE(this->remaining_capacity_sensor_,
(float) encode_uint32(frame[8], frame[9], frame[10], frame[11]) / 1000);
#endif
break;
#ifdef USE_SENSOR
case DALY_REQUEST_STATUS:
PUBLISH_STATE(this->cells_number_sensor_, frame[4]);
break;
case DALY_REQUEST_TEMPERATURE:
if (frame[4] == 1) {
PUBLISH_STATE(this->temperature_1_sensor_, frame[5] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->temperature_2_sensor_, frame[6] - DALY_TEMPERATURE_OFFSET);
}
break;
case DALY_REQUEST_CELL_VOLTAGE:
switch (frame[4]) {
case 1:
PUBLISH_STATE(this->cell_1_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_2_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_3_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 2:
PUBLISH_STATE(this->cell_4_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_5_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_6_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 3:
PUBLISH_STATE(this->cell_7_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_8_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_9_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 4:
PUBLISH_STATE(this->cell_10_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_11_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_12_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 5:
PUBLISH_STATE(this->cell_13_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_14_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_15_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 6:
PUBLISH_STATE(this->cell_16_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_17_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_18_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
}
break;
#endif
default:
break;
}
return true;
}
} // namespace esphome::daly_bms
+7 -6
View File
@@ -2,6 +2,7 @@
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor.h"
#endif
@@ -13,10 +14,10 @@
#endif
#include "esphome/components/uart/uart.h"
#include <vector>
namespace esphome::daly_bms {
static constexpr uint8_t DALY_FRAME_SIZE = 13;
class DalyBmsComponent final : public PollingComponent, public uart::UARTDevice {
public:
DalyBmsComponent() = default;
@@ -76,13 +77,13 @@ class DalyBmsComponent final : public PollingComponent, public uart::UARTDevice
void request_data_(uint8_t data_id);
// all frames of the response to the last request are in
bool response_complete_() const;
void decode_data_(std::vector<uint8_t> data);
/// Returns false for a frame that is not a BMS response or fails the checksum
bool handle_frame_(const uint8_t *frame);
uint8_t addr_;
std::vector<uint8_t> data_;
bool receiving_{false};
uint8_t data_count_{0};
// A5, address, data ID, length 8, 8 data bytes, sum8; every request and response has 8 data bytes
LengthFrameReader<DALY_FRAME_SIZE, FrameFormat<FrameHeader<0xA5>, FrameFixedLength<DALY_FRAME_SIZE>>> reader_;
uint32_t last_transmission_{0};
bool trigger_next_{false};
// update() asked for a request cycle; it starts once no cycle is running. The first one runs at boot.
+2
View File
@@ -94,5 +94,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
PlatformFramework.LN882X_ARDUINO,
},
"debug_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf52.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf54l.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)
+380
View File
@@ -0,0 +1,380 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && !defined(NRF54L_SERIES)
#include <cinttypes>
#include <cstdint>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <hal/nrf_power.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")),
mac_pretty, NRF_FICR->INFO.PART, NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF,
NRF_FICR->INFO.VARIANT >> 8 & 0xFF, NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE),
NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("not ")));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
+113
View File
@@ -0,0 +1,113 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && defined(NRF54L_SERIES)
#include <cinttypes>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
// UARTE, SPIM, SPIS, TWIM and TWIS with the same number share one instance
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " UARTE00: %-3s| UARTE20: %-3s| UARTE21: %-3s| UARTE22: %-3s| UARTE30: %-3s", //
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE00), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE20),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE21), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE22),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE30));
ESP_LOGV(TAG, " SPIM00: %-3s| SPIM20: %-3s| SPIM21: %-3s| SPIM22: %-3s| SPIM30: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM00), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM20),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM21), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM22),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM30));
ESP_LOGV(TAG, " SPIS00: %-3s| SPIS20: %-3s| SPIS21: %-3s| SPIS22: %-3s| SPIS30: %-3s", //
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS00), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS20),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS21), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS22),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS30));
ESP_LOGV(TAG, " TWIM20: %-3s| TWIM21: %-3s| TWIM22: %-3s| TWIM30: %-3s", //
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM20), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM21),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM22), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM30));
ESP_LOGV(TAG, " TWIS20: %-3s| TWIS21: %-3s| TWIS22: %-3s| TWIS30: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS20), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS21),
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS22), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS30));
ESP_LOGV(TAG, " PWM20: %-3s| PWM21: %-3s| PWM22: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM20), NRF_PERIPH_ENABLED(PWM, NRF_PWM21), NRF_PERIPH_ENABLED(PWM, NRF_PWM22),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " PDM20: %-3s| PDM21: %-3s| QDEC20: %-3s| QDEC21: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM20), NRF_PERIPH_ENABLED(PDM, NRF_PDM21), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC20),
NRF_PERIPH_ENABLED(QDEC, NRF_QDEC21));
ESP_LOGV(TAG, " COMP: %-3s| LPCOMP: %-3s| AAR00: %-3s| CCM00: %-3s", //
NRF_PERIPH_ENABLED(COMP, NRF_COMP), NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP),
NRF_PERIPH_ENABLED(AAR, NRF_AAR00), NRF_PERIPH_ENABLED(CCM, NRF_CCM00));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF registers are MMIO at fixed addresses
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main regulator
const char *reg_type = (NRF_REGULATORS->VREGMAIN.DCDCEN & REGULATORS_VREGMAIN_DCDCEN_VAL_Msk) ==
(REGULATORS_VREGMAIN_DCDCEN_VAL_Enabled << REGULATORS_VREGMAIN_DCDCEN_VAL_Pos)
? "DC/DC"
: "LDO";
ESP_LOGD(TAG, "Main regulator: %s", reg_type);
pos = buf_append_str(buf, size, pos, "|Main regulator: ");
pos = buf_append_str(buf, size, pos, reg_type);
// Power-fail comparator, the threshold goes from 1.7V up in 0.1V steps
const uint32_t pofcon = NRF_REGULATORS->POFCON;
if ((pofcon & REGULATORS_POFCON_POF_Msk) == (REGULATORS_POFCON_POF_Enabled << REGULATORS_POFCON_POF_Pos)) {
const uint32_t decivolts = 17 + ((pofcon & REGULATORS_POFCON_THRESHOLD_Msk) >> REGULATORS_POFCON_THRESHOLD_Pos);
ESP_LOGD(TAG, "Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10, decivolts % 10);
pos = buf_append_printf(buf, size, pos, "|Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10,
decivolts % 10);
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
const uint32_t variant = NRF_FICR->INFO.VARIANT;
ESP_LOGD(TAG,
"nRF debug info:\n"
" Device id: 0x%08" PRIx32 "%08" PRIx32 "\n"
" Encryption root: 0x%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "%08" PRIx32 ", Identity Root: 0x%08" PRIx32
"%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "\n"
" Device address type: %s, address: %s\n"
" Part code: 0x%" PRIx32 ", version: %c%c%c%c, package: 0x%" PRIx32 "\n"
" RAM: %" PRIu32 "kB, RRAM: %" PRIu32 "kB",
NRF_FICR->INFO.DEVICEID[1], NRF_FICR->INFO.DEVICEID[0], NRF_FICR->ER[0], NRF_FICR->ER[1], NRF_FICR->ER[2],
NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2], NRF_FICR->IR[3],
(NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")), mac_pretty,
NRF_FICR->INFO.PART, static_cast<char>(variant >> 24 & 0xFF), static_cast<char>(variant >> 16 & 0xFF),
static_cast<char>(variant >> 8 & 0xFF), static_cast<char>(variant & 0xFF), NRF_FICR->INFO.PACKAGE,
NRF_FICR->INFO.RAM, NRF_FICR->INFO.RRAM);
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#endif
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
-364
View File
@@ -2,55 +2,14 @@
#ifdef USE_ZEPHYR
#include <cinttypes>
#include <climits>
#include "esphome/core/alloc_helpers.h"
#include "esphome/core/log.h"
#include <esphome/components/zephyr/reset_reason.h>
#include <zephyr/drivers/hwinfo.h>
#include <zephyr/kernel.h>
#include <hal/nrf_power.h>
#include <cstdint>
#include <zephyr/storage/flash_map.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
const char *DebugComponent::get_reset_reason_(std::span<char, RESET_REASON_BUFFER_SIZE> buffer) {
const char *buf = zephyr::get_reset_reason(buffer);
@@ -96,329 +55,6 @@ void DebugComponent::log_partition_info_() {
flash_area_foreach(fa_cb, nullptr);
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? "Random" : "Public"), mac_pretty, NRF_FICR->INFO.PART,
NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF, NRF_FICR->INFO.VARIANT >> 8 & 0xFF,
NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE), NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? "" : "not "));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// The Python side enables the statistics only for a verbose logger
#ifdef CONFIG_SCHED_THREAD_USAGE_ANALYSIS
static void log_thread_usage(const struct k_thread *thread, void *user_data) {
@@ -215,8 +215,9 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
break;
}
for (auto &entry : this->services_) {
entry.service->gatts_event_handler(event, gatts_if, param);
// Indexed: a handler (an on_write lambda) can create a service, and push_back may move the vector.
for (size_t i = 0; i < this->services_.size(); i++) { // NOLINT(modernize-loop-convert)
this->services_[i].service->gatts_event_handler(event, gatts_if, param);
}
}
+15 -29
View File
@@ -180,23 +180,18 @@ void ArduinoI2CBus::recover_() {
return;
}
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
// Make sure that switching to output mode will make SCL low, just in
// case other code has setup the pin for a HIGH signal.
digitalWrite(this->scl_pin_, LOW); // NOLINT
// Activate input and pull up resistor for the SDA pin, so it can be read during the pulses.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
delayMicroseconds(half_period_usec);
for (auto i = 0; i < 9; i++) {
// Release pull up resistor and switch to output to make the signal LOW.
pinMode(this->scl_pin_, INPUT); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && digitalRead(this->sda_pin_) == LOW; i++) { // NOLINT
// Drive LOW. Set the level while the pin is a plain input: on RP2040 a write to an
// INPUT_PULLUP pin drives it, which would leave SCL low if the loop never runs.
pinMode(this->scl_pin_, INPUT); // NOLINT
digitalWrite(this->scl_pin_, LOW); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
delayMicroseconds(half_period_usec);
// Release output and activate pull up resistor to make the signal HIGH.
@@ -223,14 +218,7 @@ void ArduinoI2CBus::recover_() {
}
}
// Activate input and pull resistor for the SDA pin, so we can verify
// that SDA is pulled HIGH in the following step.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
// A device still holding SDA after nine pulses cannot be freed here.
if (digitalRead(this->sda_pin_) == LOW) { // NOLINT
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -242,15 +230,13 @@ void ArduinoI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
pinMode(this->sda_pin_, INPUT); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
pinMode(this->sda_pin_, INPUT); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
// From the specification:
// "A START condition immediately followed by a STOP condition (void
+5 -15
View File
@@ -346,14 +346,9 @@ void IDFI2CBus::recover_() {
return;
}
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
for (auto i = 0; i < 9; i++) {
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && gpio_get_level(sda_pin) == 0; i++) {
gpio_set_level(scl_pin, 0);
delayMicroseconds(half_period_usec);
gpio_set_level(scl_pin, 1);
@@ -378,9 +373,7 @@ void IDFI2CBus::recover_() {
}
}
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
// A device still holding SDA after nine pulses cannot be freed here.
if (gpio_get_level(sda_pin) == 0) {
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -392,10 +385,7 @@ void IDFI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
+63 -81
View File
@@ -1,5 +1,7 @@
#include "ld2410.h"
#include <algorithm>
#ifdef USE_NUMBER
#include "esphome/components/number/number.h"
#endif
@@ -119,13 +121,9 @@ static constexpr uint8_t UNCONFIRMED_INDEX = static_cast<uint8_t>(BgCorrectionRe
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
using ld24xx::HEADER_FOOTER_SIZE;
using ld24xx::validate_header_footer;
// Smallest frames whose values can all be read: the last value, data footer and check, then the frame footer
static constexpr uint8_t PERIODIC_FRAME_MIN = DETECT_DISTANCE_HIGH + 3 + HEADER_FOOTER_SIZE;
static constexpr uint8_t ENGINEERING_FRAME_MIN = OUT_PIN_SENSOR + 3 + HEADER_FOOTER_SIZE;
// Data Header & Footer
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
void LD2410Component::dump_config() {
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
@@ -231,13 +229,14 @@ void LD2410Component::restart_and_read_all_info() {
}
void LD2410Component::loop() {
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_LINE_LENGTH>(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
}
void LD2410Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
ESP_LOGV(TAG, "Sending COMMAND %02X", command);
// frame header bytes
this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
this->write_array_progmem(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -251,29 +250,27 @@ void LD2410Component::send_command_(uint8_t command, const uint8_t *command_valu
this->write_array(command_value, command_value_len);
}
// frame footer bytes
this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
this->write_array_progmem(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(50); // NOLINT
}
}
void LD2410Component::handle_periodic_data_() {
bool LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
// 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
// data header=0xAA, data footer=0x55, crc=0x00
if (this->buffer_pos_ < 12 || !ld2410::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER ||
this->buffer_data_[this->buffer_pos_ - 5] != CHECK) {
return;
if (len < 12 || frame[7] != HEADER || frame[len - 6] != FOOTER || frame[len - 5] != CHECK) {
return false;
}
/*
Data Type: 7th
0x01: Engineering mode
0x02: Normal mode
*/
bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
if (this->buffer_pos_ < (engineering_mode ? ENGINEERING_FRAME_MIN : PERIODIC_FRAME_MIN)) {
return; // too short to hold the values
bool engineering_mode = frame[DATA_TYPES] == 0x01;
if (len < (engineering_mode ? ENGINEERING_FRAME_MIN : PERIODIC_FRAME_MIN)) {
return false; // too short to hold the values
}
#ifdef USE_SWITCH
PUBLISH_STATE(this->engineering_mode_switch_, engineering_mode);
@@ -285,7 +282,7 @@ void LD2410Component::handle_periodic_data_() {
0x02 = Still targets
0x03 = Moving+Still targets
*/
const uint8_t target_state = this->buffer_data_[TARGET_STATES];
const uint8_t target_state = frame[TARGET_STATES];
#ifdef USE_LD2410_BG_CORRECTION
// Pass or fail comes only from these frames
if (this->bg_correction_running_) {
@@ -312,13 +309,13 @@ void LD2410Component::handle_periodic_data_() {
*/
#ifdef USE_SENSOR
SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY]);
encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, frame[MOVING_ENERGY]);
SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY]);
encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, frame[STILL_ENERGY]);
SAFE_PUBLISH_SENSOR(this->detection_distance_sensor_,
encode_uint16(this->buffer_data_[DETECT_DISTANCE_HIGH], this->buffer_data_[DETECT_DISTANCE_LOW]));
encode_uint16(frame[DETECT_DISTANCE_HIGH], frame[DETECT_DISTANCE_LOW]));
if (engineering_mode) {
/*
@@ -327,18 +324,18 @@ void LD2410Component::handle_periodic_data_() {
Moving energy: 20~28th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], frame[MOVING_SENSOR_START + i]);
}
/*
Still energy: 29~37th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], frame[STILL_SENSOR_START + i]);
}
/*
Light sensor: 38th bytes
*/
SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
SAFE_PUBLISH_SENSOR(this->light_sensor_, frame[LIGHT_SENSOR]);
} else {
for (auto &gate_move_sensor : this->gate_move_sensors_) {
SAFE_PUBLISH_SENSOR_UNKNOWN(gate_move_sensor);
@@ -350,9 +347,9 @@ void LD2410Component::handle_periodic_data_() {
}
#endif
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->out_pin_presence_status_binary_sensor_,
engineering_mode ? this->buffer_data_[OUT_PIN_SENSOR] == 0x01 : false);
PUBLISH_STATE(this->out_pin_presence_status_binary_sensor_, engineering_mode ? frame[OUT_PIN_SENSOR] == 0x01 : false);
#endif
return true;
}
#ifdef USE_NUMBER
@@ -363,24 +360,24 @@ void set_number_value(number::Number *n, float value) {
}
#endif
void LD2410Component::handle_ack_data_() {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", frame[COMMAND]);
if (frame[COMMAND_STATUS] != 0x01) {
ESP_LOGE(TAG, "Invalid status");
return;
return false;
}
if (this->buffer_data_[8] || this->buffer_data_[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
#ifdef USE_LD2410_BG_CORRECTION
// Only a refused start ends the run; a refused poll waits for the next poll or the deadline
if (this->buffer_data_[COMMAND] == CMD_BG_CORRECTION_START) {
if (frame[COMMAND] == CMD_BG_CORRECTION_START) {
this->finish_background_correction_(BgCorrectionResult::BG_CORRECTION_RESULT_REFUSED);
}
#endif
return;
return true;
}
switch (this->buffer_data_[COMMAND]) {
switch (frame[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -400,10 +397,10 @@ void LD2410Component::handle_ack_data_() {
break;
case CMD_QUERY_VERSION: {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -414,12 +411,12 @@ void LD2410Component::handle_ack_data_() {
}
case CMD_QUERY_DISTANCE_RESOLUTION: {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
if (len < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the resolution
}
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, frame[10]);
if (!index) {
ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
ESP_LOGW(TAG, "Unknown distance resolution %u", frame[10]);
break;
}
ESP_LOGV(TAG, "Distance resolution: %s",
@@ -431,12 +428,12 @@ void LD2410Component::handle_ack_data_() {
}
case CMD_QUERY_LIGHT_CONTROL: {
if (this->buffer_pos_ < 13 + HEADER_FOOTER_SIZE) {
if (len < 13 + HEADER_FOOTER_SIZE) {
break; // too short to hold the light settings
}
this->light_function_ = this->buffer_data_[10];
this->light_threshold_ = this->buffer_data_[11];
this->out_pin_level_ = this->buffer_data_[12];
this->light_function_ = frame[10];
this->light_threshold_ = frame[11];
this->out_pin_level_ = frame[12];
ESP_LOGV(TAG, "Light function: %u, threshold: %u, out pin level: %u", this->light_function_,
this->light_threshold_, this->out_pin_level_);
#ifdef USE_SELECT
@@ -449,11 +446,11 @@ void LD2410Component::handle_ack_data_() {
break;
}
case CMD_QUERY_MAC_ADDRESS: {
if (this->buffer_pos_ < 20) {
if (len < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
@@ -477,7 +474,7 @@ void LD2410Component::handle_ack_data_() {
break;
case CMD_BG_CORRECTION_QUERY: {
const uint8_t status = this->buffer_data_[10];
const uint8_t status = frame[10];
ESP_LOGV(TAG, "Background correction status: %u", status);
// The module stops at idle after a fail frame; idle before the run starts is ignored
if (status == BG_CORRECTION_COMPLETED ||
@@ -506,70 +503,55 @@ void LD2410Component::handle_ack_data_() {
break;
case CMD_QUERY: { // Query parameters response
if (this->buffer_pos_ < 38) {
if (len < 38) {
break; // too short to hold the parameters
}
if (this->buffer_data_[10] != HEADER)
return; // value head=0xAA
if (frame[10] != HEADER)
return true; // value head=0xAA
#ifdef USE_NUMBER
/*
Moving distance range: 13th byte
Still distance range: 14th byte
*/
set_number_value(this->max_move_distance_gate_number_, this->buffer_data_[12]);
set_number_value(this->max_still_distance_gate_number_, this->buffer_data_[13]);
set_number_value(this->max_move_distance_gate_number_, frame[12]);
set_number_value(this->max_still_distance_gate_number_, frame[13]);
/*
Moving Sensitivities: 15~23th bytes
*/
for (size_t i = 0; i < TOTAL_GATES; i++) {
set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[14 + i]);
set_number_value(this->gate_move_threshold_numbers_[i], frame[14 + i]);
}
/*
Still Sensitivities: 24~32th bytes
*/
for (size_t i = 0; i < TOTAL_GATES; i++) {
set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[23 + i]);
set_number_value(this->gate_still_threshold_numbers_[i], frame[23 + i]);
}
/*
None Duration: 33~34th bytes
*/
set_number_value(this->timeout_number_, encode_uint16(this->buffer_data_[33], this->buffer_data_[32]));
set_number_value(this->timeout_number_, encode_uint16(frame[33], frame[32]));
#endif
break;
}
default:
break;
}
return true;
}
void LD2410Component::readline_(int readch) {
if (readch < 0) {
return; // No data available
}
// Periodic and command frames both carry their count after the header
ld24xx::feed_frame_byte(
this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld24xx::cmd_frame_length,
[this](uint8_t frame_len) { return this->handle_frame_(frame_len); }, []() { ESP_LOGW(TAG, "Invalid length"); });
}
// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
bool LD2410Component::handle_frame_(uint8_t frame_len) {
this->buffer_pos_ = frame_len; // the handlers take the frame length from here
const uint8_t *tail = &this->buffer_data_[frame_len - HEADER_FOOTER_SIZE];
if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
if (!ld2410::validate_header_footer(DATA_FRAME_FOOTER, tail)) {
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->handle_periodic_data_();
return true;
}
if (!ld2410::validate_header_footer(CMD_FRAME_FOOTER, tail)) {
// Handles the frame when its footer is in place; returns false otherwise
bool LD2410Component::handle_frame_(const uint8_t *frame, uint8_t len) {
if (!ld24xx::has_footer(frame, len)) {
ESP_LOGW(TAG, "Invalid footer");
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
if (frame[0] == ld24xx::DataFrameFormat::FIRST) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
return this->handle_periodic_data_(frame, len);
}
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
return this->handle_ack_data_(frame, len);
}
void LD2410Component::set_config_mode_(bool enable) {
+6 -6
View File
@@ -24,6 +24,7 @@
#endif
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <array>
@@ -145,10 +146,9 @@ class LD2410Component final : public Component, public uart::UARTDevice {
protected:
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len);
void set_config_mode_(bool enable);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void readline_(int readch);
bool handle_periodic_data_(const uint8_t *frame, uint8_t len);
bool handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void query_parameters_();
void get_version_();
void get_mac_();
@@ -161,11 +161,11 @@ class LD2410Component final : public Component, public uart::UARTDevice {
void publish_calibration_result_(BgCorrectionResult result);
#endif
uint32_t last_rx_{0};
uint8_t light_function_ = 0;
uint8_t light_threshold_ = 0;
uint8_t out_pin_level_ = 0;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
uint8_t buffer_data_[MAX_LINE_LENGTH];
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat> reader_;
uint8_t mac_address_[MAC_ADDRESS_SIZE] = {0, 0, 0, 0, 0, 0};
uint8_t version_[6] = {0, 0, 0, 0, 0, 0};
bool bluetooth_on_{false};
+39 -140
View File
@@ -9,16 +9,12 @@ namespace esphome::ld2410s {
ESPHOME_LOG_TAG(TAG, "ld2410s");
static constexpr uint8_t SHORT_DATA_FRAME_HEADER = 0x6E;
static constexpr uint8_t SHORT_DATA_FRAME_FOOTER[] PROGMEM = {0x62};
static constexpr uint8_t SHORT_DATA_FRAME_SIZE = 5; // header, state, distance low, distance high, footer
static constexpr uint8_t STD_DATA_FRAME_HEADER[] PROGMEM = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t STD_DATA_FRAME_FOOTER[] PROGMEM = {0xF8, 0xF7, 0xF6, 0xF5};
static constexpr uint8_t CMD_FRAME_HEADER[] PROGMEM = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[] PROGMEM = {0x04, 0x03, 0x02, 0x01};
static constexpr uint8_t LONG_HEADER_SIZE = 4;
static constexpr uint8_t LENGTH_FIELD_SIZE = 2;
static constexpr uint8_t LONG_PAYLOAD_POS = LONG_HEADER_SIZE + LENGTH_FIELD_SIZE;
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
static constexpr uint8_t SHORT_DATA_FRAME_FOOTER = 0x62;
using ld24xx::HEADER_FOOTER_SIZE;
// After the header and the two byte length
static constexpr uint8_t LONG_PAYLOAD_POS = ld24xx::PayloadLength::KNOWN_AT;
static constexpr uint16_t CMD_CONFIRMATION = 0x0100; // set in the command word of an acknowledgement
static constexpr uint16_t CONFIG_MODE_START_CMD = 0x00FF;
@@ -98,10 +94,9 @@ void LD2410SComponent::dump_config() {
}
void LD2410SComponent::loop() {
if (!this->read_available<16>([this](uint8_t b) { this->receive_byte_(b); })) {
ESP_LOGV(TAG, "UART read failed");
}
const uint32_t now = App.get_loop_component_start_time();
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<16>(this->reader_, handler, now, this->last_rx_);
if (this->sequence_ == nullptr) {
if (!this->init_done_) {
this->start_sequence_(INIT_SEQUENCE, INIT_SEQUENCE_LENGTH, now);
@@ -211,7 +206,7 @@ void LD2410SComponent::run_sequence_(uint32_t now) {
void LD2410SComponent::send_command_(uint16_t command) {
uint8_t frame[CMD_FRAME_MAX_SIZE];
progmem_memcpy(frame, CMD_FRAME_HEADER, LONG_HEADER_SIZE);
progmem_memcpy(frame, CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
uint8_t pos = LONG_PAYLOAD_POS;
put_le16(frame + pos, command);
pos += 2;
@@ -240,138 +235,41 @@ void LD2410SComponent::send_command_(uint16_t command) {
default:
break;
}
put_le16(frame + LONG_HEADER_SIZE, pos - LONG_PAYLOAD_POS); // payload length
put_le16(frame + HEADER_FOOTER_SIZE, pos - LONG_PAYLOAD_POS); // payload length
progmem_memcpy(&frame[pos], CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
pos += sizeof(CMD_FRAME_FOOTER);
this->write_array(frame, pos);
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
char hex_buf[format_hex_pretty_size(CMD_FRAME_MAX_SIZE)];
ESP_LOGVV(TAG, "> %s", format_hex_pretty_to(hex_buf, frame, pos, ' '));
#endif
ESP_LOGVV_HEX(TAG, frame, pos, CMD_FRAME_MAX_SIZE, "> %s");
}
void LD2410SComponent::receive_byte_(uint8_t byte) {
if (this->rx_len_ >= RX_BUFFER_SIZE) {
this->reset_frame_();
}
this->rx_buffer_[this->rx_len_++] = byte;
if (this->frame_type_ == FrameType::NONE) {
if (this->rx_len_ == 1 && byte == SHORT_DATA_FRAME_HEADER) {
this->frame_type_ = FrameType::SHORT_DATA;
this->expected_len_ = SHORT_DATA_FRAME_SIZE;
return;
}
// The two long headers are told apart once all four bytes are in
uint8_t std_header[LONG_HEADER_SIZE];
uint8_t cmd_header[LONG_HEADER_SIZE];
progmem_memcpy(std_header, STD_DATA_FRAME_HEADER, LONG_HEADER_SIZE);
progmem_memcpy(cmd_header, CMD_FRAME_HEADER, LONG_HEADER_SIZE);
const bool std_prefix = memcmp(this->rx_buffer_, std_header, this->rx_len_) == 0;
const bool cmd_prefix = memcmp(this->rx_buffer_, cmd_header, this->rx_len_) == 0;
if (std_prefix || cmd_prefix) {
if (this->rx_len_ == LONG_HEADER_SIZE) {
this->frame_type_ = std_prefix ? FrameType::STD_DATA : FrameType::COMMAND;
}
return;
}
// Not a header: drop what was collected, and try this byte as the start of the next frame
const bool retry = this->rx_len_ > 1;
this->reset_frame_();
if (retry) {
this->receive_byte_(byte);
}
return;
}
if (this->expected_len_ == 0) {
if (this->rx_len_ < LONG_PAYLOAD_POS) {
return;
}
// Standard data and command frames carry a little-endian payload length after the header
const uint16_t payload_len =
encode_uint16(this->rx_buffer_[LONG_HEADER_SIZE + 1], this->rx_buffer_[LONG_HEADER_SIZE]);
if (payload_len > RX_BUFFER_SIZE - LONG_PAYLOAD_POS - sizeof(CMD_FRAME_FOOTER)) {
ESP_LOGV(TAG, "Dropping frame with a %u byte payload, larger than the receive buffer", payload_len);
this->count_dropped_frame_();
this->reset_frame_();
return;
}
this->expected_len_ = LONG_PAYLOAD_POS + payload_len + sizeof(CMD_FRAME_FOOTER);
return;
}
if (this->rx_len_ < this->expected_len_) {
return;
}
if (this->handle_frame_() || this->rescanning_) {
this->reset_frame_();
return;
}
// A truncated long frame swallowed the bytes that followed it; try them again as new frames, once
uint8_t rest[RX_BUFFER_SIZE];
const uint8_t rest_len = this->rx_len_ - 1;
memcpy(rest, &this->rx_buffer_[1], rest_len);
this->reset_frame_();
this->rescanning_ = true;
for (uint8_t i = 0; i < rest_len; i++) {
this->receive_byte_(rest[i]);
}
this->rescanning_ = false;
}
bool LD2410SComponent::handle_frame_() {
const uint8_t *footer_src;
uint8_t footer_size = sizeof(CMD_FRAME_FOOTER);
uint8_t payload_pos = LONG_PAYLOAD_POS;
switch (this->frame_type_) {
case FrameType::SHORT_DATA:
footer_src = SHORT_DATA_FRAME_FOOTER;
footer_size = sizeof(SHORT_DATA_FRAME_FOOTER);
payload_pos = 1;
break;
case FrameType::STD_DATA:
footer_src = STD_DATA_FRAME_FOOTER;
break;
default:
footer_src = CMD_FRAME_FOOTER;
break;
}
uint8_t footer[sizeof(CMD_FRAME_FOOTER)];
progmem_memcpy(footer, footer_src, footer_size);
if (memcmp(&this->rx_buffer_[this->rx_len_ - footer_size], footer, footer_size) != 0) {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(RX_BUFFER_SIZE)];
ESP_LOGV(TAG, "Footer does not match header: %s",
format_hex_pretty_to(hex_buf, this->rx_buffer_, this->rx_len_, ' '));
#endif
bool LD2410SComponent::handle_frame_(const uint8_t *frame, uint8_t len) {
const uint8_t type = frame[0];
const bool short_frame = type == ShortDataFrameFormat::FIRST;
if (short_frame ? frame[len - 1] != SHORT_DATA_FRAME_FOOTER : !ld24xx::has_footer(frame, len)) {
ESP_LOGV_HEX(TAG, frame, len, RX_BUFFER_SIZE, "Footer does not match header: %s");
this->count_dropped_frame_();
return false;
}
const uint8_t *payload = &this->rx_buffer_[payload_pos];
const uint16_t payload_len = this->rx_len_ - payload_pos - footer_size;
switch (this->frame_type_) {
case FrameType::SHORT_DATA:
case FrameType::STD_DATA:
if (!this->handle_data_frame_(payload, payload_len)) {
this->count_dropped_frame_();
break;
}
this->last_frame_at_ = App.get_loop_component_start_time();
this->dropped_frames_ = 0;
break;
default:
this->handle_command_ack_(payload, payload_len);
break;
const uint8_t payload_pos = short_frame ? 1 : LONG_PAYLOAD_POS;
const uint8_t *payload = &frame[payload_pos];
const uint16_t payload_len = len - payload_pos - (short_frame ? 1 : HEADER_FOOTER_SIZE);
if (type == ld24xx::CmdFrameFormat::FIRST) {
return this->handle_command_ack_(payload, payload_len);
}
if (!this->handle_data_frame_(payload, payload_len, type == ld24xx::DataFrameFormat::FIRST)) {
this->count_dropped_frame_();
return false;
}
this->last_frame_at_ = App.get_loop_component_start_time();
this->dropped_frames_ = 0;
return true;
}
bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len) {
bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len, bool standard) {
// Short frames carry [state][distance low][distance high]; standard frames put a type byte first, and the
// module only sends them before the init sequence switches it to minimal output
const uint8_t *data = payload;
if (this->frame_type_ == FrameType::STD_DATA) {
if (standard) {
if (len < 4 || payload[0] != DATA_TYPE_STANDARD) {
if (len >= 1) {
ESP_LOGV(TAG, "Ignoring data frame type %02X", payload[0]);
@@ -392,21 +290,21 @@ bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len)
return true;
}
void LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len) {
bool LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len) {
if (len < 4) {
ESP_LOGV(TAG, "Acknowledgement too short (%u bytes)", len);
return;
return false;
}
const uint16_t command_word = encode_uint16(payload[1], payload[0]);
const uint16_t ack = encode_uint16(payload[3], payload[2]);
if (!this->awaiting_ack_) {
ESP_LOGV(TAG, "Unexpected acknowledgement %04X", command_word);
return;
return true;
}
const uint16_t command = this->current_command_();
if (command_word != (command | CMD_CONFIRMATION)) {
ESP_LOGV(TAG, "Unexpected acknowledgement %04X", command_word);
return;
return true;
}
#ifdef USE_LD2410S_PARAMETERS
if (ack != 0 && command == PARAMETERS_WRITE_CMD) {
@@ -415,29 +313,29 @@ void LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len)
ESP_LOGW(TAG, "Module rejected the parameters, ack %04X", ack);
this->send_command_(CONFIG_MODE_END_CMD);
this->restart_init_(App.get_loop_component_start_time() + COMMAND_GAP_MS);
return;
return true;
}
#endif
if (ack != 0) {
// Leave the command pending so the timeout resends it
ESP_LOGW(TAG, "Module rejected command %04X, ack %04X", command, ack);
return;
return true;
}
// A short answer leaves the read pending the same way, so init cannot finish without the values
#ifdef USE_LD2410S_PARAMETERS
if (command == PARAMETERS_READ_CMD && !this->handle_parameters_(&payload[4], len - 4))
return;
return false;
#endif
#ifdef USE_LD2410S_VERSION
if (command == VERSION_READ_CMD && !this->handle_version_(&payload[4], len - 4))
return;
return false;
#endif
this->awaiting_ack_ = false;
this->step_timeouts_ = 0;
const uint32_t now = App.get_loop_component_start_time();
this->next_send_at_ = now + COMMAND_GAP_MS;
if (++this->step_ < this->sequence_len_) {
return;
return true;
}
const bool was_init = this->sequence_ == INIT_SEQUENCE;
this->sequence_ = nullptr;
@@ -447,6 +345,7 @@ void LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len)
this->last_frame_at_ = now;
this->status_clear_warning();
}
return true;
}
#ifdef USE_LD2410S_PARAMETERS
+10 -18
View File
@@ -2,6 +2,7 @@
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/components/uart/uart.h"
#ifdef USE_BINARY_SENSOR
@@ -9,8 +10,8 @@
#endif
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ld24xx/ld24xx.h"
#endif
#include "esphome/components/ld24xx/ld24xx.h"
#ifdef USE_LD2410S_VERSION
#include "esphome/components/text_sensor/text_sensor.h"
#endif
@@ -26,6 +27,8 @@ namespace esphome::ld2410s {
// Largest frame read here is the standard data frame: 4 header + 2 length + payload + 4 footer
static constexpr size_t RX_BUFFER_SIZE = 96;
static_assert(RX_BUFFER_SIZE <= 255, "frame lengths are kept in a byte");
// Minimal output: header, state, distance low, distance high, footer
using ShortDataFrameFormat = FrameFormat<FrameHeader<0x6E>, FrameFixedLength<5>>;
/// The module's common parameters, in the order the parameter read answers them
enum class Parameter : uint8_t {
@@ -78,14 +81,11 @@ class LD2410SComponent final : public Component, public uart::UARTDevice {
#endif
protected:
enum class FrameType : uint8_t { NONE, SHORT_DATA, STD_DATA, COMMAND };
void receive_byte_(uint8_t byte);
/// Returns false when the footer does not match, so the bytes can be scanned again.
bool handle_frame_();
/// Returns false for bytes that are not a real frame.
bool handle_frame_(const uint8_t *frame, uint8_t len);
/// Returns false for a data frame whose state byte is impossible, so it counts as dropped.
bool handle_data_frame_(const uint8_t *payload, uint16_t len);
void handle_command_ack_(const uint8_t *payload, uint16_t len);
bool handle_data_frame_(const uint8_t *payload, uint16_t len, bool standard);
bool handle_command_ack_(const uint8_t *payload, uint16_t len);
#ifdef USE_LD2410S_PARAMETERS
bool handle_parameters_(const uint8_t *values, uint16_t len);
#endif
@@ -97,11 +97,6 @@ class LD2410SComponent final : public Component, public uart::UARTDevice {
this->dropped_frames_++;
}
}
void reset_frame_() {
this->rx_len_ = 0;
this->expected_len_ = 0;
this->frame_type_ = FrameType::NONE;
}
void start_sequence_(const uint16_t *sequence, uint8_t length, uint32_t now);
void restart_init_(uint32_t at);
void run_sequence_(uint32_t now);
@@ -119,19 +114,16 @@ class LD2410SComponent final : public Component, public uart::UARTDevice {
const uint16_t *sequence_{nullptr}; // PROGMEM; null while nothing is being sent
uint32_t next_send_at_{0};
uint32_t last_frame_at_{0};
uint32_t last_rx_{0};
#ifdef USE_LD2410S_PARAMETERS
uint8_t parameters_[PARAMETER_COUNT]{}; // all fit a byte: gates, seconds, tenths of a hertz, speed
#endif
uint8_t rx_buffer_[RX_BUFFER_SIZE];
uint8_t rx_len_{0};
uint8_t expected_len_{0};
LengthFrameReader<RX_BUFFER_SIZE, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat, ShortDataFrameFormat> reader_;
uint8_t sequence_len_{0};
uint8_t step_{0};
uint8_t step_timeouts_{0};
uint8_t dropped_frames_{0}; // since the last accepted data frame, saturates at 255
FrameType frame_type_{FrameType::NONE};
bool awaiting_ack_{false};
bool rescanning_{false};
bool init_done_{false};
#ifdef USE_LD2410S_PARAMETERS
bool parameters_known_{false}; // the module answered the parameter read at least once
+64 -83
View File
@@ -113,13 +113,9 @@ static constexpr uint8_t STILL_BITMASK = 0x02;
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
using ld24xx::HEADER_FOOTER_SIZE;
using ld24xx::validate_header_footer;
// Smallest frames whose values can all be read: the last value, data footer and check, then the frame footer
static constexpr uint8_t PERIODIC_FRAME_MIN = STILL_ENERGY + 3 + HEADER_FOOTER_SIZE;
static constexpr uint8_t ENGINEERING_FRAME_MIN = LIGHT_SENSOR + 3 + HEADER_FOOTER_SIZE;
// Data Header & Footer
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
static constexpr uint8_t GATE_SENS_ACK_SIZE = ACK_PAYLOAD + TOTAL_GATES + HEADER_FOOTER_SIZE;
void LD2412Component::dump_config() {
@@ -234,13 +230,14 @@ void LD2412Component::restart_and_read_all_info() {
}
void LD2412Component::loop() {
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_LINE_LENGTH>(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
}
void LD2412Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
ESP_LOGV(TAG, "Sending COMMAND %02X", command);
// frame header bytes
this->write_array(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
this->write_array_progmem(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -255,7 +252,7 @@ void LD2412Component::send_command_(uint8_t command, const uint8_t *command_valu
this->write_array(command_value, command_value_len);
}
// frame footer bytes
this->write_array(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
this->write_array_progmem(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(30); // NOLINT
@@ -263,21 +260,20 @@ void LD2412Component::send_command_(uint8_t command, const uint8_t *command_valu
delay(20); // NOLINT
}
void LD2412Component::handle_periodic_data_() {
bool LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
// 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
// data header=0xAA, data footer=0x55, crc=0x00
if (this->buffer_pos_ < 12 || !ld2412::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER) {
return;
if (len < 12 || frame[7] != HEADER || frame[len - 6] != FOOTER) {
return false;
}
/*
Data Type: 7th
0x01: Engineering mode
0x02: Normal mode
*/
bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
if (this->buffer_pos_ < PERIODIC_FRAME_MIN) {
return; // too short to hold the values
bool engineering_mode = frame[DATA_TYPES] == 0x01;
if (len < PERIODIC_FRAME_MIN) {
return false; // too short to hold the values
}
#ifdef USE_SWITCH
PUBLISH_STATE(this->engineering_mode_switch_, engineering_mode);
@@ -291,7 +287,7 @@ void LD2412Component::handle_periodic_data_() {
0x02 = Still targets
0x03 = Moving+Still targets
*/
char target_state = this->buffer_data_[TARGET_STATES];
char target_state = frame[TARGET_STATES];
PUBLISH_STATE(this->target_binary_sensor_, target_state != 0x00);
PUBLISH_STATE(this->moving_target_binary_sensor_, target_state & MOVE_BITMASK);
PUBLISH_STATE(this->still_target_binary_sensor_, target_state & STILL_BITMASK);
@@ -305,24 +301,23 @@ void LD2412Component::handle_periodic_data_() {
*/
#ifdef USE_SENSOR
SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY]);
encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, frame[MOVING_ENERGY]);
SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY]);
encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, frame[STILL_ENERGY]);
if (this->detection_distance_sensor_.has_sensor()) {
int new_detect_distance = 0;
if (target_state != 0x00 && (target_state & MOVE_BITMASK)) {
new_detect_distance =
encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]);
new_detect_distance = encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]);
} else if (target_state != 0x00) {
new_detect_distance = encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]);
new_detect_distance = encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]);
}
this->detection_distance_sensor_.publish_state_if_not_dup(new_detect_distance);
}
if (engineering_mode) {
if (this->buffer_pos_ < ENGINEERING_FRAME_MIN) {
ESP_LOGW(TAG, "Engineering mode packet too short: %u", this->buffer_pos_);
if (len < ENGINEERING_FRAME_MIN) {
ESP_LOGW(TAG, "Engineering mode packet too short: %u", len);
} else {
/*
Moving distance range: 18th byte
@@ -330,18 +325,18 @@ void LD2412Component::handle_periodic_data_() {
Moving energy: 20~28th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], frame[MOVING_SENSOR_START + i]);
}
/*
Still energy: 29~37th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], frame[STILL_SENSOR_START + i]);
}
/*
Light sensor value
*/
SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
SAFE_PUBLISH_SENSOR(this->light_sensor_, frame[LIGHT_SENSOR]);
}
} else {
for (auto &gate_move_sensor : this->gate_move_sensors_) {
@@ -359,6 +354,7 @@ void LD2412Component::handle_periodic_data_() {
this->query_dynamic_background_correction_();
this->set_config_mode_(false);
}
return true;
}
#ifdef USE_NUMBER
@@ -378,18 +374,18 @@ static constexpr uint32_t GATE_QUERY_TIMEOUT_ID = 0;
static constexpr uint32_t BASIC_CONF_TIMEOUT_ID = 2;
static constexpr uint32_t QUERY_TIMEOUT_MS = 2000;
void LD2412Component::handle_ack_data_() {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", frame[COMMAND]);
if (frame[COMMAND_STATUS] != 0x01) {
ESP_LOGW(TAG, "Invalid status");
return;
return false;
}
if (this->buffer_data_[8] || this->buffer_data_[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
return;
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
return true;
}
switch (this->buffer_data_[COMMAND]) {
switch (frame[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -409,10 +405,10 @@ void LD2412Component::handle_ack_data_() {
break;
case CMD_QUERY_VERSION: {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -422,12 +418,12 @@ void LD2412Component::handle_ack_data_() {
break;
}
case CMD_QUERY_DISTANCE_RESOLUTION: {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
if (len < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the resolution
}
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, frame[10]);
if (!index) {
ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
ESP_LOGW(TAG, "Unknown distance resolution %u", frame[10]);
break;
}
ESP_LOGV(TAG, "Distance resolution: %s",
@@ -439,11 +435,11 @@ void LD2412Component::handle_ack_data_() {
}
case CMD_QUERY_LIGHT_CONTROL: {
if (this->buffer_pos_ < 12 + HEADER_FOOTER_SIZE) {
if (len < 12 + HEADER_FOOTER_SIZE) {
break; // too short to hold the light settings
}
this->light_function_ = this->buffer_data_[10];
this->light_threshold_ = this->buffer_data_[11];
this->light_function_ = frame[10];
this->light_threshold_ = frame[11];
ESP_LOGV(TAG, "Light function: %u, threshold: %u", this->light_function_, this->light_threshold_);
#ifdef USE_SELECT
PUBLISH_STATE(this->light_function_select_, static_cast<size_t>(this->light_function_));
@@ -455,11 +451,11 @@ void LD2412Component::handle_ack_data_() {
}
case CMD_QUERY_MAC_ADDRESS: {
if (this->buffer_pos_ < 20) {
if (len < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
@@ -478,11 +474,11 @@ void LD2412Component::handle_ack_data_() {
break;
case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
if (len < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the state
}
ESP_LOGV(TAG, "Handled query dynamic background correction");
bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
bool dynamic_background_correction_active = (frame[10] != 0x00);
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->dynamic_background_correction_status_binary_sensor_, dynamic_background_correction_active);
#endif
@@ -501,17 +497,17 @@ void LD2412Component::handle_ack_data_() {
case CMD_QUERY_MOTION_GATE_SENS:
case CMD_QUERY_STATIC_GATE_SENS: {
#ifdef USE_NUMBER
if (this->buffer_pos_ != GATE_SENS_ACK_SIZE) {
if (len != GATE_SENS_ACK_SIZE) {
// A length this driver does not know
ESP_LOGW(TAG, "Dropping gate threshold answer of %u bytes", this->buffer_pos_);
return;
ESP_LOGW(TAG, "Dropping gate threshold answer of %u bytes", len);
return true;
}
const bool motion = this->buffer_data_[COMMAND] == CMD_QUERY_MOTION_GATE_SENS;
const bool motion = frame[COMMAND] == CMD_QUERY_MOTION_GATE_SENS;
GateThresholds &group = this->gate_thresholds_(motion);
// True only while a held-back write waits for this answer
const bool pending = this->cancel_timeout(GATE_QUERY_TIMEOUT_ID + motion);
for (size_t i = 0; i < TOTAL_GATES; i++) {
group.last_read[i] = this->buffer_data_[ACK_PAYLOAD + i];
group.last_read[i] = frame[ACK_PAYLOAD + i];
// The pending write's user values must survive the answer
if (!pending || !has_value(group.numbers[i])) {
set_number_value(group.numbers[i], group.last_read[i]);
@@ -528,17 +524,17 @@ void LD2412Component::handle_ack_data_() {
}
case CMD_QUERY_BASIC_CONF: { // Query parameters response
if (this->buffer_pos_ < 15 + HEADER_FOOTER_SIZE) {
if (len < 15 + HEADER_FOOTER_SIZE) {
break; // too short to hold the configuration
}
// True only while a held-back write waits for this answer
const bool pending = this->cancel_timeout(BASIC_CONF_TIMEOUT_ID);
this->basic_conf_read_ = true;
// Min gate: 9th byte, max gate: 10th byte, timeout: 11~12th bytes, output pin level: 13th byte
this->min_gate_ = this->buffer_data_[10];
this->max_gate_ = this->buffer_data_[11];
this->timeout_ = encode_uint16(this->buffer_data_[13], this->buffer_data_[12]);
this->out_pin_level_ = this->buffer_data_[14];
this->min_gate_ = frame[10];
this->max_gate_ = frame[11];
this->timeout_ = encode_uint16(frame[13], frame[12]);
this->out_pin_level_ = frame[14];
ESP_LOGV(TAG, "min_distance_gate_number_: %u, max_distance_gate_number_ %u", this->min_gate_, this->max_gate_);
ESP_LOGV(TAG, "timeout_number_: %u", this->timeout_);
// The pending write's user values must survive the answer
@@ -568,36 +564,21 @@ void LD2412Component::handle_ack_data_() {
default:
break;
}
return true;
}
void LD2412Component::readline_(int readch) {
if (readch < 0) {
return; // No data available
}
// Periodic and command frames both carry their count after the header
ld24xx::feed_frame_byte(
this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld24xx::cmd_frame_length,
[this](uint8_t frame_len) { return this->handle_frame_(frame_len); }, []() { ESP_LOGW(TAG, "Invalid length"); });
}
// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
bool LD2412Component::handle_frame_(uint8_t frame_len) {
this->buffer_pos_ = frame_len; // the handlers take the frame length from here
const uint8_t *tail = &this->buffer_data_[frame_len - HEADER_FOOTER_SIZE];
if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
if (!ld2412::validate_header_footer(DATA_FRAME_FOOTER, tail)) {
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->handle_periodic_data_();
return true;
}
if (!ld2412::validate_header_footer(CMD_FRAME_FOOTER, tail)) {
// Handles the frame when its footer is in place; returns false otherwise
bool LD2412Component::handle_frame_(const uint8_t *frame, uint8_t len) {
if (!ld24xx::has_footer(frame, len)) {
ESP_LOGW(TAG, "Invalid footer");
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
if (frame[0] == ld24xx::DataFrameFormat::FIRST) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
return this->handle_periodic_data_(frame, len);
}
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
return this->handle_ack_data_(frame, len);
}
void LD2412Component::set_config_mode_(bool enable) {
+6 -6
View File
@@ -25,6 +25,7 @@
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <array>
@@ -134,11 +135,10 @@ class LD2412Component final : public Component, public uart::UARTDevice {
protected:
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len);
void set_config_mode_(bool enable);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
bool handle_periodic_data_(const uint8_t *frame, uint8_t len);
bool handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void basic_conf_timeout_();
void readline_(int readch);
void query_parameters_();
void get_version_();
void get_mac_();
@@ -160,6 +160,7 @@ class LD2412Component final : public Component, public uart::UARTDevice {
void gate_query_timeout_(bool motion);
#endif
uint32_t last_rx_{0};
uint8_t light_function_ = 0;
uint8_t light_threshold_ = 0;
// Basic configuration as last reported by the module; resent for entities that are not configured
@@ -168,8 +169,7 @@ class LD2412Component final : public Component, public uart::UARTDevice {
uint8_t min_gate_ = 1;
uint8_t max_gate_ = TOTAL_GATES;
uint8_t out_pin_level_ = 1;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
uint8_t buffer_data_[MAX_LINE_LENGTH];
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat> reader_;
uint8_t mac_address_[MAC_ADDRESS_SIZE] = {0, 0, 0, 0, 0, 0};
uint8_t version_[6] = {0, 0, 0, 0, 0, 0};
bool bluetooth_on_{false};
+55 -90
View File
@@ -71,14 +71,10 @@ static constexpr uint8_t CMD_SET_ZONE = 0xC2;
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
using ld24xx::HEADER_FOOTER_SIZE;
using ld24xx::validate_header_footer;
// Data Header & Footer
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xAA, 0xFF, 0x03, 0x00};
static constexpr uint8_t DATA_FRAME_FOOTER[2] = {0x55, 0xCC};
static constexpr uint8_t PERIODIC_FRAME_FOOTER[2] = {0x55, 0xCC};
// Successful zone query ACK: header (4) + length (2) + command/status (2) + result (2) + zone type (2) +
// 3 zones * 8 + footer (4).
static constexpr uint8_t ZONE_ACK_FRAME_SIZE = 40;
static constexpr uint8_t PERIODIC_FRAME_SIZE = 30; // header, three targets of 8 bytes, footer
static inline uint32_t convert_seconds_to_ms(uint16_t value) { return (uint32_t) value * 1000; };
@@ -104,22 +100,10 @@ static inline int16_t decode_speed(uint8_t low_byte, uint8_t high_byte) {
return speed * 10; // mm/s
}
// Length of the frame that opens the buffer: periodic frames are fixed size, command frames carry their
// payload length after the header. readline_ only buffers a valid header, so its first byte names it.
// Returns 0 while the length field has not arrived yet.
static inline uint32_t frame_length(const uint8_t *buffer, uint8_t len) {
if (len < HEADER_FOOTER_SIZE) {
return 0;
}
if (buffer[0] == DATA_FRAME_HEADER[0]) {
return PERIODIC_FRAME_SIZE;
}
return ld24xx::cmd_frame_length(buffer, len);
}
void LD2450Component::setup() {
// The first frame is due link_timeout after the boot restart's grace window
this->last_frame_ms_ = App.get_loop_component_start_time();
this->last_rx_ = this->last_frame_ms_;
this->link_deadline_ms_ = this->last_frame_ms_ + this->link_timeout_ms_;
#ifdef USE_BINARY_SENSOR
if (this->connected_binary_sensor_ != nullptr) {
@@ -241,12 +225,8 @@ void LD2450Component::dump_config() {
}
void LD2450Component::loop() {
// Before reading, so a frame in this pass resets it
const size_t count = this->available();
if (count != 0) {
this->bytes_since_frame_ = true;
}
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); }, count);
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_LINE_LENGTH>(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
this->check_link_();
}
@@ -289,7 +269,6 @@ void LD2450Component::on_valid_frame_() {
this->link_deadline_ms_ = later_ms(window, due);
}
this->last_frame_ms_ = now;
this->bytes_since_frame_ = false;
this->invalid_frames_ = 0;
if (previous != LinkState::LINK_STATE_UP) {
this->link_state_ = LinkState::LINK_STATE_UP;
@@ -323,7 +302,7 @@ void LD2450Component::publish_target_unknown_(uint8_t target) {
// Live values become unknown; settings and diagnostics keep theirs
void LD2450Component::on_link_lost_(uint32_t silent_ms, bool was_up) {
ESP_LOGW(TAG, "Radar link lost: no valid frame for %" PRIu32 " ms (%s, %u invalid frames)", silent_ms,
this->bytes_since_frame_ ? LOG_STR_LITERAL("bytes received") : LOG_STR_LITERAL("no bytes received"),
this->bytes_since_frame_() ? LOG_STR_LITERAL("bytes received") : LOG_STR_LITERAL("no bytes received"),
static_cast<unsigned>(this->invalid_frames_));
this->status_set_warning();
#ifdef USE_BINARY_SENSOR
@@ -447,14 +426,14 @@ bool LD2450Component::get_timeout_status_(uint32_t check_millis) {
}
// Extract, store and publish zone details LD2450 buffer
void LD2450Component::process_zone_() {
void LD2450Component::process_zone_(const uint8_t *frame) {
uint8_t index, start;
for (index = 0; index < MAX_ZONES; index++) {
start = 12 + index * 8;
this->zone_config_[index].x1 = encode_value_le<int16_t>(&this->buffer_data_[start]);
this->zone_config_[index].y1 = encode_value_le<int16_t>(&this->buffer_data_[start + 2]);
this->zone_config_[index].x2 = encode_value_le<int16_t>(&this->buffer_data_[start + 4]);
this->zone_config_[index].y2 = encode_value_le<int16_t>(&this->buffer_data_[start + 6]);
this->zone_config_[index].x1 = encode_value_le<int16_t>(&frame[start]);
this->zone_config_[index].y1 = encode_value_le<int16_t>(&frame[start + 2]);
this->zone_config_[index].x2 = encode_value_le<int16_t>(&frame[start + 4]);
this->zone_config_[index].y2 = encode_value_le<int16_t>(&frame[start + 6]);
#ifdef USE_NUMBER
// only one null check as all coordinates are required for a single zone
if (this->zone_numbers_[index].x1 != nullptr) {
@@ -504,7 +483,7 @@ void LD2450Component::restart_and_read_all_info() {
void LD2450Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
ESP_LOGV(TAG, "Sending COMMAND %02X", command);
// frame header bytes
this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
this->write_array_progmem(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -518,7 +497,7 @@ void LD2450Component::send_command_(uint8_t command, const uint8_t *command_valu
this->write_array(command_value, command_value_len);
}
// frame footer bytes
this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
this->write_array_progmem(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(50); // NOLINT
@@ -528,7 +507,7 @@ void LD2450Component::send_command_(uint8_t command, const uint8_t *command_valu
// LD2450 Radar data message:
// [AA FF 03 00] [0E 03 B1 86 10 00 40 01] [00 00 00 00 00 00 00 00] [00 00 00 00 00 00 00 00] [55 CC]
// Header Target 1 Target 2 Target 3 End
void LD2450Component::handle_periodic_data_() {
void LD2450Component::handle_periodic_data_(const uint8_t *frame) {
int16_t target_count = 0;
int16_t still_target_count = 0;
int16_t moving_target_count = 0;
@@ -550,18 +529,18 @@ void LD2450Component::handle_periodic_data_() {
start = TARGET_X + index * 8;
is_moving = false;
// tx and ty are used for further calculations, so always need to be populated
tx = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]);
tx = ld2450::decode_coordinate(frame[start], frame[start + 1]);
// Y
start = TARGET_Y + index * 8;
ty = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]);
ty = ld2450::decode_coordinate(frame[start], frame[start + 1]);
#ifdef USE_SENSOR
// RESOLUTION
start = TARGET_RESOLUTION + index * 8;
res = encode_value_le<uint16_t>(&this->buffer_data_[start]);
res = encode_value_le<uint16_t>(&frame[start]);
#endif
// SPEED
start = TARGET_SPEED + index * 8;
ts = ld2450::decode_speed(this->buffer_data_[start], this->buffer_data_[start + 1]);
ts = ld2450::decode_speed(frame[start], frame[start + 1]);
if (ts) {
is_moving = true;
moving_target_count++;
@@ -716,18 +695,18 @@ void LD2450Component::handle_periodic_data_() {
this->data_callback_.call();
}
void LD2450Component::handle_ack_data_() {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
bool LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", frame[COMMAND]);
if (frame[COMMAND_STATUS] != 0x01) {
ESP_LOGE(TAG, "Invalid status");
return;
return false;
}
if (this->buffer_data_[8] || this->buffer_data_[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
return;
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
return true;
}
switch (this->buffer_data_[COMMAND]) {
switch (frame[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -747,10 +726,10 @@ void LD2450Component::handle_ack_data_() {
break;
case CMD_QUERY_VERSION: {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -761,11 +740,11 @@ void LD2450Component::handle_ack_data_() {
}
case CMD_QUERY_MAC_ADDRESS: {
if (this->buffer_pos_ < 20) {
if (len < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
@@ -798,21 +777,21 @@ void LD2450Component::handle_ack_data_() {
break;
case CMD_QUERY_TARGET_MODE:
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
if (len < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the mode
}
ESP_LOGV(TAG, "Query target tracking mode");
#ifdef USE_SWITCH
PUBLISH_STATE(this->multi_target_switch_, this->buffer_data_[10] == 0x02);
PUBLISH_STATE(this->multi_target_switch_, frame[10] == 0x02);
#endif
break;
case CMD_QUERY_ZONE:
if (this->buffer_pos_ < ZONE_ACK_FRAME_SIZE) {
if (len < ZONE_ACK_FRAME_SIZE) {
break; // too short to hold the zones
}
ESP_LOGV(TAG, "Query zone conf");
this->zone_type_ = this->buffer_data_[10];
this->zone_type_ = frame[10];
this->publish_zone_type();
#ifdef USE_SELECT
if (this->zone_type_select_ != nullptr) {
@@ -820,16 +799,16 @@ void LD2450Component::handle_ack_data_() {
ESP_LOGV(TAG, "Change zone type to: %.*s", (int) zone.size(), zone.c_str());
}
#endif
if (this->buffer_data_[10] == 0x00) {
if (frame[10] == 0x00) {
ESP_LOGV(TAG, "Zone: Disabled");
}
if (this->buffer_data_[10] == 0x01) {
if (frame[10] == 0x01) {
ESP_LOGV(TAG, "Zone: Area detection");
}
if (this->buffer_data_[10] == 0x02) {
if (frame[10] == 0x02) {
ESP_LOGV(TAG, "Zone: Area filter");
}
this->process_zone_();
this->process_zone_(frame);
break;
case CMD_SET_ZONE:
@@ -840,43 +819,29 @@ void LD2450Component::handle_ack_data_() {
default:
break;
}
return true;
}
// Read LD2450 buffer data
void LD2450Component::readline_(int readch) {
if (readch < 0) {
return; // No data available
}
ld24xx::feed_frame_byte(
this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld2450::frame_length,
[this](uint8_t frame_len) { return this->handle_frame_(frame_len); },
[this]() {
if (this->invalid_frames_ < UINT16_MAX) {
this->invalid_frames_++;
}
ESP_LOGW(TAG, "Invalid header/footer");
});
}
// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
bool LD2450Component::handle_frame_(uint8_t frame_len) {
this->buffer_pos_ = frame_len; // the handlers take the frame length from here
const uint8_t *end = &this->buffer_data_[frame_len];
if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
if (end[-2] != DATA_FRAME_FOOTER[0] || end[-1] != DATA_FRAME_FOOTER[1]) {
return false;
// Handles the frame when its footer is in place; returns false otherwise
bool LD2450Component::handle_frame_(const uint8_t *frame, uint8_t len) {
const uint8_t *end = &frame[len];
const bool periodic = frame[0] == PeriodicFrameFormat::FIRST;
if (periodic ? end[-2] != PERIODIC_FRAME_FOOTER[0] || end[-1] != PERIODIC_FRAME_FOOTER[1]
: !ld24xx::has_footer(frame, len)) {
if (this->invalid_frames_ < UINT16_MAX) {
this->invalid_frames_++;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->on_valid_frame_();
this->handle_periodic_data_();
return true;
}
if (!ld2450::validate_header_footer(CMD_FRAME_FOOTER, end - HEADER_FOOTER_SIZE)) {
ESP_LOGW(TAG, "Invalid footer");
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
if (periodic) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->on_valid_frame_();
this->handle_periodic_data_(frame);
return true;
}
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
return this->handle_ack_data_(frame, len);
}
// Set Config Mode - Pre-requisite sending commands
+13 -9
View File
@@ -30,6 +30,7 @@
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/core/preferences.h"
@@ -46,6 +47,8 @@ static constexpr uint8_t DEFAULT_PRESENCE_TIMEOUT = 5; // Timeout to reset pres
static constexpr uint8_t MAX_LINE_LENGTH = 45;
static constexpr uint8_t MAX_TARGETS = 3; // Max 3 Targets in LD2450
static constexpr uint8_t MAX_ZONES = 3; // Max 3 Zones in LD2450
// Periodic frames: header, three targets of 8 bytes, footer; they carry no length
using PeriodicFrameFormat = FrameFormat<FrameHeader<0xAA, 0xFF, 0x03, 0x00>, FrameFixedLength<30>>;
// Silence after our own commands (restart, Bluetooth toggle, ...) is not a link loss; a restart takes about 2.3 s
static constexpr uint32_t LINK_GRACE_MS = 5000;
@@ -202,11 +205,10 @@ class LD2450Component : public Component, public uart::UARTDevice {
protected:
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len);
void set_config_mode_(bool enable);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void process_zone_();
void readline_(int readch);
void handle_periodic_data_(const uint8_t *frame);
bool handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void process_zone_(const uint8_t *frame);
void get_version_();
void get_mac_();
void query_target_tracking_mode_();
@@ -218,6 +220,9 @@ class LD2450Component : public Component, public uart::UARTDevice {
bool get_timeout_status_(uint32_t check_millis);
void open_link_grace_();
void check_link_();
bool bytes_since_frame_() const {
return static_cast<int32_t>(this->last_rx_ - this->last_frame_ms_) > 0 || this->reader_.length() != 0;
}
void on_valid_frame_();
void on_link_lost_(uint32_t silent_ms, bool was_up);
void on_link_up_(bool restored);
@@ -238,16 +243,15 @@ class LD2450Component : public Component, public uart::UARTDevice {
uint32_t timeout_ = DEFAULT_PRESENCE_TIMEOUT * 1000; // presence_timeout, in ms
uint32_t link_timeout_ms_{0};
uint32_t last_frame_ms_{0}; // last valid periodic frame; until the first one, when setup() ran
uint32_t last_rx_{0}; // last pass that read bytes
uint32_t link_deadline_ms_{0}; // the link is lost when the loop clock reaches this
uint8_t buffer_data_[MAX_LINE_LENGTH];
uint8_t mac_address_[MAC_ADDRESS_SIZE] = {0, 0, 0, 0, 0, 0};
uint8_t version_[6] = {0, 0, 0, 0, 0, 0};
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, PeriodicFrameFormat> reader_;
uint8_t zone_type_ = 0;
bool bluetooth_on_{false};
LinkState link_state_{LinkState::LINK_STATE_WAITING};
bool bytes_since_frame_{false}; // any bytes since the last valid frame
uint16_t invalid_frames_{0}; // since the last valid frame, saturating
uint16_t invalid_frames_{0}; // since the last valid frame, saturating
Target target_info_[MAX_TARGETS];
Zone zone_config_[MAX_ZONES];
#ifdef USE_TEXT_SENSOR
+33 -105
View File
@@ -1,66 +1,33 @@
#include "ld2460.h"
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <numbers>
namespace esphome::ld2460 {
ESPHOME_LOG_TAG(TAG, "ld2460");
static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
// PROGMEM keeps the patterns out of RAM on the ESP8266; they are copied out for each compare
static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] PROGMEM = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0x04, 0x03, 0x02, 0x01};
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] PROGMEM = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0xF8, 0xF7, 0xF6, 0xF5};
static constexpr uint8_t CMD_REPORT_DATA = 0x04;
static constexpr uint8_t CMD_QUERY_INSTALLATION_MODE = 0x0A;
static constexpr uint8_t ACK_FRAME_LENGTH = 12;
static constexpr uint8_t MAX_QUERY_ATTEMPTS = 3;
// Header, command, length (12, little endian), payload 0x01, footer
static constexpr uint8_t QUERY_INSTALLATION_MODE_FRAME[] PROGMEM = {
0xFD, 0xFC, 0xFB, 0xFA, CMD_QUERY_INSTALLATION_MODE, 0x0C, 0x00, 0x01, 0x04, 0x03, 0x02, 0x01,
};
static bool matches(const uint8_t *bytes, const uint8_t *pattern) {
uint8_t copy[HEADER_FOOTER_SIZE];
progmem_memcpy(copy, pattern, sizeof(copy));
return std::memcmp(bytes, copy, sizeof(copy)) == 0;
}
// Header (4), command (1), length (2, little endian); the length counts the whole frame
static constexpr uint8_t FRAME_PREFIX_SIZE = 7;
static uint16_t frame_length(const uint8_t *frame) { return encode_uint16(frame[6], frame[5]); }
// First offset after 0 whose bytes, as far as they go, match a header; len when there is none (len >= 1)
static uint8_t next_header_start(const uint8_t *buffer, uint8_t len) {
uint8_t data_header[HEADER_FOOTER_SIZE];
uint8_t cmd_header[HEADER_FOOTER_SIZE];
progmem_memcpy(data_header, DATA_FRAME_HEADER, sizeof(data_header));
progmem_memcpy(cmd_header, CMD_FRAME_HEADER, sizeof(cmd_header));
uint8_t start = 1;
for (; start < len; start++) {
const size_t n = std::min<size_t>(len - start, HEADER_FOOTER_SIZE);
if (std::memcmp(&buffer[start], data_header, n) == 0 || std::memcmp(&buffer[start], cmd_header, n) == 0) {
break;
}
}
return start;
}
static constexpr float RADIANS_TO_DEGREES = 180.0f / std::numbers::pi_v<float>;
void LD2460Component::setup() { this->send_query_(); }
// Header, command, length (12, little endian), payload 0x01, footer
static constexpr uint8_t QUERY_INSTALLATION_MODE_FRAME[] PROGMEM = {
0xFD, 0xFC, 0xFB, 0xFA, CMD_QUERY_INSTALLATION_MODE, 0x0C, 0x00, 0x01, 0x04, 0x03, 0x02, 0x01,
};
void LD2460Component::send_query_() {
uint8_t frame[sizeof(QUERY_INSTALLATION_MODE_FRAME)];
progmem_memcpy(frame, QUERY_INSTALLATION_MODE_FRAME, sizeof(frame));
this->write_array(frame, sizeof(frame));
this->write_array_progmem(QUERY_INSTALLATION_MODE_FRAME, sizeof(QUERY_INSTALLATION_MODE_FRAME));
}
void LD2460Component::dump_config() {
@@ -82,19 +49,19 @@ void LD2460Component::dump_config() {
}
void LD2460Component::loop() {
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
const uint32_t now = App.get_loop_component_start_time();
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_FRAME_LENGTH>(this->reader_, handler, now, this->last_rx_);
}
void LD2460Component::handle_periodic_data_() {
const uint8_t *data = this->buffer_data_;
if (!this->align_to_header_(DATA_FRAME_HEADER) || data[4] != CMD_REPORT_DATA) {
bool LD2460Component::handle_periodic_data_(const uint8_t *data, uint8_t packet_len) {
if (data[4] != CMD_REPORT_DATA) {
ESP_LOGW(TAG, "Invalid periodic data header");
return;
return false;
}
const uint8_t packet_len = this->buffer_pos_;
if (packet_len < 11 || (packet_len - 11) % 4 != 0) {
if ((packet_len - MIN_FRAME_LENGTH) % 4 != 0) {
ESP_LOGW(TAG, "Periodic packet length %u is not a whole number of targets", packet_len);
return;
return false;
}
if (this->query_attempts_ != 0) {
@@ -109,7 +76,7 @@ void LD2460Component::handle_periodic_data_() {
}
#ifdef USE_SENSOR
uint8_t num_targets = std::min<uint8_t>((packet_len - 11) / 4, MAX_TARGETS);
uint8_t num_targets = std::min<uint8_t>((packet_len - MIN_FRAME_LENGTH) / 4, MAX_TARGETS);
for (uint8_t i = 0; i < MAX_TARGETS; i++) {
TargetSensors &t = this->target_sensors_[i];
if (i >= num_targets) {
@@ -155,75 +122,35 @@ void LD2460Component::handle_periodic_data_() {
#endif
this->data_callback_.call();
return true;
}
void LD2460Component::readline_(uint8_t readch) {
if (this->buffer_pos_ >= MAX_LINE_LENGTH) {
// Keep the bytes from the next offset that could start a header, so a frame already partly
// buffered behind stray bytes survives; it is still fully validated once its footer arrives
const uint8_t start = next_header_start(this->buffer_data_, this->buffer_pos_);
this->buffer_pos_ -= start;
std::memmove(this->buffer_data_, &this->buffer_data_[start], this->buffer_pos_);
// Header-shaped noise keeps a whole header; warning only otherwise bounds the warning rate
if (this->buffer_pos_ < HEADER_FOOTER_SIZE) {
ESP_LOGW(TAG, "Max frame length exceeded; ignoring");
} else {
ESP_LOGV(TAG, "Max frame length exceeded; kept %u bytes", this->buffer_pos_);
}
// Handles the frame when its footer and structure are in place; returns false otherwise
bool LD2460Component::handle_frame_(const uint8_t *frame, uint8_t len) {
if (!ld24xx::has_footer(frame, len)) {
ESP_LOGV_HEX(TAG, frame, len, MAX_FRAME_LENGTH, "Invalid footer: %s");
return false;
}
this->buffer_data_[this->buffer_pos_++] = readch;
if (this->buffer_pos_ < HEADER_FOOTER_SIZE) {
return;
}
const uint8_t *tail = &this->buffer_data_[this->buffer_pos_ - HEADER_FOOTER_SIZE];
bool is_data = readch == progmem_read_byte(&DATA_FRAME_FOOTER[3]) && matches(tail, DATA_FRAME_FOOTER);
if (!is_data && (readch != progmem_read_byte(&CMD_FRAME_FOOTER[3]) || !matches(tail, CMD_FRAME_FOOTER))) {
return;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Frame: %s");
if (is_data) {
this->handle_periodic_data_();
} else {
this->handle_ack_();
}
this->buffer_pos_ = 0;
ESP_LOGV_HEX(TAG, frame, len, MAX_FRAME_LENGTH, "Frame: %s");
if (frame[0] == DataFrame::FIRST)
return this->handle_periodic_data_(frame, len);
return this->handle_ack_(frame, len);
}
// Once a footer is matched, shift the buffer to the first offset holding a header whose length
// field ends the frame exactly at the footer. Stray bytes, truncated frames and header bytes inside
// a payload are skipped this way. Returns false when no such offset exists.
bool LD2460Component::align_to_header_(const uint8_t *header) {
for (uint8_t i = 0; i + FRAME_PREFIX_SIZE <= this->buffer_pos_; i++) {
const uint8_t *frame = &this->buffer_data_[i];
if (matches(frame, header) && frame_length(frame) == this->buffer_pos_ - i) {
if (i != 0) {
this->buffer_pos_ -= i;
std::memmove(this->buffer_data_, frame, this->buffer_pos_);
}
return true;
}
}
return false;
}
void LD2460Component::handle_ack_() {
const uint8_t *data = this->buffer_data_;
if (!this->align_to_header_(CMD_FRAME_HEADER) || this->buffer_pos_ != ACK_FRAME_LENGTH) {
bool LD2460Component::handle_ack_(const uint8_t *data, uint8_t len) {
if (len != ACK_FRAME_LENGTH) {
ESP_LOGW(TAG, "Dropping malformed command frame");
return;
return false;
}
if (data[4] != CMD_QUERY_INSTALLATION_MODE) {
ESP_LOGD(TAG, "Ignoring reply to command 0x%02X", data[4]);
return;
return true;
}
const uint8_t mode = data[7];
if (mode != static_cast<uint8_t>(InstallationMode::INSTALLATION_MODE_SIDE) &&
mode != static_cast<uint8_t>(InstallationMode::INSTALLATION_MODE_TOP)) {
ESP_LOGW(TAG, "Unexpected installation mode %u", mode);
return;
return true;
}
this->installation_mode_ = static_cast<InstallationMode>(mode);
this->query_attempts_ = 0;
@@ -236,6 +163,7 @@ void LD2460Component::handle_ack_() {
t.last_x = INT16_MIN;
}
#endif
return true;
}
} // namespace esphome::ld2460
+17 -11
View File
@@ -1,6 +1,7 @@
#pragma once
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
@@ -8,8 +9,13 @@
namespace esphome::ld2460 {
static constexpr uint8_t MAX_LINE_LENGTH = 32; // Longest frame is a 5-target data frame of 31 bytes
static constexpr uint8_t MAX_FRAME_LENGTH = 31; // A 5-target data frame
static constexpr uint8_t MAX_TARGETS = 5;
// Header (4), command, whole-frame length (2, LE), payload, footer (4)
static constexpr uint8_t MIN_FRAME_LENGTH = 11;
using FrameLength = FrameLengthU16LE<LengthField{.offset = 5}>;
using DataFrame = FrameFormat<ld24xx::DataFrameHeader, FrameLength, FrameMinLength<MIN_FRAME_LENGTH>>;
using CmdFrame = FrameFormat<ld24xx::CmdFrameHeader, FrameLength, FrameMinLength<MIN_FRAME_LENGTH>>;
enum class InstallationMode : uint8_t {
INSTALLATION_MODE_SIDE = 1,
@@ -40,10 +46,16 @@ class LD2460Component : public Component, public uart::UARTDevice {
protected:
void send_query_();
bool align_to_header_(const uint8_t *header);
void handle_periodic_data_();
void handle_ack_();
void readline_(uint8_t readch);
bool handle_periodic_data_(const uint8_t *data, uint8_t packet_len);
bool handle_ack_(const uint8_t *data, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
uint32_t last_rx_{0};
LengthFrameReader<MAX_FRAME_LENGTH, DataFrame, CmdFrame> reader_;
// The angle formula depends on how the module is mounted, so it is read from the module at boot
InstallationMode installation_mode_{InstallationMode::INSTALLATION_MODE_SIDE};
// Queries sent so far; 0 once the module answered. Data frames resend up to MAX_QUERY_ATTEMPTS.
uint8_t query_attempts_{1};
#ifdef USE_SENSOR
// INT16_MIN marks a slot with no published coordinates, so the next report always publishes
@@ -56,12 +68,6 @@ class LD2460Component : public Component, public uart::UARTDevice {
#endif
LazyCallbackManager<void()> data_callback_;
uint8_t buffer_data_[MAX_LINE_LENGTH];
uint8_t buffer_pos_{0};
// The angle formula depends on how the module is mounted, so it is read from the module at boot
InstallationMode installation_mode_{InstallationMode::INSTALLATION_MODE_SIDE};
// Queries sent so far; 0 once the module answered. Data frames resend up to MAX_QUERY_ATTEMPTS.
uint8_t query_attempts_{1};
};
} // namespace esphome::ld2460
+17 -65
View File
@@ -1,13 +1,12 @@
#pragma once
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/progmem.h"
#include <algorithm>
#include <cstring>
#include <memory>
#include <span>
#ifdef USE_SENSOR
@@ -79,72 +78,25 @@ inline void format_version_str(const uint8_t *version, std::span<char, 20> buffe
version[5], version[4], version[3], version[2]);
}
// Commands and their answers share this header, a little-endian byte count and this footer
// Commands and their answers share this header, a little-endian byte count and this footer; periodic data frames have
// their own header and footer
static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0x04, 0x03, 0x02, 0x01};
static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] PROGMEM = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0x04, 0x03, 0x02, 0x01};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0xF8, 0xF7, 0xF6, 0xF5};
inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;
}
// Header (4), payload length (2, LE), payload, footer (4)
using PayloadLength = PayloadLengthU16LE<LengthField{.offset = HEADER_FOOTER_SIZE, .trailer = HEADER_FOOTER_SIZE}>;
using CmdFrameHeader = FrameHeader<0xFD, 0xFC, 0xFB, 0xFA>;
using DataFrameHeader = FrameHeader<0xF4, 0xF3, 0xF2, 0xF1>;
using CmdFrameFormat = FrameFormat<CmdFrameHeader, PayloadLength>;
using DataFrameFormat = FrameFormat<DataFrameHeader, PayloadLength>;
// Whole command frame length, or 0 until the count arrives; 32 bit so 0xFFFF cannot wrap to 0
inline uint32_t cmd_frame_length(const uint8_t *buffer, uint8_t count) {
if (count < HEADER_FOOTER_SIZE + 2) {
return 0;
}
return HEADER_FOOTER_SIZE + 2 + encode_value_le<uint16_t>(&buffer[HEADER_FOOTER_SIZE]) + HEADER_FOOTER_SIZE;
}
// Drops the first `from` bytes and anything after them that does not begin a header; returns the bytes kept
inline uint8_t drop_to_next_header(uint8_t *buffer, uint8_t count, uint8_t from, const uint8_t *data_header) {
for (; from < count; from++) {
const size_t n = std::min<size_t>(HEADER_FOOTER_SIZE, count - from);
if (std::memcmp(&buffer[from], CMD_FRAME_HEADER, n) == 0 || std::memcmp(&buffer[from], data_header, n) == 0) {
std::memmove(buffer, &buffer[from], count - from);
return count - from;
}
}
return 0;
}
// Feeds one byte into a frame buffer. A frame opens with the command header or `data_header` and ends at
// `frame_length(buffer, count)` bytes (0 while unknown); `handle_frame(len)` returns false for a footer out
// of place. A dropped or oversized frame calls `on_drop()`. The handler may overwrite `pos`; the splitter
// works from the count it saved.
template<size_t N, typename LengthFn, typename HandleFn, typename DropFn>
void feed_frame_byte(uint8_t (&buffer)[N], uint8_t &pos, uint8_t byte, const uint8_t *data_header,
LengthFn frame_length, HandleFn handle_frame, DropFn on_drop) {
// The first byte picks the header; bytes that do not continue it are dropped
if (pos > 0 && pos < HEADER_FOOTER_SIZE) {
const uint8_t *header = buffer[0] == data_header[0] ? data_header : CMD_FRAME_HEADER;
if (byte != header[pos]) {
pos = 0;
}
}
if (pos == 0 && byte != data_header[0] && byte != CMD_FRAME_HEADER[0]) {
return;
}
buffer[pos++] = byte;
// Drain every whole frame left in the buffer
while (true) {
const uint32_t frame_len = frame_length(buffer, pos);
if (frame_len == 0 || (frame_len <= N && pos < frame_len)) {
return;
}
const uint8_t total = pos;
// Keep only what begins a header: after the frame, or after its first byte when it is dropped
uint8_t from = 1;
if (frame_len <= N && handle_frame(static_cast<uint8_t>(frame_len))) {
from = frame_len;
} else {
on_drop();
}
pos = drop_to_next_header(buffer, total, from, data_header);
if (pos == 0) {
return;
}
}
// Whether a command or periodic data frame of at least HEADER_FOOTER_SIZE bytes ends in its footer
inline bool has_footer(const uint8_t *frame, size_t len) {
uint8_t footer[HEADER_FOOTER_SIZE];
progmem_memcpy(footer, frame[0] == DataFrameFormat::FIRST ? DATA_FRAME_FOOTER : CMD_FRAME_FOOTER, sizeof(footer));
return std::memcmp(&frame[len - HEADER_FOOTER_SIZE], footer, sizeof(footer)) == 0;
}
} // namespace esphome::ld24xx
+56
View File
@@ -1,3 +1,4 @@
from dataclasses import dataclass
import json
import logging
from pathlib import Path
@@ -188,6 +189,61 @@ def get_board_pins() -> dict[str, int]:
return lookup_board_pins(get_libretiny_board())
@dataclass(frozen=True)
class HardwareUart:
"""A hardware UART of the configured board and the pin numbers it can use."""
port: int
tx_pins: tuple[int, ...]
rx_pins: tuple[int, ...]
# The board lists pin choices instead of a default pin for this direction
tx_pin_choices: bool
rx_pin_choices: bool
@property
def pin_choices(self) -> bool:
"""True when the pins must be passed when the UART starts."""
return self.tx_pin_choices or self.rx_pin_choices
def get_hardware_uarts() -> list[HardwareUart]:
"""Hardware UARTs of the configured board; empty for a board without pin data."""
board_pins = get_board_pins()
uarts = []
for port in range(3):
pins: dict[str, list[int]] = {"TX": [], "RX": []}
choices: dict[str, bool] = {"TX": False, "RX": False}
for role, role_pins in pins.items():
name = f"SERIAL{port}_{role}"
for key, pin in board_pins.items():
if key == name:
role_pins.append(pin)
elif key.startswith(f"{name}_"):
role_pins.append(pin)
choices[role] = True
if pins["TX"] or pins["RX"]:
uarts.append(
HardwareUart(
port,
tuple(pins["TX"]),
tuple(pins["RX"]),
choices["TX"],
choices["RX"],
)
)
return uarts
def has_software_serial() -> bool:
"""True when the family's Arduino core has SoftwareSerial (LT_ARD_HAS_SOFTSERIAL)."""
return get_libretiny_family() == FAMILY_RTL8710B
def can_choose_uart_pins() -> bool:
"""True when SerialClass::begin() takes the pins, which LibreTiny added in 1.12.0."""
return CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION] >= cv.Version(1, 12, 0)
def only_on_family(*, supported=None, unsupported=None):
"""Config validator for features only available on some LibreTiny families."""
if supported is not None and not isinstance(supported, list):
@@ -151,7 +151,8 @@ Color color_from_light_color_values(LightColorValues val) {
auto r = to_uint8_scale(val.get_color_brightness() * val.get_red());
auto g = to_uint8_scale(val.get_color_brightness() * val.get_green());
auto b = to_uint8_scale(val.get_color_brightness() * val.get_blue());
auto w = to_uint8_scale(val.get_white());
// White keeps its default of 100% in RGB mode, where it must not count as the strongest channel
uint8_t w = val.get_color_mode() == ColorMode::RGB ? 0 : to_uint8_scale(val.get_white());
return Color(r, g, b, w);
}
@@ -12,6 +12,45 @@ uint8_t ESPColorCorrection::gamma_correct_(uint8_t value) const {
return result;
}
uint16_t ESPColorCorrection::gamma_level_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value * 257;
return progmem_read_uint16(&this->gamma_table_[value]);
}
uint8_t ESPColorCorrection::gamma_round_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
return (progmem_read_uint16(&this->gamma_table_[value]) + 128) / 257;
}
// Lighting every non-zero channel instead would turn a dim red with a trace of green into yellow
Color ESPColorCorrection::correct_dark_pixel_(Color color) const {
// Compared without the local brightness, which is the same for every channel: the scaled 8-bit
// values are too coarse to compare at the lowest brightness
uint16_t strengths[4];
uint16_t max_strength = 0;
bool lit = false;
for (uint8_t i = 0; i < 4; i++) {
strengths[i] = color[i] * this->max_brightness_[i];
max_strength = std::max(max_strength, strengths[i]);
lit |= esp_scale8_twice(color[i], this->max_brightness_[i], this->local_brightness_) != 0;
}
Color res;
if (!lit)
return res;
// Stretch the strongest channel to full scale and round the others against it; the table is too
// coarse to compare its lowest levels
for (uint8_t i = 0; i < 4; i++) {
if (strengths[i] == max_strength) {
res[i] = 1;
} else if (strengths[i] != 0) {
res[i] = this->gamma_level_(strengths[i] * 255 / max_strength) >= 0x8000 ? 1 : 0;
}
}
return res;
}
uint8_t ESPColorCorrection::gamma_uncorrect_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
@@ -40,10 +40,13 @@ class ESPColorCorrection {
#endif
void set_gamma_table(const uint16_t *table) { this->gamma_table_ = table; }
/// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma, keeping a lit pixel lit
inline Color color_correct(Color color) const ESPHOME_ALWAYS_INLINE {
// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma
return Color(this->color_correct_red(color.red), this->color_correct_green(color.green),
this->color_correct_blue(color.blue), this->color_correct_white(color.white));
Color res(this->round_channel_(COLOR_CHANNEL_R, color.red), this->round_channel_(COLOR_CHANNEL_G, color.green),
this->round_channel_(COLOR_CHANNEL_B, color.blue), this->round_channel_(COLOR_CHANNEL_W, color.white));
if (res.raw_32 == 0 && color.raw_32 != 0)
res = this->correct_dark_pixel_(color);
return Color(this->limit_(res.red), this->limit_(res.green), this->limit_(res.blue), this->limit_(res.white));
}
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
return this->color_correct_channel(COLOR_CHANNEL_R, red);
@@ -90,6 +93,15 @@ class ESPColorCorrection {
#endif
return res;
}
inline uint8_t round_channel_(uint8_t channel, uint8_t value) const ESPHOME_ALWAYS_INLINE {
return this->gamma_round_(esp_scale8_twice(value, this->max_brightness_[channel], this->local_brightness_));
}
/// Forward gamma as the table's 16-bit level
uint16_t gamma_level_(uint8_t value) const;
/// Forward gamma rounded to uint8, where a low level becomes 0
uint8_t gamma_round_(uint8_t value) const;
/// The levels of a pixel whose channels all round to 0: 1 for its strongest channels, unless it is black
Color correct_dark_pixel_(Color color) const;
/// Forward gamma: read uint16 PROGMEM table, convert to uint8
uint8_t gamma_correct_(uint8_t value) const;
/// Reverse gamma and limit for one stored level
+18 -1
View File
@@ -36,6 +36,10 @@ class ESPColorAccessor {
#if defined(USE_LIGHT_PARTITION) && defined(USE_LIGHT_POWER_ESTIMATION)
virtual const ESPColorCorrection *get_color_correction_internal(int32_t index) const { return nullptr; }
#endif
#ifdef USE_LIGHT_PARTITION
// For internal use only: whether the LED at `index` stores a white level.
virtual bool has_white_internal(int32_t index) const { return true; }
#endif
};
/// Color accessor that is completely at peace with the void of nothingness.
@@ -78,6 +82,10 @@ class BufferColorAccessor : public ESPColorAccessor {
}
void set_effect_data(int32_t index, uint8_t value) override { this->effect_data[index] = value; }
#ifdef USE_LIGHT_PARTITION
bool has_white_internal(int32_t index) const override { return this->channel_colors.has_white(); }
#endif
/// Allocate a zeroed block of buffer_bytes() plus `extra_bytes` for the caller, which start at
/// `effect_data + num_leds`, and pass it to set_buffer(). Returns false if it failed.
bool allocate(RAMAllocator<uint8_t> &allocator, size_t num_leds, size_t extra_bytes = 0) {
@@ -151,7 +159,12 @@ class CorrectedBufferColorAccessor final : public BufferColorAccessor {
return this->color_correction->color_uncorrect_channel(channel, this->get_channel_raw(index, channel));
}
void set(int32_t index, Color color) override { this->set_raw(index, this->color_correction->color_correct(color)); }
void set(int32_t index, Color color) override {
// A white level the strip cannot show must not count as the pixel's strongest channel
if (!this->channel_colors.has_white())
color.white = 0;
this->set_raw(index, this->color_correction->color_correct(color));
}
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
this->set_channel_raw(index, channel, this->color_correction->color_correct_channel(channel, value));
}
@@ -273,6 +286,10 @@ class ESPColorView final : public ESPColorSettable {
return this->accessor_->get_color_correction_internal(this->index_);
}
#endif
#ifdef USE_LIGHT_PARTITION
// This method is for internal use only.
bool has_white_internal() const { return this->accessor_->has_white_internal(this->index_); }
#endif
protected:
ESPColorAccessor *const accessor_;
+1 -1
View File
@@ -9,7 +9,7 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
char buffer[TIMESTAMP_LEN + ESPHOME_LOGGER_TX_BUFFER_SIZE + HEADROOM];
time_t rawtime;
time(&rawtime);
::time(&rawtime);
struct tm timeinfo;
localtime_r(&rawtime, &timeinfo); // Thread-safe version
size_t pos = strftime(buffer, TIMESTAMP_LEN + 1, "[%H:%M:%S]", &timeinfo);
+165
View File
@@ -0,0 +1,165 @@
#include "at_reply.h"
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <strings.h>
namespace esphome::modem {
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole) {
const size_t capacity = size - 1;
if (whole) {
len = 0;
}
bool dropped = false;
if (data_len > capacity) {
memcpy(buf, data + data_len - capacity, capacity);
len = capacity;
dropped = true;
} else {
if (len + data_len > capacity) {
const size_t drop = len + data_len - capacity;
memmove(buf, buf + drop, len - drop);
len -= drop;
dropped = true;
}
memcpy(buf + len, data, data_len);
len += data_len;
}
buf[len] = '\0';
return dropped;
}
ReplyEnd reply_end(const char *data, size_t len, bool skip_first) {
const char *end = data + len;
const char *line = data;
if (skip_first) {
const auto *newline = static_cast<const char *>(memchr(data, '\n', len));
line = newline != nullptr ? newline + 1 : end;
}
while (line < end) {
const auto *newline = static_cast<const char *>(memchr(line, '\n', end - line));
if (newline == nullptr) {
break; // the line has not ended yet
}
size_t size = newline - line;
if (size != 0 && line[size - 1] == '\r') {
size--;
}
if (size == 2 && memcmp(line, "OK", 2) == 0) {
return ReplyEnd::REPLY_END_OK;
}
// esp_modem drops a CMUX frame without a line end, so the ": <reason>" part may be missing
if ((size == 5 && memcmp(line, "ERROR", 5) == 0) || (size >= 10 && memcmp(line, "+CME ERROR", 10) == 0) ||
(size >= 10 && memcmp(line, "+CMS ERROR", 10) == 0)) {
return ReplyEnd::REPLY_END_ERROR;
}
line = newline + 1;
}
return ReplyEnd::REPLY_END_NONE;
}
size_t flatten_reply(char *reply, size_t len) {
for (size_t i = 0; i < len; i++) {
if (reply[i] == '\r' || reply[i] == '\n') {
reply[i] = ' ';
}
}
while (len != 0 && reply[len - 1] == ' ') {
len--;
}
if (len >= 2 && memcmp(reply + len - 2, "OK", 2) == 0 && (len == 2 || reply[len - 3] == ' ')) {
len -= 2;
while (len != 0 && reply[len - 1] == ' ') {
len--;
}
}
size_t start = 0;
while (start < len && reply[start] == ' ') {
start++;
}
len -= start;
memmove(reply, reply + start, len);
reply[len] = '\0';
return len;
}
int registration_from_reply(const char *reply, const char *prefix) {
const size_t prefix_len = strlen(prefix);
for (const char *line = strstr(reply, prefix); line != nullptr; line = strstr(line + 1, prefix)) {
const char *start = line + prefix_len;
char *end = nullptr;
strtol(start, &end, 10);
if (end == start || *end != ',') {
continue;
}
start = end + 1;
const auto stat = static_cast<int32_t>(strtol(start, &end, 10));
if (end != start) {
return stat;
}
}
return REGISTRATION_UNKNOWN;
}
int merge_registration(int lte, int legacy) {
// A multimode modem can be registered or still searching on one network type while the other refuses it
if (is_registered(lte)) {
return lte;
}
if (is_registered(legacy)) {
return legacy;
}
// A definite answer from one query outweighs a timeout of the other
if (lte == REGISTRATION_SEARCHING || legacy == REGISTRATION_SEARCHING) {
return REGISTRATION_SEARCHING;
}
if (lte == REGISTRATION_DENIED || legacy == REGISTRATION_DENIED) {
return REGISTRATION_DENIED;
}
if (lte >= 0 || legacy >= 0) {
return lte >= 0 ? lte : legacy;
}
if (lte == REGISTRATION_NO_ANSWER || legacy == REGISTRATION_NO_ANSWER) {
return REGISTRATION_NO_ANSWER;
}
if (lte == REGISTRATION_UNSUPPORTED && legacy == REGISTRATION_UNSUPPORTED) {
return REGISTRATION_UNSUPPORTED;
}
return REGISTRATION_UNKNOWN;
}
bool reply_names_unsupported(const char *reply) {
static constexpr char PREFIX[] = "+CME ERROR:";
static constexpr char TEXT[] = "operation not supported";
const char *code = strstr(reply, PREFIX);
if (code == nullptr) {
return false;
}
code += sizeof(PREFIX) - 1;
while (*code == ' ') {
code++;
}
return strncasecmp(code, TEXT, sizeof(TEXT) - 1) == 0 || (code[0] == '4' && !isdigit(code[1]));
}
const char *sim_status(char *reply) {
static constexpr char PREFIX[] = "+CPIN:";
char *status = strstr(reply, PREFIX);
if (status == nullptr) {
return nullptr;
}
status += sizeof(PREFIX) - 1;
while (*status == ' ') {
status++;
}
// A URC in the same reply follows on its own line, which flatten_reply() turned into two spaces
char *end = strstr(status, " ");
if (end != nullptr) {
*end = '\0';
}
return status;
}
} // namespace esphome::modem
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <cstddef>
#include <cstdint>
// Parsers for raw AT replies; free of esp_modem so they build and run in host unit tests
namespace esphome::modem {
enum class ReplyEnd : uint8_t {
REPLY_END_NONE, // no complete final result line yet
REPLY_END_OK, // an OK line
REPLY_END_ERROR, // an ERROR, +CME ERROR: or +CMS ERROR: line
};
// AT+CEREG? and AT+CREG? <stat> values (3GPP TS 27.007)
static constexpr int REGISTRATION_NOT_SEARCHING = 0;
static constexpr int REGISTRATION_HOME = 1;
static constexpr int REGISTRATION_SEARCHING = 2;
static constexpr int REGISTRATION_DENIED = 3;
static constexpr int REGISTRATION_REPORTED_UNKNOWN = 4;
static constexpr int REGISTRATION_ROAMING = 5;
static constexpr int REGISTRATION_SMS_ONLY_HOME = 6;
static constexpr int REGISTRATION_SMS_ONLY_ROAMING = 7;
static constexpr int REGISTRATION_EMERGENCY_ONLY = 8;
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_HOME = 9;
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_ROAMING = 10;
// Results beyond the 3GPP values
static constexpr int REGISTRATION_UNKNOWN = -1; // no readable answer
static constexpr int REGISTRATION_UNSUPPORTED = -2; // the query is not supported
static constexpr int REGISTRATION_NO_ANSWER = -3; // the query timed out
/// Registered on a network, so the data attach can be requested. SMS only and "CSFB not preferred" limit the
/// circuit switched side, not the packet data attach; emergency only (8) is not a registration.
inline bool is_registered(int registration) {
return registration == REGISTRATION_HOME || registration == REGISTRATION_ROAMING ||
(registration >= REGISTRATION_SMS_ONLY_HOME && registration <= REGISTRATION_SMS_ONLY_ROAMING) ||
(registration >= REGISTRATION_CSFB_NOT_PREFERRED_HOME &&
registration <= REGISTRATION_CSFB_NOT_PREFERRED_ROAMING);
}
/// Add data to the reply in buf (size includes the terminator, len is the current length). With whole, data is
/// everything received so far (UART) and replaces the reply; otherwise it is one new CMUX frame and is appended. A
/// reply longer than the buffer keeps its newest bytes, where the final line is. Returns true when bytes were dropped.
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole);
/// How the reply ends. Only a complete final result line counts, so ERROR inside a payload line does not; a +CME ERROR
/// line counts even without its reason, which a dropped CMUX frame can take away. With
/// skip_first, the first line is a cut-off fragment and is ignored.
ReplyEnd reply_end(const char *data, size_t len, bool skip_first);
/// Puts a raw reply on one line for the log and drops the final OK; returns the new length
size_t flatten_reply(char *reply, size_t len);
/// The <stat> after the first comma of the "<n>,<stat>" line starting with prefix (+CREG: and friends), or
/// REGISTRATION_UNKNOWN; a one-field line is an unsolicited notification and is skipped
int registration_from_reply(const char *reply, const char *prefix);
/// The state that tells most from the AT+CEREG? (LTE) and AT+CREG? (2G and 3G) results
int merge_registration(int lte, int legacy);
/// Whether an error reply says the command is not supported (+CME ERROR: 4 or its verbose text)
bool reply_names_unsupported(const char *reply);
/// The SIM status in a flattened AT+CPIN? reply, cut before any following line, or nullptr
const char *sim_status(char *reply);
} // namespace esphome::modem
+296 -47
View File
@@ -1,5 +1,6 @@
#ifdef USE_ESP32
#include "modem_component.h"
#include "at_reply.h"
#include "soc/soc_caps.h"
#include <driver/uart.h>
@@ -42,6 +43,14 @@ static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
// A silent modem is not going to answer the next second, so its probes are spaced out, doubling up to a minute
static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
// A modem in command mode answers the ATE0 sent before the mode detection within this time
static constexpr uint32_t ECHO_OFF_TIMEOUT_MS = 100;
// The +++ escape needs a second of silence before it; esp_modem waits for the answer after it
static constexpr uint32_t ESCAPE_GUARD_MS = 1100;
// A SIM7670 left in CMUX by an ESP reset ignores every frame until this many flag bytes overflow its receive buffer;
// it then reinitialises its AT channel within about 2 s
static constexpr size_t CMUX_FLUSH_BYTES = 4096;
static constexpr uint32_t CMUX_FLUSH_SETTLE_MS = 3000;
// How long the task waits for the main loop to run on_sync before attaching
static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
// esp_modem's command strings and the log lines are built on this stack
@@ -56,6 +65,12 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
static constexpr uint32_t ATTACH_POLL_MS = 4000;
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
static constexpr uint8_t ATTACH_UNKNOWN_POLLS = 15; // about a minute of polls
// AT+CGATT=1: SIMCom documents up to 75 s, but a SIM7080G that is not registered yet held it for 141 s
static constexpr uint32_t ATTACH_TIMEOUT_MS = 150000;
// SIM status polls that fail before a warning, and between repeats of it
static constexpr uint8_t SIM_WARN_AFTER = 10;
static constexpr uint8_t SIM_WARN_EVERY = 60;
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
@@ -73,8 +88,22 @@ static const LogString *state_to_str(ModemState state) {
// Indexed by ModemFault
PROGMEM_STRING_TABLE(ModemFaultStrings, "", "Modem not responding", "Configured baud rate failed",
"init_at command failed", "SIM not ready", "SIM locked", "SIM PIN not sent; check pin_code",
"PIN record not saved", "APN or radio setup failed", "No network attachment", "PPP link failed",
"Modem teardown failed");
"PIN record not saved", "APN or radio setup failed", "No network attachment",
"Network registration denied", "PPP link failed", "Modem teardown failed");
// Indexed by the AT+CEREG? <stat> value
PROGMEM_STRING_TABLE(RegistrationStrings, "not searching", "registered", "searching", "denied", "unknown", "roaming",
"registered for SMS only", "roaming for SMS only", "emergency only",
"registered, CSFB not preferred", "roaming, CSFB not preferred", "other");
static const LogString *registration_to_str(int registration) {
if (registration == REGISTRATION_UNSUPPORTED) {
return LOG_STR("not supported");
}
if (registration < 0) {
return LOG_STR("not reported");
}
return RegistrationStrings::get_log_str(static_cast<uint8_t>(registration), RegistrationStrings::LAST_INDEX);
}
// Indexed by esp_modem::command_result
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
@@ -586,6 +615,9 @@ ModemState ModemComponent::compute_next_state_() {
}
ModemState ModemComponent::handle_state_enabling_() {
// With echo on (SIM7670G after power-up), the modem sends esp_modem's PPP probe back and the detection takes it for
// a PPP reply; in PPP or CMUX these bytes are dropped as a bad frame
this->at_reply_("ATE0", ECHO_OFF_TIMEOUT_MS);
// Find the baud rate the modem answers at and leave it in command mode, synced
if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
// A failed detection keeps the previous mode, which would skip the baud rate search below
@@ -611,21 +643,18 @@ ModemState ModemComponent::handle_state_enabling_() {
exited = false;
const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
bool found = false;
bool probed = false;
bool rejected = false;
for (size_t i = 0; i != std::size(bauds) && !found; i++) {
const int baud = bauds[i];
if (baud == 0 || baud == detected || std::find(bauds, bauds + i, baud) != bauds + i) {
continue;
}
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
if (this->set_uart_baud_(baud) != ESP_OK) {
ESP_LOGW(TAG, "UART rejected baud rate %d", baud);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
rejected = true;
continue;
}
this->current_baud_rate_ = baud;
probed = true;
std::string output;
found = this->dce_->at("AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
if (!found) {
@@ -633,11 +662,31 @@ ModemState ModemComponent::handle_state_enabling_() {
}
}
if (!found) {
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
if (!probed && !rejected) {
// A modem left in data mode before PPP started, or stuck in CMUX, answers none of the probes; both recoveries
// go out at the rate the detection used
if (this->current_baud_rate_ != detected) {
const esp_err_t err = this->set_uart_baud_(detected);
if (err != ESP_OK) {
ESP_LOGW(TAG, "UART rejected baud rate %d (%s); data mode and CMUX recovery skipped", detected,
esp_err_to_name(err));
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
rejected = true;
}
}
// The escape before the flush is what a stuck SIM7670G responds to; the order is measured, not arbitrary
if (this->current_baud_rate_ == detected && (this->escape_data_mode_() || this->flush_cmux_())) {
exited = true;
break;
}
// A UART that refused a rate set BAUD
if (!rejected) {
this->not_responding_(detected);
}
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
const uint32_t delay_ms = this->next_probe_delay_();
if (delay_ms == PROBE_RETRY_MAX_MS) {
this->answered_ = false; // silent for minutes, so the wiring hint applies again
}
return this->retry_(ModemState::MODEM_STATE_ENABLING, delay_ms);
}
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
break;
@@ -671,10 +720,19 @@ ModemState ModemComponent::handle_state_enabling_() {
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
// The modem answers AT, so it is in command mode. A failed data mode exit leaves esp_modem's UART side in data mode,
// from where its later switch to CMUX fails at once, so its mode is set to match; this sends nothing to the modem.
if (!this->dce_->set_mode(modem_mode::RESUME_COMMAND_MODE)) {
ESP_LOGW(TAG, "esp_modem refused command mode; the switch to PPP may fail");
}
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
if (this->dce_->set_echo(false) != command_result::OK) {
ESP_LOGW(TAG, "Failed to disable command echo");
}
// Verbose +CME ERROR text, so a failed command or a missing SIM says why; a modem without it keeps plain ERROR
if (this->dce_->config_mobile_termination_error(2) != command_result::OK) {
ESP_LOGW(TAG, "Modem refused verbose errors (AT+CMEE=2)");
}
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
@@ -690,6 +748,7 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGW(TAG, "Failed to power the SIM up");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
this->modem_synced_ = true; // it answers, so a disable() still tears it down
this->answered_ = true;
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
@@ -698,12 +757,11 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
if (this->dce_->set_baud(this->baud_rate_) == command_result::OK) {
delay(200); // NOLINT
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
if (this->set_uart_baud_(this->baud_rate_) != ESP_OK) {
ESP_LOGE(TAG, "UART rejected baud rate %d", this->baud_rate_);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
return ModemState::MODEM_STATE_DISCONNECTING;
}
this->current_baud_rate_ = this->baud_rate_;
if (this->dce_->sync() != command_result::OK) {
ESP_LOGE(TAG, "Failed to sync modem at baud rate %d.", this->baud_rate_);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
@@ -731,6 +789,7 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGW(TAG, "Modem refused hardware flow control; UART overruns are possible");
}
this->modem_synced_ = true;
this->answered_ = true;
return ModemState::MODEM_STATE_SYNCED;
}
@@ -746,12 +805,13 @@ ModemState ModemComponent::handle_state_synced_() {
this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
}
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
this->sim_polls_ = 0;
return ModemState::MODEM_STATE_CONNECTING;
}
ModemState ModemComponent::handle_state_connecting_() {
if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
// ENABLING just synced; only a failed attachment read comes back here unsure of the modem
// ENABLING just synced; a command that timed out comes back here unsure of the modem
if (this->resync_) {
this->resync_ = false;
if (this->dce_->sync() != command_result::OK) {
@@ -792,35 +852,78 @@ ModemState ModemComponent::handle_state_connecting_() {
}
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
this->attach_polls_ = 0;
}
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON) {
// A modem still searching for a network refuses this; the attachment poll asks again
if (this->dce_->set_network_attachment_state(1) != command_result::OK) {
ESP_LOGD(TAG, "Network attachment request refused");
}
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
this->idle_polls_ = 0;
this->unknown_polls_ = 0;
}
int attached = 0;
if (this->dce_->get_network_attachment_state(attached) != command_result::OK) {
ESP_LOGW(TAG, "Failed to read the network attachment state");
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
this->resync_ = true;
this->request_resync_();
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (!attached) {
const int registration = this->read_registration_();
if (registration == REGISTRATION_NO_ANSWER) {
// The state is open, so the modem is checked with a sync instead
ESP_LOGW(TAG, "No answer to a registration query");
this->request_resync_();
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
// "Not searching" for a few polls in a row means the attachment is off; right after CFUN=1 it is only brief
this->idle_polls_ = registration == REGISTRATION_NOT_SEARCHING ? static_cast<uint8_t>(this->idle_polls_ + 1) : 0;
const bool idle = this->idle_polls_ >= ATTACH_DIAG_EVERY;
// A state that cannot be read or means nothing here holds the request back only for a while
const bool unknown = registration == REGISTRATION_UNKNOWN || registration == REGISTRATION_REPORTED_UNKNOWN ||
(registration > REGISTRATION_ROAMING && !is_registered(registration));
this->unknown_polls_ = unknown ? static_cast<uint8_t>(this->unknown_polls_ + 1) : 0;
const bool unknown_too_long = this->unknown_polls_ >= ATTACH_UNKNOWN_POLLS;
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON &&
(is_registered(registration) || registration == REGISTRATION_UNSUPPORTED || idle || unknown_too_long)) {
if (unknown_too_long) {
ESP_LOGI(TAG, "Registration state %d (%s) for %u polls; requesting the network attachment anyway", registration,
LOG_STR_ARG(registration_to_str(registration)), this->unknown_polls_);
this->unknown_polls_ = 0;
}
// Before registration a modem can hold the AT channel on this for minutes and drop every command meanwhile,
// so it waits for one; the fallbacks above send it anyway, and ATTACH_TIMEOUT_MS covers that hold
const command_result attach = this->at_reply_("AT+CGATT=1", ATTACH_TIMEOUT_MS);
if (attach == command_result::TIMEOUT) {
ESP_LOGW(TAG, "No answer to the network attachment request");
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->request_resync_();
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (attach != command_result::OK) {
ESP_LOGW(TAG, "Network attachment request refused: %s", this->reply_);
}
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
int rssi = 99, ber = 99, registration = -1, mode = -1; // -1 stays when the query fails
this->dce_->get_network_registration_state(registration);
int rssi = 99, ber = 99, mode = -1; // -1 stays when the query fails
this->dce_->get_signal_quality(rssi, ber);
this->dce_->get_network_system_mode(mode);
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
rssi, ber);
ESP_LOGW(TAG, "Modem not attached yet: registration %d (%s), network type %d, CSQ %d, BER %d", registration,
LOG_STR_ARG(registration_to_str(registration)), mode, rssi, ber);
if (unknown) {
ESP_LOGW(TAG, "Network attachment request held back while the registration state is unknown (%u of %u polls)",
this->unknown_polls_, ATTACH_UNKNOWN_POLLS);
}
if (registration == REGISTRATION_DENIED) {
// The modem's reason tells a rejected APN (ESM failure) from a SIM the network does not serve
const command_result reason_read = this->at_reply_("AT+CEER");
ESP_LOGW(TAG,
"The network refused registration (AT+CEER %s: %s); check the APN and that the SIM's plan covers "
"this modem's network types",
LOG_STR_ARG(result_to_str(reason_read)), this->reply_);
}
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
}
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
}
@@ -923,11 +1026,114 @@ void ModemComponent::transition_to_(ModemState next_state) {
}
}
esp_err_t ModemComponent::set_uart_baud_(int baud) {
const esp_err_t err = uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud);
if (err == ESP_OK) {
this->current_baud_rate_ = baud;
}
return err;
}
bool ModemComponent::escape_data_mode_() {
delay(ESCAPE_GUARD_MS); // NOLINT
if (this->dce_->set_command_mode() != command_result::OK) {
ESP_LOGD(TAG, "No answer after the data mode escape");
return false;
}
ESP_LOGW(TAG, "Modem was left in data mode; escaped to command mode");
return true;
}
bool ModemComponent::flush_cmux_() {
// With RTS/CTS a silent modem can hold CTS off; the flag bytes would then stay queued and block every later write
if (this->rts_pin_ != nullptr) {
ESP_LOGW(TAG, "CMUX recovery is not available with RTS/CTS flow control");
return false;
}
static constexpr uint8_t CMUX_FLAG = 0xF9;
uint8_t flags[64];
memset(flags, CMUX_FLAG, sizeof(flags));
const auto port = static_cast<uart_port_t>(this->uart_port_);
for (size_t sent = 0; sent < CMUX_FLUSH_BYTES; sent += sizeof(flags)) {
if (this->dte_->write(flags, sizeof(flags)) != static_cast<int>(sizeof(flags))) {
ESP_LOGW(TAG, "CMUX flush: short write after %u bytes", static_cast<unsigned>(sent));
return false;
}
}
// 10 bits per byte, plus a margin
const uint32_t send_ms = CMUX_FLUSH_BYTES * 10 * 1000 / this->current_baud_rate_ + 100;
if (uart_wait_tx_done(port, pdMS_TO_TICKS(send_ms)) != ESP_OK) {
ESP_LOGW(TAG, "CMUX flush: transmit not finished after %u ms", static_cast<unsigned>(send_ms));
return false;
}
delay(CMUX_FLUSH_SETTLE_MS); // NOLINT
if (this->dce_->sync() != command_result::OK) {
ESP_LOGD(TAG, "No answer after the CMUX flush");
return false;
}
ESP_LOGW(TAG, "Modem was stuck in CMUX; reset it to command mode");
return true;
}
// A command timed out: the next pass checks with a sync that the modem still answers
void ModemComponent::request_resync_() {
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
this->resync_ = true;
}
// One registration query: the <stat>, REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER or REGISTRATION_UNKNOWN
int ModemComponent::read_stat_(const char *cmd, const char *prefix) {
const command_result result = this->at_reply_(cmd);
if (result == command_result::TIMEOUT) {
return REGISTRATION_NO_ANSWER;
}
if (result == command_result::FAIL && reply_names_unsupported(this->reply_)) {
return REGISTRATION_UNSUPPORTED;
}
const int stat = result == command_result::OK ? registration_from_reply(this->reply_, prefix) : REGISTRATION_UNKNOWN;
if (stat == REGISTRATION_UNKNOWN) {
// An error such as a SIM failure is a warning on the diagnostic polls, so it shows at the default log level
if (result == command_result::FAIL && this->attach_polls_ % ATTACH_DIAG_EVERY == 0) {
ESP_LOGW(TAG, "%s failed: %s", cmd, this->reply_);
} else {
ESP_LOGD(TAG, "%s gave no state: %s", cmd, this->reply_);
}
}
return stat;
}
// AT+CEREG covers LTE; on 2G and 3G the network registration is in AT+CREG, and AT+CGATT=1 is answered quickly once
// it is set. Returns the <stat> that tells most, or one of the negative REGISTRATION_ values.
int ModemComponent::read_registration_() {
const int lte = this->read_stat_("AT+CEREG?", "+CEREG:");
if (is_registered(lte)) {
return lte;
}
return merge_registration(lte, this->read_stat_("AT+CREG?", "+CREG:"));
}
void ModemComponent::not_responding_(int baud) {
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
if (this->answered_) {
// It answered before, so the wiring is fine; a long command or a modem restart keeps it silent for minutes
ESP_LOGW(TAG, "Modem not responding at %d baud; it may be busy or restarting", baud);
} else {
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
}
this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
}
void ModemComponent::sim_not_ready_(const char *reason) {
// A missing or broken SIM never gets ready; the status is polled every second, so only some polls warn
if (++this->sim_polls_ == SIM_WARN_AFTER + SIM_WARN_EVERY) {
this->sim_polls_ = SIM_WARN_AFTER;
}
if (this->sim_polls_ == SIM_WARN_AFTER) {
ESP_LOGW(TAG, "SIM not ready: %s. Check that a working SIM is inserted",
reason[0] != '\0' ? reason : LOG_STR_LITERAL("no reply"));
}
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
}
#ifdef USE_MODEM_SEND_AT
bool ModemComponent::send_at(const std::string &cmd, uint32_t timeout) { return this->send_at(cmd.c_str(), timeout); }
@@ -954,13 +1160,54 @@ bool ModemComponent::send_at(const char *cmd, uint32_t timeout) {
#endif
// at() keeps no text from a failed command, so the raw reply is collected into reply_ to show the +CME ERROR
command_result ModemComponent::at_reply_(const char *cmd, uint32_t timeout) {
std::string line = cmd; // poll commands fit the short string buffer
line += '\r';
this->reply_len_ = 0;
this->reply_[0] = '\0';
#ifdef CONFIG_ESP_MODEM_USE_INFLATABLE_BUFFER_IF_NEEDED
// The inflatable buffer gathers CMUX frames too, so every reply comes over whole each time
const bool whole = true;
#else
// esp_modem hands a UART reply over whole each time, and a CMUX reply one frame at a time
const modem_mode mode = this->dce_->get_mode();
const bool whole = mode != modem_mode::CMUX_MODE && mode != modem_mode::CMUX_MANUAL_MODE &&
mode != modem_mode::CMUX_MANUAL_DATA && mode != modem_mode::CMUX_MANUAL_COMMAND;
#endif
struct {
bool whole;
bool cut;
} state{whole, false};
const command_result result = this->dce_->command(
line,
[this, &state](const uint8_t *data, size_t len) {
// OK, or FAIL once an ERROR line has ended (the +CME ERROR reason may still be on its way), else TIMEOUT
state.cut |= collect_reply(this->reply_, sizeof(this->reply_), this->reply_len_,
reinterpret_cast<const char *>(data), len, state.whole);
switch (reply_end(this->reply_, this->reply_len_, state.cut)) {
case ReplyEnd::REPLY_END_OK:
return command_result::OK;
case ReplyEnd::REPLY_END_ERROR:
return command_result::FAIL;
default:
return command_result::TIMEOUT;
}
},
timeout);
this->reply_len_ = flatten_reply(this->reply_, this->reply_len_);
this->reply_cut_ = state.cut;
return result;
}
command_result ModemComponent::at_(const char *cmd, uint32_t timeout) {
std::string output;
const command_result result = this->dce_->at(cmd, output, timeout);
const command_result result = this->at_reply_(cmd, timeout);
// A reply longer than the buffer kept only its end
const char *cut = this->reply_cut_ ? LOG_STR_LITERAL("...") : "";
if (result == command_result::OK) {
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
} else {
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
}
return result;
}
@@ -973,25 +1220,27 @@ SimResult ModemComponent::prepare_sim_() {
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
}
#endif
std::string output;
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
// The raw reply keeps the +CME ERROR text a missing SIM gives; status below points into it
const command_result result = this->at_reply_("AT+CPIN?");
if (result == command_result::TIMEOUT) {
// The next pass checks with a sync whether the modem or only the SIM interface is silent
ESP_LOGD(TAG, "No answer to the SIM status request");
this->sim_not_ready_(LOG_STR_LITERAL("no answer to AT+CPIN?"));
this->request_resync_();
return SimResult::SIM_RESULT_RETRY;
}
if (result != command_result::OK) {
// A SIM that is still starting answers with an error for a second or so
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
ESP_LOGD(TAG, "SIM status not readable yet: %s", this->reply_);
this->sim_not_ready_(this->reply_);
return SimResult::SIM_RESULT_RETRY;
}
// Anything else, such as an echoed command, is not a status and must not reach the lock checks below
const char *found = strstr(output.c_str(), "+CPIN:");
if (found != nullptr) {
found += sizeof("+CPIN:") - 1;
while (*found == ' ') {
found++;
}
}
const char *found = sim_status(this->reply_);
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
if (status.empty()) {
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
this->sim_not_ready_(this->reply_);
return SimResult::SIM_RESULT_RETRY;
}
ESP_LOGD(TAG, "SIM: %s", status.c_str());
@@ -1019,8 +1268,8 @@ SimResult ModemComponent::prepare_sim_() {
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
return SimResult::SIM_RESULT_LOCKED;
}
ESP_LOGW(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
this->sim_not_ready_(status.c_str());
return SimResult::SIM_RESULT_RETRY;
}
#ifdef USE_MODEM_PIN_CODE
+22 -1
View File
@@ -62,6 +62,7 @@ enum class ModemFault : uint8_t {
MODEM_FAULT_PIN_RECORD,
MODEM_FAULT_SETUP,
MODEM_FAULT_NOT_ATTACHED,
MODEM_FAULT_REGISTRATION_DENIED,
MODEM_FAULT_PPP,
MODEM_FAULT_TEARDOWN,
};
@@ -151,6 +152,7 @@ class ModemComponent : public Component {
static constexpr uint32_t RETRY_DELAY_MS = 1000;
static constexpr size_t URC_LINE_SIZE = 128;
static constexpr size_t AT_COMMAND_SIZE = 128;
static constexpr size_t REPLY_SIZE = 256; // a longer reply keeps its newest bytes, so its final line counts
#ifdef USE_MODEM_POLL
static constexpr uint8_t CSQ_UNKNOWN = 99; // AT+CSQ rssi or ber the modem cannot tell
static constexpr uint8_t CSQ_RSSI_MAX = 31;
@@ -200,8 +202,20 @@ class ModemComponent : public Component {
void hand_over_(uint32_t pending);
/// Send an AT command from the task and log the result; blocks for up to the timeout
esp_modem::command_result at_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
/// Send an AT command; reply_ gets the whole reply on one line, including any +CME ERROR text
esp_modem::command_result at_reply_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
void publish_status_();
/// Send the +++ escape with its guard times; true when the modem answered
bool escape_data_mode_();
/// Overflow a stuck CMUX receiver with flag bytes; true when the modem answers AT afterwards
bool flush_cmux_();
void request_resync_();
int read_stat_(const char *cmd, const char *prefix);
int read_registration_();
/// Set the UART rate; current_baud_rate_ follows when the UART takes it
esp_err_t set_uart_baud_(int baud);
void not_responding_(int baud);
void sim_not_ready_(const char *reason);
void dump_connect_params_();
SimResult prepare_sim_();
#ifdef USE_MODEM_PIN_CODE
@@ -221,6 +235,9 @@ class ModemComponent : public Component {
const char *urc_line_{nullptr}; // the line urc_pending_ hands to loop(), inside urc_reader_
#endif
std::unique_ptr<esp_modem::DCE> dce_;
char reply_[REPLY_SIZE + 1]{}; // task only; the last reply, null-terminated
size_t reply_len_{0};
bool reply_cut_{false}; // the last reply was longer than reply_ and kept only its end
std::shared_ptr<esp_modem::DTE> dte_;
esp_netif_t *ppp_netif_{nullptr};
ESPPreferenceObject pref_;
@@ -291,6 +308,9 @@ class ModemComponent : public Component {
uint8_t init_at_count_{0};
uint8_t uart_port_{UART_NUM_MAX};
uint8_t attach_polls_{0};
uint8_t idle_polls_{0}; // polls in a row that reported "not searching"
uint8_t unknown_polls_{0}; // polls in a row with no usable registration state
uint8_t sim_polls_{0}; // failed SIM status reads in this attempt
#ifdef USE_MODEM_POLL
uint8_t poll_rssi_{CSQ_UNKNOWN}; // raw AT+CSQ answers
uint8_t poll_ber_{CSQ_UNKNOWN};
@@ -298,7 +318,8 @@ class ModemComponent : public Component {
#endif
bool connect_timeout_armed_{false};
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
bool answered_{false}; // the modem synced since boot, so its wiring and power are fine
bool resync_{false}; // a command timed out, so CONNECTING syncs again first
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
#ifdef USE_MODEM_SEND_AT
char at_command_[AT_COMMAND_SIZE];
+16 -4
View File
@@ -323,12 +323,18 @@ bool MQTTClientComponent::can_proceed() {
}
void MQTTClientComponent::start_dnslookup_() {
this->status_set_warning();
// No lookup can start before the network is up: there is no DNS server to ask yet.
// Stay disconnected, and loop() calls this again as soon as it is up.
this->waiting_for_network_ = !network::is_connected();
if (this->waiting_for_network_)
return;
for (auto &subscription : this->subscriptions_) {
subscription.subscribed = false;
subscription.resubscribe_timeout = 0;
}
this->status_set_warning();
this->dns_resolve_error_ = false;
this->dns_resolved_ = false;
ip_addr_t addr;
@@ -358,9 +364,13 @@ void MQTTClientComponent::start_dnslookup_() {
}
default:
case ERR_ARG: {
// error
// The lookup never started, so there is no answer to wait for; loop() tries again in 5 seconds
ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
break;
this->state_ = MQTT_CLIENT_DISCONNECTED;
this->disconnect_reason_ = MQTTClientDisconnectReason::DNS_RESOLVE_ERROR;
this->on_disconnect_.call(MQTTClientDisconnectReason::DNS_RESOLVE_ERROR);
this->connect_begin_ = millis();
return;
}
}
@@ -505,7 +515,9 @@ void MQTTClientComponent::loop() {
case MQTT_CLIENT_DISABLED:
return; // Return to avoid a reboot when disabled
case MQTT_CLIENT_DISCONNECTED:
if (now - this->connect_begin_ > 5000) {
// Back off 5 s after a failed attempt. Without a network no attempt was made, so the
// first one starts as soon as the network is up instead of 5 s after boot.
if (this->waiting_for_network_ || now - this->connect_begin_ > 5000) {
this->start_dnslookup_();
}
break;
+2
View File
@@ -436,6 +436,8 @@ class MQTTClientComponent final : public Component {
network::IPAddress ip_;
bool dns_resolved_{false};
bool dns_resolve_error_{false};
/// The last start_dnslookup_() found no network, so no attempt was made and there is nothing to back off from
bool waiting_for_network_{false};
bool enable_on_boot_{true};
#ifdef USE_MQTT_CRASH_LOG
bool crash_log_offered_{false};
+117 -39
View File
@@ -1,4 +1,5 @@
from collections.abc import Callable
import logging
from esphome import automation
import esphome.codegen as cg
@@ -8,6 +9,8 @@ import esphome.config_validation as cv
from esphome.const import CONF_DURATION, CONF_ID, CONF_MODE, CONF_VOLTAGE
from esphome.types import ConfigType
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@tomaszduda23"]
DEPENDENCIES = ["i2c"]
DOMAIN = "npm1300"
@@ -42,20 +45,18 @@ NPM1300_CHILD_SCHEMA = cv.Schema(
{cv.GenerateID(CONF_NPM1300_ID): cv.use_id(NPM1300Component)}
)
# Status registers read on each update: VBUSINSTATUS, BCHGCHARGESTATUS and BCHGERRREASON
NPM1300Status = npm1300_ns.struct("NPM1300Status")
# The status registers read on each update
STATUS_PUBLISHER = cg.HubFunction(
"status",
cg.void,
[
(cg.uint8, "vbus_status"),
(cg.uint8, "charge_status"),
(cg.uint8, "error_reason"),
],
[(NPM1300Status.operator("const").operator("ref"), "status")],
define="USE_NPM1300_STATUS_PUBLISHER",
)
VBUS_STATUS = STATUS_PUBLISHER.param("vbus_status")
CHARGE_STATUS = STATUS_PUBLISHER.param("charge_status")
ERROR_REASON = STATUS_PUBLISHER.param("error_reason")
STATUS = STATUS_PUBLISHER.param("status")
VBUS_STATUS = STATUS.vbus
CHARGE_STATUS = STATUS.charge
ERROR_REASON = STATUS.error_reason
# The ADC results and the amperes per code of the battery current
DATA_PUBLISHER = cg.HubFunction(
"data",
@@ -77,7 +78,10 @@ OUTPUTS = NPM1300Output.options(
# Written for a field the YAML leaves out
NPM1300_UNSET = 0xFF
# ADCNTCRSEL codes, by kiloohms
THERMISTOR_NONE = "none"
THERMISTOR_RESISTANCES = {10: 1, 47: 2, 100: 3}
# B25/50 of the thermistors the product specification lists for each resistance, by kiloohms
THERMISTOR_BETAS = {10: 3380, 47: 4050, 100: 4250}
LDO_MODES = {"load_switch": 0, "ldo": 1}
TERMINATION_CURRENTS = {"10%": 0, "20%": 1}
# BCHGVTRICKLESEL, by millivolts
@@ -101,14 +105,13 @@ def _one_of_units(
validator: Callable[[object], float],
allowed: list[int],
unit: str,
scale: float = 1000,
) -> Callable[[object], float]:
"""Validate a quantity with `validator` and accept only the listed values, given in units * `scale`."""
"""Validate a quantity with `validator` and accept only the listed values, given in thousandths of `unit`."""
def validate(value: object) -> float:
value = validator(value)
if round(value * scale) not in allowed:
options = ", ".join(f"{v / scale:g}{unit}" for v in allowed)
if _millis(value) not in allowed:
options = ", ".join(f"{v / 1000:g}{unit}" for v in allowed)
raise cv.Invalid(f"Must be one of {options}")
return value
@@ -135,6 +138,23 @@ def _stepped(
return validate
def _thermistor_resistance(value: object) -> float | str:
if isinstance(value, str) and value.lower() == THERMISTOR_NONE:
return THERMISTOR_NONE
value = cv.resistance(value)
if round(value) not in (kilohms * 1000 for kilohms in THERMISTOR_RESISTANCES):
options = ", ".join(f"{kilohms}kOhm" for kilohms in THERMISTOR_RESISTANCES)
raise cv.Invalid(f"Must be one of {options} or {THERMISTOR_NONE}")
return value
def thermistor_beta(config: ConfigType) -> int:
"""The B constant of the hub's thermistor: the configured one, or the one listed for its resistance."""
if (beta := config.get(CONF_THERMISTOR_BETA)) is not None:
return beta
return THERMISTOR_BETAS[round(config[CONF_THERMISTOR_RESISTANCE] / 1000)]
OUTPUT_VOLTAGE = _stepped(cv.voltage, 1000, 3300, 100, "V")
VBUS_CURRENT_LIMIT = _stepped(cv.current, 100, 1500, 100, "A")
@@ -150,15 +170,58 @@ LDO_SCHEMA = BUCK_SCHEMA.extend(
}
)
CHARGER_SCHEMA = cv.Schema(
WARM_TERMINATION_VOLTAGE_DEFAULT = 3.6
def _warm_termination_default(config: ConfigType) -> ConfigType:
"""Keep the default warm termination voltage at or below the termination voltage.
Warn when the default stays below a higher termination voltage.
"""
if (
not isinstance(config, dict)
or CONF_WARM_TERMINATION_VOLTAGE in config
or CONF_TERMINATION_VOLTAGE not in config
):
return config
try:
termination = cv.voltage(config[CONF_TERMINATION_VOLTAGE])
except cv.Invalid:
# The schema reports it
return config
if termination < WARM_TERMINATION_VOLTAGE_DEFAULT - 0.001:
# A warm battery is never charged higher than a cool one
return {
**config,
CONF_WARM_TERMINATION_VOLTAGE: config[CONF_TERMINATION_VOLTAGE],
}
if termination > WARM_TERMINATION_VOLTAGE_DEFAULT + 0.001:
_LOGGER.warning(
"npm1300 '%s' is not set, so a warm battery (45 °C to 60 °C by default) stops "
"charging at %.2fV instead of the %.2fV of '%s'. Set '%s' to the value your "
"battery allows when warm",
CONF_WARM_TERMINATION_VOLTAGE,
WARM_TERMINATION_VOLTAGE_DEFAULT,
termination,
CONF_TERMINATION_VOLTAGE,
CONF_WARM_TERMINATION_VOLTAGE,
)
return config
_CHARGER_SETTINGS_SCHEMA = cv.Schema(
{
cv.Required(CONF_CHARGE_CURRENT): _stepped(cv.current, 32, 800, 2, "A"),
cv.Optional(CONF_TERMINATION_VOLTAGE, default="4.2V"): _one_of_units(
cv.voltage, TERMINATION_VOLTAGES, "V"
# Defaults are the reset values of the product specification
cv.Optional(CONF_CHARGE_CURRENT, default="32mA"): _stepped(
cv.current, 32, 800, 2, "A"
),
cv.Optional(CONF_WARM_TERMINATION_VOLTAGE): _one_of_units(
cv.Optional(CONF_TERMINATION_VOLTAGE, default="3.6V"): _one_of_units(
cv.voltage, TERMINATION_VOLTAGES, "V"
),
cv.Optional(
CONF_WARM_TERMINATION_VOLTAGE,
default=f"{WARM_TERMINATION_VOLTAGE_DEFAULT}V",
): _one_of_units(cv.voltage, TERMINATION_VOLTAGES, "V"),
cv.Optional(CONF_TERMINATION_CURRENT, default="10%"): cv.enum(
TERMINATION_CURRENTS
),
@@ -169,22 +232,37 @@ CHARGER_SCHEMA = cv.Schema(
cv.current, list(DISCHARGE_CURRENT_LIMITS), "A"
),
cv.Optional(CONF_RECHARGE, default=True): cv.boolean,
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
cv.Optional(CONF_ENABLED, default=False): cv.boolean,
}
)
CHARGER_SCHEMA = cv.All(_warm_termination_default, _CHARGER_SETTINGS_SCHEMA)
CONFIG_SCHEMA = (
def _check_thermistor(config: ConfigType) -> ConfigType:
"""A wrong thermistor shifts the battery temperature the charger sees, so charging needs one chosen."""
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
if CONF_CHARGER in config and resistance is None:
raise cv.Invalid(
f"'{CONF_THERMISTOR_RESISTANCE}' is required with '{CONF_CHARGER}': set the nominal "
f"resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
path=[CONF_THERMISTOR_RESISTANCE],
)
if CONF_THERMISTOR_BETA in config and resistance in (None, THERMISTOR_NONE):
raise cv.Invalid(
f"'{CONF_THERMISTOR_BETA}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
"resistance of the thermistor",
path=[CONF_THERMISTOR_BETA],
)
return config
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(NPM1300Component),
cv.Optional(CONF_VBUS_CURRENT_LIMIT): VBUS_CURRENT_LIMIT,
cv.Optional(CONF_THERMISTOR_RESISTANCE): _one_of_units(
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
),
cv.Optional(CONF_THERMISTOR_BETA, default=3380): cv.int_range(
min=1, max=65535
),
cv.Optional(CONF_THERMISTOR_RESISTANCE): _thermistor_resistance,
cv.Optional(CONF_THERMISTOR_BETA): cv.int_range(min=1, max=65535),
cv.Optional(CONF_CHARGER): CHARGER_SCHEMA,
cv.Optional(CONF_BUCK1): BUCK_SCHEMA,
cv.Optional(CONF_BUCK2): BUCK_SCHEMA,
@@ -193,7 +271,8 @@ CONFIG_SCHEMA = (
}
)
.extend(cv.polling_component_schema("60s"))
.extend(i2c.i2c_device_schema(0x6B))
.extend(i2c.i2c_device_schema(0x6B)),
_check_thermistor,
)
@@ -208,7 +287,7 @@ def _vbus_current_limit_code(amps: float) -> int:
def _charger_config(config: ConfigType) -> cg.StructInitializer:
termination = _termination_voltage_code(config[CONF_TERMINATION_VOLTAGE])
warm = config.get(CONF_WARM_TERMINATION_VOLTAGE)
warm = _termination_voltage_code(config[CONF_WARM_TERMINATION_VOLTAGE])
return cg.StructInitializer(
NPM1300ChargerConfig,
("current", _millis(config[CONF_CHARGE_CURRENT]) // 2),
@@ -217,10 +296,7 @@ def _charger_config(config: ConfigType) -> cg.StructInitializer:
DISCHARGE_CURRENT_LIMITS[_millis(config[CONF_DISCHARGE_CURRENT_LIMIT])],
),
("termination_voltage", termination),
(
"warm_termination_voltage",
termination if warm is None else _termination_voltage_code(warm),
),
("warm_termination_voltage", warm),
("trickle_voltage", TRICKLE_VOLTAGES[_millis(config[CONF_TRICKLE_VOLTAGE])]),
("termination_current", TERMINATION_CURRENTS[config[CONF_TERMINATION_CURRENT]]),
("recharge", config[CONF_RECHARGE]),
@@ -247,6 +323,13 @@ def _output_config(config: ConfigType | None) -> cg.StructInitializer:
def _config(config: ConfigType) -> cg.StructInitializer:
charger = config.get(CONF_CHARGER)
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
if resistance is None:
thermistor, beta = NPM1300_UNSET, 0
elif resistance == THERMISTOR_NONE:
thermistor, beta = 0, 0
else:
thermistor = THERMISTOR_RESISTANCES[round(resistance / 1000)]
beta = thermistor_beta(config)
return cg.StructInitializer(
NPM1300Config,
(
@@ -254,13 +337,8 @@ def _config(config: ConfigType) -> cg.StructInitializer:
cg.ArrayInitializer(*(_output_config(config.get(key)) for key in OUTPUTS)),
),
("charger", None if charger is None else _charger_config(charger)),
("thermistor_beta", config[CONF_THERMISTOR_BETA]),
(
"thermistor",
NPM1300_UNSET
if resistance is None
else THERMISTOR_RESISTANCES[round(resistance / 1000)],
),
("thermistor_beta", beta),
("thermistor", thermistor),
("charger_configured", charger is not None),
)
+51 -34
View File
@@ -29,6 +29,7 @@ static constexpr uint16_t REG_BCHG_VTERM = 0x030C;
static constexpr uint16_t REG_BCHG_VTERM_R = 0x030D;
static constexpr uint16_t REG_BCHG_VTRICKLE_SEL = 0x030E;
static constexpr uint16_t REG_BCHG_ITERM_SEL = 0x030F;
static constexpr uint16_t REG_BCHG_NTC_STATUS = 0x0332;
static constexpr uint16_t REG_BCHG_CHARGE_STATUS = 0x0334;
static constexpr uint16_t REG_BCHG_ERR_REASON = 0x0336;
static constexpr uint16_t REG_BUCK1_ENA_SET = 0x0400;
@@ -53,6 +54,9 @@ static constexpr uint16_t REG_SHIP_TASK_SHIP_MODE = 0x0B02;
// VBUSINSTATUS
static constexpr uint8_t VBUS_PRESENT = 0x01;
// NTCSTATUS
static constexpr uint8_t NTC_STATUS_COLD = 0x01;
static constexpr uint8_t NTC_STATUS_HOT = 0x08;
// BCHGCHARGESTATUS; bit 0 (battery detected) is reserved since C00 silicon
static constexpr uint8_t CHARGE_STATUS_COMPLETED = 0x02;
static constexpr uint8_t CHARGE_STATUS_TRICKLE = 0x04;
@@ -107,26 +111,36 @@ float ntc_temperature(uint16_t code, float inv_beta) {
#endif
#ifdef USE_TEXT_SENSOR
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Error", "Paused, Die Too Hot", "Charge Complete", "Trickle Charge",
"Constant Current", "Constant Voltage", "Discharging", "Not Charging");
// BCHGCHARGESTATUS bits in order of priority; bit i is reported as string i + 1
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Discharging", "Error", "Disabled", "Paused, PMIC Too Hot",
"Charge Complete", "Trickle Charge", "Constant Current", "Constant Voltage",
"Paused, Battery Too Cold", "Paused, Battery Too Hot", "Not Charging");
static constexpr uint8_t CHARGER_STATUS_FIRST_BIT = 3;
// BCHGCHARGESTATUS bits in order of priority, reported from string CHARGER_STATUS_FIRST_BIT on
static const uint8_t CHARGER_STATUS_BITS[] PROGMEM = {CHARGE_STATUS_DIE_TEMP_HIGH, CHARGE_STATUS_COMPLETED,
CHARGE_STATUS_TRICKLE, CHARGE_STATUS_CONSTANT_CURRENT,
CHARGE_STATUS_CONSTANT_VOLTAGE};
static uint8_t charger_status_index(uint8_t vbus_status, uint8_t charge_status, uint8_t error_reason) {
if (error_reason != 0)
static uint8_t charger_status_index(const NPM1300Status &status) {
if ((status.vbus & VBUS_PRESENT) == 0)
return 0;
if (status.error_reason != 0)
return 1;
if ((status.charger_enable & 1) == 0)
return 2;
for (size_t i = 0; i < sizeof(CHARGER_STATUS_BITS); i++) {
if ((charge_status & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
return i + 1;
if ((status.charge & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
return CHARGER_STATUS_FIRST_BIT + i;
}
return (vbus_status & VBUS_PRESENT) == 0 ? 6 : 7;
// The charger stops without an error outside the cold and hot limits of the battery temperature
if ((status.ntc & NTC_STATUS_COLD) != 0)
return 8;
if ((status.ntc & NTC_STATUS_HOT) != 0)
return 9;
return 10;
}
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
uint8_t error_reason) {
const uint8_t index = charger_status_index(vbus_status, charge_status, error_reason);
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status) {
const uint8_t index = charger_status_index(status);
if (index == last)
return;
last = index;
@@ -198,7 +212,7 @@ bool NPM1300Component::configure_charger_(const NPM1300Config &config) {
split_9bit(charger.discharge_limit, discharge);
uint8_t disable = charger.recharge ? 0 : CHARGER_DISABLE_RECHARGE;
// Without a thermistor the charger reports an NTC error and does not charge
if (config.thermistor == NPM1300_UNSET)
if (config.thermistor == 0 || config.thermistor == NPM1300_UNSET)
disable |= CHARGER_DISABLE_NTC;
const uint8_t enable = (CHARGER_DISABLE_RECHARGE | CHARGER_DISABLE_NTC) & ~disable;
if (this->write_register16(REG_BCHG_ISET_MSB, current, sizeof(current)) != i2c::ERROR_OK ||
@@ -292,33 +306,40 @@ void NPM1300Component::hibernate(uint32_t duration_ms) {
}
void NPM1300Component::update() {
uint8_t vbus_status;
uint8_t charge_status;
uint8_t error_reason;
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &vbus_status) &&
this->read_byte_reg16(REG_BCHG_CHARGE_STATUS, &charge_status) &&
this->read_byte_reg16(REG_BCHG_ERR_REASON, &error_reason)))
NPM1300Status status;
// NTCSTATUS, DIETEMPSTATUS and BCHGCHARGESTATUS
uint8_t charger_status[3];
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &status.vbus) &&
this->read_byte_reg16(REG_BCHG_ENABLE_SET, &status.charger_enable) &&
this->read_register16(REG_BCHG_NTC_STATUS, charger_status, sizeof(charger_status)) ==
i2c::ERROR_OK &&
this->read_byte_reg16(REG_BCHG_ERR_REASON, &status.error_reason)))
return;
status.ntc = charger_status[0];
status.charge = charger_status[2];
// Without a thermistor the NTC pin is grounded and can read as a hot battery
if (progmem_read_byte(&this->config_->thermistor) == 0)
status.ntc = 0;
// The chip goes back to its default VBUS current limit whenever VBUS is removed
const bool vbus_present = (vbus_status & VBUS_PRESENT) != 0;
const bool vbus_present = (status.vbus & VBUS_PRESENT) != 0;
if (vbus_present && !this->vbus_present_ && this->vbus_current_limit_ != NPM1300_UNSET &&
!this->status_comm_check(this->apply_vbus_current_limit_()))
return;
this->vbus_present_ = vbus_present;
if (error_reason != this->last_error_reason_) {
this->last_error_reason_ = error_reason;
if (error_reason != 0) {
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", error_reason);
if (status.error_reason != this->last_error_reason_) {
this->last_error_reason_ = status.error_reason;
if (status.error_reason != 0) {
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", status.error_reason);
}
}
#ifdef USE_NPM1300_STATUS_PUBLISHER
if (this->status_publisher_ != nullptr)
this->status_publisher_(vbus_status, charge_status, error_reason);
this->status_publisher_(status);
#endif
#ifdef USE_SWITCH
if (!this->status_comm_check(this->publish_switches_()))
if (!this->status_comm_check(this->publish_switches_(status)))
return;
#endif
@@ -348,16 +369,10 @@ void NPM1300Component::update() {
}
#ifdef USE_SWITCH
bool NPM1300Component::publish_switches_() {
bool NPM1300Component::publish_switches_(const NPM1300Status &status) {
PUBLISH_STATE(this->charger_switch_, (status.charger_enable & 1) != 0);
uint8_t value;
bool ok = true;
if (this->charger_switch_ != nullptr) {
if (this->read_byte_reg16(REG_BCHG_ENABLE_SET, &value)) {
this->charger_switch_->publish_state((value & 1) != 0);
} else {
ok = false;
}
}
switch_::Switch *const bucks[2] = {this->buck1_switch_, this->buck2_switch_};
if (bucks[0] != nullptr || bucks[1] != nullptr) {
if (this->read_byte_reg16(REG_BUCK_STATUS, &value)) {
@@ -461,7 +476,9 @@ void NPM1300Component::dump_config() {
ESP_LOGCONFIG(TAG, " Enabled at boot: %s", YESNO(output.enabled != 0));
}
}
if (config.thermistor != NPM1300_UNSET) {
if (config.thermistor == 0) {
ESP_LOGCONFIG(TAG, " Thermistor: none");
} else if (config.thermistor != NPM1300_UNSET) {
ESP_LOGCONFIG(TAG, " Thermistor B constant: %u", config.thermistor_beta);
}
#ifdef USE_SENSOR
+13 -5
View File
@@ -54,10 +54,19 @@ struct NPM1300Config {
NPM1300OutputConfig outputs[NPM1300_OUTPUT_COUNT];
NPM1300ChargerConfig charger; // only applied when charger_configured
uint16_t thermistor_beta;
uint8_t thermistor; // ADCNTCRSEL code: 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
uint8_t thermistor; // ADCNTCRSEL code: 0 for none, 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
bool charger_configured;
};
/// The status registers read on every update
struct NPM1300Status {
uint8_t vbus; // VBUSINSTATUS
uint8_t charger_enable; // BCHGENABLESET
uint8_t ntc; // NTCSTATUS
uint8_t charge; // BCHGCHARGESTATUS
uint8_t error_reason; // BCHGERRREASON
};
#ifdef USE_NPM1300_DATA_PUBLISHER
/// The 10-bit ADC result whose high 8 bits are adc[msb] and low 2 bits are at `shift` in adc[lsbs]
inline uint16_t adc_code(const uint8_t *adc, uint8_t msb, uint8_t lsbs, uint8_t shift) {
@@ -68,8 +77,7 @@ float ntc_temperature(uint16_t code, float inv_beta);
#endif
#ifdef USE_TEXT_SENSOR
/// Publish the charger status text, only when it differs from `last`
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
uint8_t error_reason);
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status);
#endif
class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
@@ -95,7 +103,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
float get_setup_priority() const override { return setup_priority::BUS - 1.0f; }
#ifdef USE_NPM1300_STATUS_PUBLISHER
HUB_PUBLISHER(status, uint8_t, uint8_t, uint8_t)
HUB_PUBLISHER(status, const NPM1300Status &)
#endif
#ifdef USE_NPM1300_DATA_PUBLISHER
HUB_PUBLISHER(data, const uint8_t *, float)
@@ -128,7 +136,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
#endif
#ifdef USE_SWITCH
/// Returns false when a status read failed
bool publish_switches_();
bool publish_switches_(const NPM1300Status &status);
#endif
const NPM1300Config *config_;
+6 -5
View File
@@ -21,7 +21,6 @@ from esphome.types import ConfigType
from . import (
ADC,
CONF_NPM1300_ID,
CONF_THERMISTOR_BETA,
CONF_THERMISTOR_RESISTANCE,
CONF_VBUS_CURRENT_LIMIT,
DATA_PUBLISHER,
@@ -30,7 +29,9 @@ from . import (
DUMP_TAG,
IBAT_SCALE,
NPM1300_CHILD_SCHEMA,
THERMISTOR_NONE,
npm1300_ns,
thermistor_beta,
)
DEPENDENCIES = ["npm1300"]
@@ -109,10 +110,10 @@ def _final_validate(config: ConfigType) -> None:
if CONF_BATTERY_TEMPERATURE not in config:
return
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
if CONF_THERMISTOR_RESISTANCE not in hub:
if hub.get(CONF_THERMISTOR_RESISTANCE, THERMISTOR_NONE) == THERMISTOR_NONE:
raise cv.Invalid(
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' "
"set on the npm1300 component",
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
"nominal resistance of the battery thermistor on the npm1300 component",
path=[CONF_BATTERY_TEMPERATURE],
)
@@ -145,7 +146,7 @@ async def to_code(config: ConfigType) -> None:
if (var := await sensors(CONF_BATTERY_TEMPERATURE, None)) is not None:
hub_config = next(c for c in CORE.config[DOMAIN] if c[CONF_ID] == hub_id)
state = npm1300_ns.ntc_temperature(
_adc(2, 5, 2), 1.0 / hub_config[CONF_THERMISTOR_BETA]
_adc(2, 5, 2), 1.0 / thermistor_beta(hub_config)
)
_add_adc_sensor(hub, var, state, "Battery Temperature")
await sensors(CONF_VBUS_CURRENT_LIMIT, hub.set_vbus_current_limit_sensor)
+12 -4
View File
@@ -15,6 +15,7 @@ from . import (
CONF_THERMISTOR_RESISTANCE,
NPM1300_CHILD_SCHEMA,
OUTPUTS,
THERMISTOR_NONE,
)
DEPENDENCIES = ["npm1300"]
@@ -44,11 +45,18 @@ def _final_validate(config: ConfigType) -> None:
if CONF_CHARGER not in config:
return
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
# Only the charger block turns off the NTC check, without which the charger never starts
if CONF_CHARGER not in hub and CONF_THERMISTOR_RESISTANCE not in hub:
# A wrong thermistor shifts the battery temperature the charger sees
if CONF_THERMISTOR_RESISTANCE not in hub:
raise cv.Invalid(
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block or "
f"'{CONF_THERMISTOR_RESISTANCE}' on the npm1300 component",
f"The '{CONF_CHARGER}' switch needs '{CONF_THERMISTOR_RESISTANCE}' on the npm1300 "
f"component: the nominal resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
path=[CONF_CHARGER],
)
# Only the charger block turns off the NTC check, without which the charger never starts
if CONF_CHARGER not in hub and hub[CONF_THERMISTOR_RESISTANCE] == THERMISTOR_NONE:
raise cv.Invalid(
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block when "
f"'{CONF_THERMISTOR_RESISTANCE}' is '{THERMISTOR_NONE}'",
path=[CONF_CHARGER],
)
+2 -6
View File
@@ -11,14 +11,12 @@ from esphome.cpp_generator import (
from esphome.types import ConfigType
from . import (
CHARGE_STATUS,
CONF_NPM1300_ID,
DUMP,
DUMP_TAG,
ERROR_REASON,
NPM1300_CHILD_SCHEMA,
STATUS,
STATUS_PUBLISHER,
VBUS_STATUS,
npm1300_ns,
)
@@ -48,9 +46,7 @@ async def to_code(config: ConfigType) -> None:
)
STATUS_PUBLISHER.add(
hub,
npm1300_ns.publish_charger_status(
parent_ref(var), last, VBUS_STATUS, CHARGE_STATUS, ERROR_REASON
),
npm1300_ns.publish_charger_status(parent_ref(var), last, STATUS),
)
DUMP.add(
hub,
+10 -3
View File
@@ -13,6 +13,7 @@ from esphome.build_helpers.ccache import resolve_ccache_path
import esphome.codegen as cg
from esphome.components import network
from esphome.components.zephyr import (
PreferenceStorage,
Section,
add_extra_script,
copy_files as zephyr_copy_files,
@@ -106,6 +107,7 @@ from .const import (
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANT_REGULATOR,
VARIANTS_NRF54L,
VARIANTS_WITHOUT_USB,
)
from .framework import (
@@ -536,6 +538,11 @@ def _final_validate(config):
FINAL_VALIDATE_SCHEMA = _final_validate
def _preferences_storage(variant: str) -> PreferenceStorage:
"""The storage for preferences: ZMS on the RRAM of the nRF54L, NVS on flash."""
return "ZMS" if variant in VARIANTS_NRF54L else "NVS"
@coroutine_with_priority(CoroPriority.PLATFORM)
async def to_code(config: ConfigType) -> None:
"""Convert the configuration to code."""
@@ -544,7 +551,7 @@ async def to_code(config: ConfigType) -> None:
variant = get_nrf52_variant()
cg.add_define("ESPHOME_VARIANT", variant)
cg.add_build_flag(f"-DUSE_NRF52_VARIANT_{variant}")
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if variant in VARIANTS_NRF54L:
# The entropy driver runs on the CRACEN crypto unit, which needs Nordic's PSA crypto
include_west_project("mbedtls")
include_west_project("oberon-psa-crypto")
@@ -612,11 +619,11 @@ async def to_code(config: ConfigType) -> None:
if config[KEY_BOOTLOADER] in ADAFRUIT_BOOTLOADERS:
cg.add_define("USE_BOOTLOADER_ADAFRUIT")
zephyr_setup_preferences()
zephyr_setup_preferences(_preferences_storage(variant))
zephyr_to_code(config)
# The nRF54L has RRAM (cpuapp_rram) and no flash0 node
if CORE.testing_mode and variant not in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if CORE.testing_mode and variant not in VARIANTS_NRF54L:
zephyr_add_overlay(
f"""
&flash0 {{
+2 -1
View File
@@ -17,6 +17,7 @@ from .const import (
VARIANT_NRF54LM20,
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANTS_NRF54L,
)
from .framework import (
check_and_install,
@@ -145,7 +146,7 @@ def upload_using_cmsis_dap(unique_id: str | None = None) -> None:
pyocd = [str(paths["python_executable"]), "-m", "pyocd"]
probe = ["-t", target] + (["-u", unique_id] if unique_id else [])
cmd = [*pyocd, "flash", "--no-wait", *probe, "-e", "sector"]
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if variant in VARIANTS_NRF54L:
cmd += ["--script", str(_NRF54L_WATCHDOG_SCRIPT)]
cmd += [str(image) for image in images]
if not run_command_ok(cmd, env=env, stream_output=True):
+2
View File
@@ -41,6 +41,8 @@ VARIANT_I2C = {
VARIANT_NRF54LM20: VariantI2C("i2c21", (1, 3)),
}
VARIANTS_WITHOUT_USB = frozenset({VARIANT_NRF52832, VARIANT_NRF54L15})
# The nRF54L family: RRAM instead of flash, the CRACEN crypto unit and the wdt31 watchdog
VARIANTS_NRF54L = frozenset({VARIANT_NRF54L15, VARIANT_NRF54LM20})
# Devicetree label of the main regulator, reg1 on the others
VARIANT_REGULATOR = {VARIANT_NRF52832: "reg"}
VARIANT_FLASH_SIZE = {VARIANT_NRF52832: 0x80000, VARIANT_NRF52840: 0x100000}
@@ -83,6 +83,9 @@ class PartitionLightOutput final : public light::AddressableLight {
void set(int32_t index, Color color) override {
light::ESPColorView color_view = this->parent_->get_color_view_(index);
// A white level the LED cannot show must not count as the pixel's strongest channel
if (!color_view.has_white_internal()) // NOLINT
color.white = 0;
color_view.set_raw(this->parent_->get_color_correction_(color_view)->color_correct(color));
}
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
@@ -98,6 +101,10 @@ class PartitionLightOutput final : public light::AddressableLight {
this->parent_->get_color_view_(index).set_effect_data(value);
}
bool has_white_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_view_(index).has_white_internal();
}
#ifdef USE_LIGHT_POWER_ESTIMATION
const light::ESPColorCorrection *get_color_correction_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_correction_(this->parent_->get_color_view_(index));
+3
View File
@@ -0,0 +1,3 @@
"""PCM1863 audio ADC component."""
DOMAIN = "pcm1863"
+62
View File
@@ -0,0 +1,62 @@
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.audio_adc import AudioAdc
import esphome.config_validation as cv
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_INPUT, CONF_MIC_GAIN
from esphome.types import ConfigType
CODEOWNERS = ["@anabolyc"]
DEPENDENCIES = ["i2c"]
CONF_PCM1863_ID = "pcm1863_id"
# The PGA covers -12 dB to +40 dB in 0.5 dB steps
PCM1863_MIC_GAIN_MIN = -12.0
PCM1863_MIC_GAIN_MAX = 40.0
pcm1863_ns = cg.esphome_ns.namespace("pcm1863")
PCM1863 = pcm1863_ns.class_("PCM1863", AudioAdc, cg.Component, i2c.I2CDevice)
pcm1863_input = pcm1863_ns.enum("PCM1863Input")
# The declaration order is the select option order and the C++ enum value of each input
PCM1863_INPUT_ENUM = pcm1863_input.options(
"NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2", prefix="PCM1863_INPUT_"
)
pcm1863_bits_per_sample = pcm1863_ns.enum("PCM1863BitsPerSample")
PCM1863_BITS_PER_SAMPLE_ENUM = {
16: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_16,
20: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_20,
24: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_24,
32: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_32,
}
_validate_bits = cv.float_with_unit("bits", "bit")
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(PCM1863),
cv.Optional(CONF_BITS_PER_SAMPLE, default="24bit"): cv.All(
_validate_bits, cv.enum(PCM1863_BITS_PER_SAMPLE_ENUM)
),
cv.Optional(CONF_INPUT, default="VIN1"): cv.enum(
PCM1863_INPUT_ENUM, upper=True
),
cv.Optional(CONF_MIC_GAIN, default="0db"): cv.All(
cv.decibel,
cv.float_range(min=PCM1863_MIC_GAIN_MIN, max=PCM1863_MIC_GAIN_MAX),
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(i2c.i2c_device_schema(0x4A))
)
async def to_code(config: ConfigType) -> None:
var = await i2c.new_i2c_component(config)
cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
cg.add(var.set_input(config[CONF_INPUT]))
cg.add(var.set_mic_gain(config[CONF_MIC_GAIN]))
+96
View File
@@ -0,0 +1,96 @@
#include "pcm1863.h"
#include "pcm1863_const.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include <cmath>
namespace esphome::pcm1863 {
ESPHOME_LOG_TAG(TAG, "pcm1863");
// Indexed by PCM1863BitsPerSample
PROGMEM_STRING_TABLE(BitsPerSampleStrings, "32", "24", "20", "16");
PROGMEM_STRING_TABLE(InputStrings, "NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2");
// Page select and power up: bits 2:0 clear is the run state, and the reserved bits 7:3
// must be written as 0b01110 or the analog section stops
static constexpr i2c::I2CRegValue PCM1863_INIT[] PROGMEM = {
{PCM1863_REG_PAGE, PCM1863_PAGE_0},
{PCM1863_REG_POWER_CTRL, PCM1863_PWR_CTRL_RSV},
};
void PCM1863::dump_config() {
ESP_LOGCONFIG(TAG,
"PCM1863 audio ADC:\n"
" Bits Per Sample: %s\n"
" Input: %s\n"
" Mic Gain: %.1f dB",
LOG_STR_ARG(BitsPerSampleStrings::get_log_str(this->bits_per_sample_, 0)),
LOG_STR_ARG(InputStrings::get_log_str(this->input_, 0)), this->mic_gain_);
#ifdef USE_PCM1863_SELECT
LOG_SELECT(" ", "Input", this->input_select_);
#endif
}
void PCM1863::setup() {
// Writing PCM1863_RESET to the page selector restores every register to its default
if (!this->setup_check(this->write_byte(PCM1863_REG_PAGE, PCM1863_RESET)))
return;
delay(2);
// The datasheet does not say which page the reset leaves selected, so select page 0 first
if (!this->setup_check(this->write_registers(PCM1863_INIT)))
return;
if (!this->setup_check(this->configure_i2s_format_() && this->configure_input_() && this->configure_mic_gain_()))
return;
this->setup_complete_ = true;
#ifdef USE_PCM1863_SELECT
// Show the input the ADC booted with, so the select does not start out blank
PUBLISH_STATE(this->input_select_, this->input_);
#endif
}
bool PCM1863::set_mic_gain(float mic_gain) {
// Nothing reaches the chip after a failed setup, so report the change as not applied
if (this->is_failed())
return false;
this->mic_gain_ = clamp<float>(mic_gain, PCM1863_MIC_GAIN_MIN, PCM1863_MIC_GAIN_MAX);
if (!this->setup_complete_)
return true;
return this->status_comm_result(this->configure_mic_gain_());
}
bool PCM1863::configure_mic_gain_() {
// The PGA gain registers take a two's complement value in 0.5 dB steps
const auto reg_val = static_cast<uint8_t>(lroundf(this->mic_gain_ / PCM1863_MIC_GAIN_STEP));
return this->write_byte(PCM1863_REG_PGA_VAL_CH1_L, reg_val) && this->write_byte(PCM1863_REG_PGA_VAL_CH1_R, reg_val);
}
bool PCM1863::set_input(PCM1863Input input) {
if (this->is_failed())
return false;
this->input_ = input;
if (!this->setup_complete_)
return true;
return this->status_comm_result(this->configure_input_());
}
bool PCM1863::configure_input_() {
// Bit 6 of both input select registers is reserved and must always be written as 1
const uint8_t mux = this->input_ == PCM1863_INPUT_NONE ? 0 : 1 << (this->input_ - 1);
const uint8_t reg_val = PCM1863_INPUT_SEL_RSV | mux;
return this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_L, reg_val) &&
this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_R, reg_val);
}
bool PCM1863::configure_i2s_format_() {
const uint8_t wlen = this->bits_per_sample_;
const uint8_t reg_val =
(wlen << PCM1863_PCM_CFG_RX_WLEN_SHIFT) | (wlen << PCM1863_PCM_CFG_TX_WLEN_SHIFT) | PCM1863_PCM_CFG_FMT_I2S;
return this->write_byte(PCM1863_REG_PCM_CFG, reg_val);
}
} // namespace esphome::pcm1863
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include "esphome/components/audio_adc/audio_adc.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/core/component.h"
#ifdef USE_PCM1863_SELECT
#include "esphome/components/select/select.h"
#endif
#include "pcm1863_const.h"
namespace esphome::pcm1863 {
// Positions of the select options, in the order audio_adc.py declares them
enum PCM1863Input : uint8_t {
PCM1863_INPUT_NONE,
PCM1863_INPUT_VIN1,
PCM1863_INPUT_VIN2,
PCM1863_INPUT_VIN3,
PCM1863_INPUT_VIN4,
PCM1863_INPUT_DIFF_1,
PCM1863_INPUT_DIFF_2,
};
// The word length code of PCM1863_REG_PCM_CFG
enum PCM1863BitsPerSample : uint8_t {
PCM1863_BITS_PER_SAMPLE_32,
PCM1863_BITS_PER_SAMPLE_24,
PCM1863_BITS_PER_SAMPLE_20,
PCM1863_BITS_PER_SAMPLE_16,
};
/// Texas Instruments PCM1863 stereo audio ADC for line and microphone input.
/// The register map and reset sequence follow the datasheet (SLAS831D) and the Linux
/// kernel driver in sound/soc/codecs/pcm186x.c.
class PCM1863 final : public audio_adc::AudioAdc, public Component, public i2c::I2CDevice {
#ifdef USE_PCM1863_SELECT
SUB_SELECT(input)
#endif
public:
void setup() override;
void dump_config() override;
void set_bits_per_sample(PCM1863BitsPerSample bits_per_sample) { this->bits_per_sample_ = bits_per_sample; }
/// Selects the analog input. Takes effect immediately once setup has run.
bool set_input(PCM1863Input input);
bool set_mic_gain(float mic_gain) override;
float mic_gain() override { return this->mic_gain_; }
protected:
bool configure_i2s_format_();
bool configure_mic_gain_();
bool configure_input_();
float mic_gain_{0};
bool setup_complete_{false};
PCM1863BitsPerSample bits_per_sample_{PCM1863_BITS_PER_SAMPLE_24};
PCM1863Input input_{PCM1863_INPUT_VIN1};
};
} // namespace esphome::pcm1863
@@ -0,0 +1,50 @@
#pragma once
#include <cstdint>
namespace esphome::pcm1863 {
// PCM1863 page 0 register addresses.
// Names and layout follow the Texas Instruments PCM186x family register map (SLAS831D).
static constexpr uint8_t PCM1863_REG_PAGE = 0x00; /* Page selector; writing 0xFE triggers a full reset */
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_L = 0x01; /* ADC1 left PGA gain, 0.5 dB/LSB, two's complement */
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_R = 0x02; /* ADC1 right PGA gain, 0.5 dB/LSB, two's complement */
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_L = 0x06;
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_R = 0x07;
static constexpr uint8_t PCM1863_REG_PCM_CFG = 0x0B; /* Word length and serial audio format */
static constexpr uint8_t PCM1863_REG_POWER_CTRL = 0x70; /* Power down, sleep and standby */
// PCM1863_REG_PAGE: the register holds the page number, and the two documented
// commands are selecting a page and resetting every register
static constexpr uint8_t PCM1863_PAGE_0 = 0x00;
static constexpr uint8_t PCM1863_RESET = 0xFE;
// PCM1863_REG_PCM_CFG: receive word length in bits 7:6, transmit word length in bits 3:2,
// serial audio format in bits 1:0. Bit 5 is reserved and bit 4 only applies to TDM; both
// are zero at reset and are written as zero here.
static constexpr uint8_t PCM1863_PCM_CFG_RX_WLEN_SHIFT = 6;
static constexpr uint8_t PCM1863_PCM_CFG_TX_WLEN_SHIFT = 2;
static constexpr uint8_t PCM1863_PCM_CFG_FMT_I2S = 0x00;
// PCM1863_REG_ADC1_INPUT_SEL_L / _R
// Bit 7 selects signal polarity, bit 6 is reserved and must always be written as 1,
// and bits 5:0 pick the analog input. See the PCM186x datasheet, "MUX, MIX, and
// Polarity Input Selection".
static constexpr uint8_t PCM1863_INPUT_SEL_RSV = 0x40; // bit 6, always write 1
// Bits 5:0 select one input: none, VIN1 to VIN4 single-ended (0x01 to 0x08), then the
// differential pairs VIN1/VIN2 (0x10) and VIN4/VIN3 (0x20)
// PCM1863_REG_POWER_CTRL
// Bits 2:0 are power down, sleep and standby; all three are clear in the run state.
// Bits 7:3 are reserved and the datasheet requires them to always be written as 0b01110,
// which is also their reset value. Writing them as zero stops the analog section.
static constexpr uint8_t PCM1863_PWR_CTRL_RSV = 0x70;
// The PGA gain registers hold a two's complement value in 0.5 dB steps,
// from -24 (-12 dB) to +80 (+40 dB)
static constexpr float PCM1863_MIC_GAIN_MIN = -12.0f;
static constexpr float PCM1863_MIC_GAIN_MAX = 40.0f;
static constexpr float PCM1863_MIC_GAIN_STEP = 0.5f;
} // namespace esphome::pcm1863
+32
View File
@@ -0,0 +1,32 @@
import esphome.codegen as cg
from esphome.components import select
import esphome.config_validation as cv
from esphome.const import ENTITY_CATEGORY_CONFIG, ICON_CHIP
from esphome.types import ConfigType
from .audio_adc import CONF_PCM1863_ID, PCM1863, PCM1863_INPUT_ENUM
PCM1863_INPUT_OPTIONS = list(PCM1863_INPUT_ENUM)
CONFIG_SCHEMA = select.select_schema(
select.ApplySelect,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_CHIP,
).extend(
{
cv.GenerateID(CONF_PCM1863_ID): cv.use_id(PCM1863),
}
)
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_PCM1863_SELECT")
hub = await cg.get_variable(config[CONF_PCM1863_ID])
# The ADC publishes the new option only once the I2C write went through
await select.sub_selects(config, parent=hub).create(
config,
hub.set_input_select,
options=PCM1863_INPUT_OPTIONS,
apply="set_input(static_cast<pcm1863::PCM1863Input>(index))",
publish="on_success",
)
+10
View File
@@ -0,0 +1,10 @@
"""Pioneer WT series mini splits, controlled through the serial port of the WiFi module."""
import esphome.codegen as cg
CODEOWNERS = ["@martinsah"]
DOMAIN = "pioneer_wt"
pioneer_wt_ns = cg.esphome_ns.namespace("pioneer_wt")
CONF_PIONEER_WT_ID = "pioneer_wt_id"
+33
View File
@@ -0,0 +1,33 @@
import esphome.codegen as cg
from esphome.components import climate, uart
import esphome.config_validation as cv
from esphome.types import ConfigType
from . import DOMAIN, pioneer_wt_ns
DEPENDENCIES = ["uart"]
PioneerWT = pioneer_wt_ns.class_(
"PioneerWT", climate.Climate, uart.UARTDevice, cg.Component
)
CONFIG_SCHEMA = (
climate.climate_schema(PioneerWT)
.extend(uart.UART_DEVICE_SCHEMA)
.extend(cv.COMPONENT_SCHEMA)
)
FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema(
DOMAIN,
baud_rate=115200,
require_tx=True,
require_rx=True,
data_bits=8,
parity="NONE",
stop_bits=1,
)
async def to_code(config: ConfigType) -> None:
var = await uart.new_uart_component(config)
await climate.register_climate(var, config)
@@ -0,0 +1,340 @@
#include "pioneer_wt.h"
#include <cinttypes>
#include <cmath>
#include <cstring>
#include <iterator>
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
namespace esphome::pioneer_wt {
ESPHOME_LOG_TAG(TAG, "pioneer_wt");
static constexpr uint32_t RESEND_INTERVAL_MS = 500;
static constexpr uint8_t MAX_ATTEMPTS = 4;
// Ask for a full status again if the AC has reported nothing for this long.
static constexpr uint32_t STATUS_REFRESH_MS = 5 * 60 * 1000;
// Until the first full status has arrived, ask again this often.
static constexpr uint32_t STATUS_RETRY_MS = 30 * 1000;
static constexpr float MIN_TEMPERATURE_C = 16.0f;
static constexpr float MAX_TEMPERATURE_C = 31.0f;
static constexpr uint8_t FAN_SPEED_COUNT = 7;
static constexpr const char *const FAN_SPEED_NAMES[FAN_SPEED_COUNT] PROGMEM = {
"Speed 1", "Speed 2", "Speed 3", "Speed 4", "Speed 5", "Speed 6", "Speed 7"};
// Reply to the AC's once-a-minute check, as the stock module sends it. The last body byte is the
// WiFi signal in dBm; a fixed -48 is enough for the AC.
static constexpr uint8_t PRESENCE_REPLY_FRAME[] PROGMEM = {0xA5, 0x01, 0x00, 0x23, 0x00, 0x00, 0x00, 0x12, 0x47,
0x09, 0x80, 0x0C, 0x02, 0x64, 0xFF, 0xFF, 0xFF, 0xD0};
// Climate mode for each value of ATTR_MODE
static constexpr uint8_t CLIMATE_MODES[] PROGMEM = {
climate::CLIMATE_MODE_HEAT_COOL, climate::CLIMATE_MODE_COOL, climate::CLIMATE_MODE_DRY,
climate::CLIMATE_MODE_FAN_ONLY, climate::CLIMATE_MODE_HEAT,
};
void PioneerWT::setup() {
this->set_supported_custom_fan_modes_static(FAN_SPEED_NAMES, FAN_SPEED_COUNT);
this->request_status_();
#ifdef USE_SWITCH
if (this->display_switch_ != nullptr)
this->display_switch_->restore();
if (this->beeper_switch_ != nullptr)
this->beeper_switch_->restore();
#endif
}
climate::ClimateTraits PioneerWT::traits() {
auto traits = climate::ClimateTraits();
traits.add_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE);
traits.set_supported_modes({climate::CLIMATE_MODE_OFF, climate::CLIMATE_MODE_HEAT_COOL, climate::CLIMATE_MODE_COOL,
climate::CLIMATE_MODE_HEAT, climate::CLIMATE_MODE_DRY, climate::CLIMATE_MODE_FAN_ONLY});
traits.set_supported_fan_modes({climate::CLIMATE_FAN_AUTO});
traits.set_supported_swing_modes({climate::CLIMATE_SWING_OFF, climate::CLIMATE_SWING_VERTICAL});
traits.set_supported_presets({climate::CLIMATE_PRESET_NONE, climate::CLIMATE_PRESET_ECO});
traits.set_visual_min_temperature(MIN_TEMPERATURE_C);
traits.set_visual_max_temperature(MAX_TEMPERATURE_C);
// The AC keeps its setpoint in whole degrees Fahrenheit, so half degrees Celsius would not all be kept.
traits.set_visual_target_temperature_step(1.0f);
traits.set_visual_current_temperature_step(0.1f);
return traits;
}
void PioneerWT::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto handle = [this](const uint8_t *frame, size_t len) {
if (!checksum_valid(frame, len)) {
ESP_LOGD(TAG, "Dropped a frame with a wrong checksum");
return false;
}
this->handle_frame_(frame, len);
return true;
};
this->read_frames(this->reader_, handle, now, this->last_rx_);
if (!this->queue_.empty() && now - this->last_send_ >= RESEND_INTERVAL_MS)
this->send_pending_();
// The target temperature only arrives in a full status, so it tells whether one has been received.
const uint32_t status_interval = std::isnan(this->target_temperature) ? STATUS_RETRY_MS : STATUS_REFRESH_MS;
if (now - this->last_status_ >= status_interval)
this->request_status_();
}
void PioneerWT::handle_frame_(const uint8_t *frame, size_t len) {
const uint8_t flags = frame[2];
const uint8_t type = frame[3];
const uint8_t seq = frame[4];
const uint8_t ack = frame[5];
const uint8_t *payload = frame + HEADER_SIZE;
const size_t payload_len = len - HEADER_SIZE;
ESP_LOGVV_HEX(TAG, frame, len, MAX_FRAME_SIZE, "RX %s");
if (type == TYPE_REPLY) {
if (!this->queue_.empty() && this->queue_.front().seq == ack) {
if (this->queue_.front().power != POWER_UNCHANGED)
this->acked_power_ = this->queue_.front().power;
// Pop first: the warning log can run automations that queue another command.
this->pop_command_();
this->status_clear_warning();
this->last_send_ = 0; // send the next one right away
}
return;
}
if (type != TYPE_DATA || payload_len < 2)
return;
const uint8_t msg_class = payload[0];
if (flags & FLAG_WANT_ACK)
this->write_frame_(FLAG_WANT_ACK, TYPE_REPLY, 0, seq, CLASS_REPLY, msg_class, nullptr, 0);
if (msg_class != CLASS_STATUS)
return;
if (payload_len == 2) {
if (!(flags & FLAG_WANT_ACK))
this->write_array_progmem(PRESENCE_REPLY_FRAME, sizeof(PRESENCE_REPLY_FRAME));
return;
}
this->handle_status_(payload + 2, payload_len - 2);
// Reports count only once a full status has arrived, so the boot request is repeated until one does.
if (!std::isnan(this->target_temperature))
this->last_status_ = App.get_loop_component_start_time();
}
void PioneerWT::handle_status_(const uint8_t *body, size_t len) {
AttributeReader attrs(body, len);
bool changed = false;
while (attrs.next()) {
const uint32_t v = attrs.value();
switch (attrs.id()) {
case ATTR_POWER:
this->power_ = v != 0;
this->acked_power_ = POWER_UNCHANGED;
break;
case ATTR_MODE:
if (v < std::size(CLIMATE_MODES)) {
this->ac_mode_ = v;
} else {
ESP_LOGD(TAG, "Unknown mode %" PRIu32, v);
}
break;
case ATTR_SETPOINT_F: {
const float target = fahrenheit_to_celsius(v);
changed |= target != this->target_temperature;
this->target_temperature = target;
break;
}
case ATTR_INDOOR_TEMP_C100: {
const float current = static_cast<float>(v) / 100.0f;
changed |= current != this->current_temperature;
this->current_temperature = current;
break;
}
case ATTR_FAN_SPEED:
if (v == 0) {
changed |= this->set_fan_mode_(climate::CLIMATE_FAN_AUTO);
} else if (v <= FAN_SPEED_COUNT) {
changed |= this->set_custom_fan_mode_(FAN_SPEED_NAMES[v - 1]);
} else {
ESP_LOGD(TAG, "Unknown fan speed %" PRIu32, v);
}
break;
case ATTR_SWING_VERTICAL: {
const auto swing = v == SWING_ON ? climate::CLIMATE_SWING_VERTICAL : climate::CLIMATE_SWING_OFF;
changed |= swing != this->swing_mode;
this->swing_mode = swing;
break;
}
case ATTR_ECO:
changed |= this->set_preset_(v ? climate::CLIMATE_PRESET_ECO : climate::CLIMATE_PRESET_NONE);
break;
#ifdef USE_SWITCH
case ATTR_DISPLAY:
PUBLISH_STATE(this->display_switch_, v != 0);
break;
case ATTR_BEEPER:
PUBLISH_STATE(this->beeper_switch_, v != 0);
break;
#endif
default:
break;
}
}
if (attrs.stopped_on_unknown()) {
ESP_LOGD(TAG, "Status attribute %04X has an unknown size; ignored the rest of the frame", attrs.id());
}
const auto mode = this->power_ ? static_cast<climate::ClimateMode>(progmem_read_byte(&CLIMATE_MODES[this->ac_mode_]))
: climate::CLIMATE_MODE_OFF;
changed |= mode != this->mode;
this->mode = mode;
if (changed)
this->publish_state();
}
void PioneerWT::control(const climate::ClimateCall &call) {
uint8_t body[MAX_BODY_SIZE];
uint8_t *p = body;
int8_t power = POWER_UNCHANGED;
if (call.get_mode().has_value()) {
const auto mode = *call.get_mode();
if (mode == climate::CLIMATE_MODE_OFF) {
power = 0;
p = put_attr(p, ATTR_POWER, 0);
} else {
uint8_t ac_mode = 0;
for (size_t i = 0; i < std::size(CLIMATE_MODES); i++) {
if (progmem_read_byte(&CLIMATE_MODES[i]) == mode) {
ac_mode = i;
break;
}
}
// Queued commands count: an "off" still waiting to be sent is followed by a power on.
if (!this->wanted_power_(this->queue_.size() == TX_QUEUE_SIZE)) {
power = 1;
p = put_attr(p, ATTR_POWER, 1);
}
p = put_attr(p, ATTR_MODE, ac_mode);
}
}
if (call.get_target_temperature().has_value()) {
// Automations can ask for any value; the visual range is not enforced for them.
const float celsius = clamp(*call.get_target_temperature(), MIN_TEMPERATURE_C, MAX_TEMPERATURE_C);
p = put_be32(put_be16(p, ATTR_SETPOINT_F), lroundf(celsius_to_fahrenheit(celsius)));
}
// The app always sends fan speed with these companions; match it exactly.
int fan_speed = -1;
if (call.get_fan_mode().has_value() && *call.get_fan_mode() == climate::CLIMATE_FAN_AUTO) {
fan_speed = 0;
} else if (call.has_custom_fan_mode()) {
// The call holds the pointer from FAN_SPEED_NAMES, so the pointers can be compared.
const char *name = call.get_custom_fan_mode().c_str();
for (uint8_t i = 0; i < FAN_SPEED_COUNT; i++) {
if (name == FAN_SPEED_NAMES[i]) {
fan_speed = i + 1;
break;
}
}
}
if (fan_speed >= 0) {
p = put_attr(p, ATTR_FAN_EXTRA_1, 0);
p = put_attr(p, ATTR_FAN_EXTRA_2, 0);
p = put_attr(p, ATTR_FAN_SPEED, fan_speed);
p = put_attr(p, ATTR_FAN_AUTO, fan_speed == 0);
}
if (call.get_swing_mode().has_value()) {
const bool swing = *call.get_swing_mode() == climate::CLIMATE_SWING_VERTICAL;
p = put_attr(p, ATTR_SWING_VERTICAL, swing ? SWING_ON : SWING_OFF);
}
if (call.get_preset().has_value())
p = put_attr(p, ATTR_ECO, *call.get_preset() == climate::CLIMATE_PRESET_ECO);
if (p != body)
this->queue_command_(CLASS_COMMAND, body, p - body, power);
// State is published when the AC reports the new values back.
}
void PioneerWT::send_setting_(uint16_t attr, bool on) {
uint8_t body[3];
put_attr(body, attr, on);
this->queue_command_(CLASS_COMMAND, body, sizeof(body));
}
void PioneerWT::request_status_() {
// Asks the AC to send every setting, as the stock module does at boot.
static constexpr uint8_t REQUEST_ALL[] = {0xFF, 0xFF};
this->queue_command_(CLASS_NETWORK, REQUEST_ALL, sizeof(REQUEST_ALL));
this->last_status_ = App.get_loop_component_start_time();
}
void PioneerWT::queue_command_(uint8_t msg_class, const uint8_t *body, size_t len, int8_t power) {
if (this->queue_.size() == TX_QUEUE_SIZE) {
ESP_LOGW(TAG, "Command queue full; dropping the oldest command");
this->pop_command_();
}
PendingCommand pending{msg_class, this->next_seq_++, static_cast<uint8_t>(len), power, {}};
std::memcpy(pending.body.data(), body, len);
this->queue_.push(pending);
if (this->next_seq_ == 0)
this->next_seq_ = 1;
}
void PioneerWT::pop_command_() {
this->queue_.pop();
this->attempts_ = 0;
}
bool PioneerWT::wanted_power_(bool skip_head) const {
// An acknowledged power change counts until the AC reports the power
bool power = this->acked_power_ == POWER_UNCHANGED ? this->power_ : this->acked_power_;
for (const PendingCommand &pending : this->queue_) {
if (skip_head) {
skip_head = false;
continue;
}
if (pending.power != POWER_UNCHANGED)
power = pending.power;
}
return power;
}
void PioneerWT::send_pending_() {
const PendingCommand &pending = this->queue_.front();
if (this->attempts_ >= MAX_ATTEMPTS) {
const uint8_t seq = pending.seq;
// Pop first: the warning log can run automations that queue another command.
this->pop_command_();
ESP_LOGD(TAG, "No acknowledgement for command seq %02X; giving up", seq);
this->status_set_warning(LOG_STR("No acknowledgement"));
return;
}
this->attempts_++;
this->write_frame_(FLAG_WANT_ACK, TYPE_DATA, pending.seq, 0, pending.msg_class, pending.msg_class,
pending.body.data(), pending.len);
this->last_send_ = App.get_loop_component_start_time();
}
void PioneerWT::write_frame_(uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1, uint8_t class_2,
const uint8_t *body, size_t len) {
uint8_t frame[HEADER_SIZE + 2 + MAX_BODY_SIZE];
const size_t total = build_frame(frame, flags, type, seq, ack, class_1, class_2, body, len);
ESP_LOGVV_HEX(TAG, frame, total, sizeof(frame), "TX %s");
this->write_array(frame, total);
}
void PioneerWT::dump_config() {
LOG_CLIMATE("", "Pioneer WT", this);
#ifdef USE_SWITCH
LOG_SWITCH(" ", "Display", this->display_switch_);
LOG_SWITCH(" ", "Beeper", this->beeper_switch_);
#endif
}
} // namespace esphome::pioneer_wt
@@ -0,0 +1,85 @@
#pragma once
#include <array>
#include <cstdint>
#include "esphome/components/climate/climate.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#ifdef USE_SWITCH
#include "esphome/components/switch/switch.h"
#endif
#include "pioneer_wt_protocol.h"
namespace esphome::pioneer_wt {
// The largest body control() builds is 30 bytes.
static constexpr size_t MAX_BODY_SIZE = 32;
static constexpr size_t TX_QUEUE_SIZE = 4;
class PioneerWT final : public climate::Climate, public uart::UARTDevice, public Component {
public:
void setup() override;
void loop() override;
void dump_config() override;
/// Turns the indoor unit's front display on or off.
void set_display_on(bool on) { this->send_setting_(ATTR_DISPLAY, on); }
/// Turns the beep that confirms each command on or off.
void set_beeper_on(bool on) { this->send_setting_(ATTR_BEEPER, on); }
#ifdef USE_SWITCH
SUB_SWITCH(display)
SUB_SWITCH(beeper)
#endif
protected:
climate::ClimateTraits traits() override;
void control(const climate::ClimateCall &call) override;
void handle_frame_(const uint8_t *frame, size_t len);
void handle_status_(const uint8_t *body, size_t len);
void write_frame_(uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1, uint8_t class_2,
const uint8_t *body, size_t len);
/// Queues a data frame that the AC must acknowledge; it is resent until it is.
void queue_command_(uint8_t msg_class, const uint8_t *body, size_t len, int8_t power = POWER_UNCHANGED);
void send_pending_();
/// Removes the command at the head of the queue.
void pop_command_();
/// Power once the queued commands are applied; skip_head leaves out a head about to be dropped.
bool wanted_power_(bool skip_head) const;
/// Queues a command that sets one on/off attribute.
void send_setting_(uint16_t attr, bool on);
void request_status_();
static constexpr int8_t POWER_UNCHANGED = -1;
struct PendingCommand {
uint8_t msg_class;
uint8_t seq;
uint8_t len;
// Power the command sets: 0, 1 or POWER_UNCHANGED
int8_t power;
std::array<uint8_t, MAX_BODY_SIZE> body;
};
uint32_t last_send_{0};
// Time of the last status report (counted once a full one has arrived), or of the last request for one
uint32_t last_status_{0};
uint32_t last_rx_{0};
PacketReader reader_;
StaticRingBuffer<PendingCommand, TX_QUEUE_SIZE> queue_;
// Send attempts of the command at the head of the queue
uint8_t attempts_{0};
uint8_t next_seq_{1};
// Power the AC last reported
bool power_{false};
// Power set by an acknowledged command, until the next power report: 0, 1 or POWER_UNCHANGED
int8_t acked_power_{POWER_UNCHANGED};
// Value of ATTR_MODE: 0 auto, 1 cool, 2 dry, 3 fan, 4 heat
uint8_t ac_mode_{0};
};
} // namespace esphome::pioneer_wt
@@ -0,0 +1,122 @@
#include "pioneer_wt_protocol.h"
#include <cstring>
#include "esphome/core/hal.h"
namespace esphome::pioneer_wt {
uint16_t frame_crc(const uint8_t *frame, size_t len) {
const uint16_t head = crc16be(frame, 8);
return crc16be(frame + HEADER_SIZE, len - HEADER_SIZE, head);
}
enum class AttrKind : uint8_t {
ATTR_KIND_UNKNOWN,
ATTR_KIND_ONE_BYTE,
ATTR_KIND_FOUR_BYTES,
// One count byte, then that many bytes
ATTR_KIND_COUNT_PREFIXED,
// Two length bytes, then that many bytes
ATTR_KIND_LENGTH_PREFIXED,
};
// The reader must know how every attribute is stored to step over the ones it does not use.
// The IDs are grouped by storage.
static constexpr uint16_t ONE_BYTE_IDS[] PROGMEM = {
0x0001, 0x0005, 0x000C, 0x000D, 0x000E, 0x0011, 0x0012, 0x0013, 0x0017, 0x001E, 0x0022, 0x0025, 0x0026, 0x0027,
0x002D, 0x0035, 0x005E, 0x0073, 0x0074, 0x00A4, 0x00C9, 0x00DF, 0x0148, 0x015E, 0x0173, 0x0224, 0x0225,
};
static constexpr uint16_t FOUR_BYTE_IDS[] PROGMEM = {
0x0002, 0x0003, 0x003D, 0x0041, 0x0042, 0x005C, 0x0060, 0x0064, 0x0065,
0x0072, 0x0095, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x0221, 0x0222, 0x0227,
};
static constexpr uint16_t COUNT_PREFIXED_IDS[] PROGMEM = {0x0038, 0x0039};
static constexpr uint16_t LENGTH_PREFIXED_IDS[] PROGMEM = {0x00FA, 0x00FB, 0x0147, 0x0223};
template<size_t N> static bool contains(const uint16_t (&ids)[N], uint16_t id) {
for (const uint16_t &entry : ids) {
if (progmem_read_uint16(&entry) == id)
return true;
}
return false;
}
static AttrKind attr_kind(uint16_t id) {
if (contains(ONE_BYTE_IDS, id))
return AttrKind::ATTR_KIND_ONE_BYTE;
if (contains(FOUR_BYTE_IDS, id))
return AttrKind::ATTR_KIND_FOUR_BYTES;
if (contains(COUNT_PREFIXED_IDS, id))
return AttrKind::ATTR_KIND_COUNT_PREFIXED;
if (contains(LENGTH_PREFIXED_IDS, id))
return AttrKind::ATTR_KIND_LENGTH_PREFIXED;
return AttrKind::ATTR_KIND_UNKNOWN;
}
bool AttributeReader::next() {
if (this->pos_ + 2 > this->len_)
return false;
const uint8_t *data = this->data_;
const uint16_t id = encode_uint16(data[this->pos_], data[this->pos_ + 1]);
size_t start = this->pos_ + 2;
size_t value_len;
const AttrKind kind = attr_kind(id);
switch (kind) {
case AttrKind::ATTR_KIND_ONE_BYTE:
value_len = 1;
break;
case AttrKind::ATTR_KIND_FOUR_BYTES:
value_len = 4;
break;
case AttrKind::ATTR_KIND_COUNT_PREFIXED:
if (start + 1 > this->len_)
return false;
value_len = data[start++];
break;
case AttrKind::ATTR_KIND_LENGTH_PREFIXED:
if (start + 2 > this->len_)
return false;
value_len = encode_uint16(data[start], data[start + 1]);
start += 2;
break;
default:
this->id_ = id;
this->unknown_ = true;
return false;
}
if (start + value_len > this->len_)
return false;
this->id_ = id;
const uint8_t *v = data + start;
if (kind == AttrKind::ATTR_KIND_ONE_BYTE) {
this->value_ = v[0];
} else if (kind == AttrKind::ATTR_KIND_FOUR_BYTES) {
this->value_ = encode_uint32(v[0], v[1], v[2], v[3]);
} else {
this->value_ = 0;
}
this->pos_ = start + value_len;
return true;
}
size_t build_frame(uint8_t *out, uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1,
uint8_t class_2, const uint8_t *body, size_t len) {
const size_t total = HEADER_SIZE + 2 + len;
out[0] = FRAME_START_1;
out[1] = FRAME_START_2;
out[2] = flags;
out[3] = type;
out[4] = seq;
out[5] = ack;
out[6] = 0x00;
out[LEN_POS] = total;
out[HEADER_SIZE] = class_1;
out[HEADER_SIZE + 1] = class_2;
if (len)
std::memcpy(out + HEADER_SIZE + 2, body, len);
put_be16(out + CRC_POS, frame_crc(out, total));
return total;
}
} // namespace esphome::pioneer_wt
@@ -0,0 +1,93 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
namespace esphome::pioneer_wt {
// Frame layout: A5 01 | flags | type | seq | ack | 00 | len | crc_hi crc_lo | class class | body
static constexpr size_t HEADER_SIZE = 10;
static constexpr uint8_t FRAME_START_1 = 0xA5;
static constexpr uint8_t FRAME_START_2 = 0x01;
// The length byte counts the whole frame.
static constexpr size_t LEN_POS = 7;
static constexpr size_t CRC_POS = 8;
static constexpr size_t MAX_FRAME_SIZE = 255;
static constexpr uint8_t FLAG_NO_ACK = 0x00;
static constexpr uint8_t FLAG_WANT_ACK = 0x01;
static constexpr uint8_t TYPE_DATA = 0x21;
static constexpr uint8_t TYPE_REPLY = 0x23;
static constexpr uint8_t CLASS_COMMAND = 0x0A;
static constexpr uint8_t CLASS_NETWORK = 0x0B;
static constexpr uint8_t CLASS_STATUS = 0x0C;
// First class byte of a reply
static constexpr uint8_t CLASS_REPLY = 0x80;
// Attribute IDs
static constexpr uint16_t ATTR_POWER = 0x0001;
static constexpr uint16_t ATTR_SETPOINT_C100 = 0x0002;
static constexpr uint16_t ATTR_INDOOR_TEMP_C100 = 0x0003;
static constexpr uint16_t ATTR_FAN_SPEED = 0x0005;
static constexpr uint16_t ATTR_SWING_VERTICAL = 0x0011;
static constexpr uint16_t ATTR_MODE = 0x0012;
static constexpr uint16_t ATTR_ECO = 0x0013;
static constexpr uint16_t ATTR_DISPLAY = 0x001E;
static constexpr uint16_t ATTR_BEEPER = 0x0025;
static constexpr uint16_t ATTR_FAN_AUTO = 0x0073;
static constexpr uint16_t ATTR_FAN_EXTRA_1 = 0x0224;
static constexpr uint16_t ATTR_FAN_EXTRA_2 = 0x0225;
static constexpr uint16_t ATTR_SETPOINT_F = 0x0227;
static constexpr uint8_t SWING_ON = 0x01;
static constexpr uint8_t SWING_OFF = 0x08;
/// CRC-16/XMODEM over a whole frame, skipping the two checksum bytes at offset 8.
uint16_t frame_crc(const uint8_t *frame, size_t len);
// A5 01, ..., whole-frame length at 7, CRC (2) at 8, body
using PacketReader =
LengthFrameReader<MAX_FRAME_SIZE,
FrameFormat<FrameHeader<FRAME_START_1, FRAME_START_2>,
FrameLengthU8<LengthField{.offset = LEN_POS}>, FrameMinLength<HEADER_SIZE>>>;
inline bool checksum_valid(const uint8_t *frame, size_t len) {
return frame_crc(frame, len) == encode_uint16(frame[CRC_POS], frame[CRC_POS + 1]);
}
/// Walks the attribute list in a status body. Stops at the first ID whose size is unknown.
class AttributeReader final {
public:
AttributeReader(const uint8_t *data, size_t len) : data_(data), len_(len) {}
/// Moves to the next attribute. Returns false at the end of the body or at an unknown ID.
bool next();
uint16_t id() const { return this->id_; }
uint32_t value() const { return this->value_; }
/// True when the walk stopped early on an ID of unknown size.
bool stopped_on_unknown() const { return this->unknown_; }
protected:
const uint8_t *data_;
size_t len_;
size_t pos_{0};
uint32_t value_{0};
uint16_t id_{0};
bool unknown_{false};
};
/// Builds a frame into out, which must hold HEADER_SIZE + 2 + len bytes. Returns the frame length.
size_t build_frame(uint8_t *out, uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1,
uint8_t class_2, const uint8_t *body, size_t len);
/// Writes a one-byte attribute (2-byte ID, then the value) at p. Returns the new end.
inline uint8_t *put_attr(uint8_t *p, uint16_t id, uint8_t value) {
p = put_be16(p, id);
*p++ = value;
return p;
}
} // namespace esphome::pioneer_wt
+37
View File
@@ -0,0 +1,37 @@
import esphome.codegen as cg
from esphome.components import switch
import esphome.config_validation as cv
from esphome.const import CONF_BEEPER, CONF_DISPLAY, ENTITY_CATEGORY_CONFIG
from esphome.types import ConfigType
from . import CONF_PIONEER_WT_ID
from .climate import PioneerWT
ICON_LED_ON = "mdi:led-on"
ICON_VOLUME_HIGH = "mdi:volume-high"
def _switch_schema(icon: str) -> cv.Schema:
return switch.switch_schema(
switch.ApplySwitch,
icon=icon,
entity_category=ENTITY_CATEGORY_CONFIG,
default_restore_mode="DISABLED",
)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(CONF_PIONEER_WT_ID): cv.use_id(PioneerWT),
cv.Optional(CONF_DISPLAY): _switch_schema(ICON_LED_ON),
cv.Optional(CONF_BEEPER): _switch_schema(ICON_VOLUME_HIGH),
}
)
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_PIONEER_WT_ID])
switches = switch.sub_switches(config, parent=hub)
# No publish: the switch state follows what the AC reports back.
await switches(CONF_DISPLAY, hub.set_display_switch, apply="set_display_on(state)")
await switches(CONF_BEEPER, hub.set_beeper_switch, apply="set_beeper_on(state)")
+43 -86
View File
@@ -7,9 +7,6 @@ namespace esphome::pmsx003 {
ESPHOME_LOG_TAG(TAG, "pmsx003");
static const uint8_t START_CHARACTER_1 = 0x42;
static const uint8_t START_CHARACTER_2 = 0x4D;
static const uint16_t STABILISING_MS = 30000; // time taken for the sensor to become stable after power on in ms
static const uint16_t CMD_MEASUREMENT_MODE_PASSIVE =
@@ -95,82 +92,42 @@ void PMSX003Component::loop() {
}
}
if (now - this->last_transmission_ >= 500) {
// last transmission too long ago. Reset RX index.
this->data_index_ = 0;
}
const size_t avail = this->available();
if (avail == 0)
return;
this->last_transmission_ = now;
this->read_available(
[this, now](uint8_t byte) {
this->data_[this->data_index_] = byte;
auto check = this->check_byte_();
if (!check.has_value()) {
if (this->update_interval_ > STABILISING_MS || now - this->last_update_ >= this->update_interval_) {
this->parse_data_();
this->last_update_ = now;
}
this->data_index_ = 0;
} else if (!*check) {
// wrong data
this->data_index_ = 0;
} else {
// next byte
this->data_index_++;
}
},
avail);
auto handle = [this, now](const uint8_t *frame, size_t len) {
if (!this->check_frame_(frame, len))
return false;
if (this->update_interval_ > STABILISING_MS || now - this->last_update_ >= this->update_interval_) {
this->parse_data_(frame);
this->last_update_ = now;
}
return true;
};
this->read_frames(this->reader_, handle, now, this->last_transmission_);
}
optional<bool> PMSX003Component::check_byte_() {
const uint8_t index = this->data_index_;
const uint8_t byte = this->data_[index];
bool frame_fits(const uint8_t *buf) {
const size_t len = PayloadLength::get(buf);
if (len <= MAX_FRAME_SIZE)
return true;
ESP_LOGW(TAG, "Payload length %u doesn't match. Are you using the correct PMSX003 type?",
static_cast<unsigned>(len - PayloadLength::KNOWN_AT));
return false;
}
if (index == 0 || index == 1) {
const uint8_t start_char = index == 0 ? START_CHARACTER_1 : START_CHARACTER_2;
if (byte == start_char) {
return true;
}
ESP_LOGW(TAG, "Start character %u mismatch: 0x%02X != 0x%02X", index + 1, byte, start_char);
bool PMSX003Component::check_frame_(const uint8_t *frame, size_t total_size) {
const uint16_t payload_length = total_size - PayloadLength::KNOWN_AT;
if (!this->check_payload_length_(payload_length)) {
ESP_LOGW(TAG, "Payload length %u doesn't match. Are you using the correct PMSX003 type?", payload_length);
return false;
}
if (index == 2) {
return true;
}
const uint16_t payload_length = this->get_16_bit_uint_(2);
if (index == 3) {
if (this->check_payload_length_(payload_length)) {
return true;
} else {
ESP_LOGW(TAG, "Payload length %u doesn't match. Are you using the correct PMSX003 type?", payload_length);
return false;
}
}
// start (16bit) + length (16bit) + DATA (payload_length - 16bit) + checksum (16bit)
const uint16_t total_size = 4 + payload_length;
if (index < total_size - 1) {
return true;
}
// checksum is without checksum bytes
const uint16_t checksum = sum16_bytes(this->data_, total_size - 2);
const uint16_t check = this->get_16_bit_uint_(total_size - 2);
const uint16_t checksum = sum16_bytes(frame, total_size - 2);
const uint16_t check = encode_uint16(frame[total_size - 2], frame[total_size - 1]);
if (checksum != check) {
ESP_LOGW(TAG, "PMSX003 checksum mismatch! 0x%02X != 0x%02X", checksum, check);
return false;
}
return {};
return true;
}
bool PMSX003Component::check_payload_length_(uint16_t payload_length) {
@@ -214,11 +171,11 @@ void PMSX003Component::send_command_(Command cmd, uint16_t data) {
}
}
void PMSX003Component::parse_data_() {
void PMSX003Component::parse_data_(const uint8_t *frame) {
// PM mass concentrations
const uint16_t pm_1_0_std_concentration = this->get_16_bit_uint_(4);
const uint16_t pm_2_5_std_concentration = this->get_16_bit_uint_(6);
const uint16_t pm_10_0_std_concentration = this->get_16_bit_uint_(8);
const uint16_t pm_1_0_std_concentration = encode_value<uint16_t>(frame + 4);
const uint16_t pm_2_5_std_concentration = encode_value<uint16_t>(frame + 6);
const uint16_t pm_10_0_std_concentration = encode_value<uint16_t>(frame + 8);
PUBLISH_STATE(this->pm_1_0_std_sensor_, pm_1_0_std_concentration);
PUBLISH_STATE(this->pm_2_5_std_sensor_, pm_2_5_std_concentration);
@@ -234,9 +191,9 @@ void PMSX003Component::parse_data_() {
const uint8_t pc_offset = is_luftmy ? 10 : 16;
if (!is_luftmy) {
const uint16_t pm_1_0_concentration = this->get_16_bit_uint_(10);
const uint16_t pm_2_5_concentration = this->get_16_bit_uint_(12);
const uint16_t pm_10_0_concentration = this->get_16_bit_uint_(14);
const uint16_t pm_1_0_concentration = encode_value<uint16_t>(frame + 10);
const uint16_t pm_2_5_concentration = encode_value<uint16_t>(frame + 12);
const uint16_t pm_10_0_concentration = encode_value<uint16_t>(frame + 14);
ESP_LOGD(TAG, "Got PM1.0 Concentration: %u µg/m³, PM2.5 Concentration %u µg/m³, PM10.0 Concentration: %u µg/m³",
pm_1_0_concentration, pm_2_5_concentration, pm_10_0_concentration);
@@ -247,10 +204,10 @@ void PMSX003Component::parse_data_() {
}
// Particle counts at pc_offset: >0.3, >0.5, >1.0, >2.5µm
const uint16_t pm_particles_03um = this->get_16_bit_uint_(pc_offset);
const uint16_t pm_particles_05um = this->get_16_bit_uint_(pc_offset + 2);
const uint16_t pm_particles_10um = this->get_16_bit_uint_(pc_offset + 4);
const uint16_t pm_particles_25um = this->get_16_bit_uint_(pc_offset + 6);
const uint16_t pm_particles_03um = encode_value<uint16_t>(frame + pc_offset);
const uint16_t pm_particles_05um = encode_value<uint16_t>(frame + pc_offset + 2);
const uint16_t pm_particles_10um = encode_value<uint16_t>(frame + pc_offset + 4);
const uint16_t pm_particles_25um = encode_value<uint16_t>(frame + pc_offset + 6);
PUBLISH_STATE(this->pm_particles_03um_sensor_, pm_particles_03um);
PUBLISH_STATE(this->pm_particles_05um_sensor_, pm_particles_05um);
@@ -263,8 +220,8 @@ void PMSX003Component::parse_data_() {
// PMS5003T uses pc_offset+8 and pc_offset+10 for temperature/humidity, not particle counts
if (this->type_ != Type::PMS5003T) {
const uint16_t pm_particles_50um = this->get_16_bit_uint_(pc_offset + 8);
const uint16_t pm_particles_100um = this->get_16_bit_uint_(pc_offset + 10);
const uint16_t pm_particles_50um = encode_value<uint16_t>(frame + pc_offset + 8);
const uint16_t pm_particles_100um = encode_value<uint16_t>(frame + pc_offset + 10);
ESP_LOGD(TAG, "Got PM5.0 Particles: %u Count/0.1L, PM10.0 Particles: %u Count/0.1L", pm_particles_50um,
pm_particles_100um);
@@ -275,7 +232,7 @@ void PMSX003Component::parse_data_() {
// Formaldehyde
if (this->type_ == Type::PMS5003S || this->type_ == Type::PMS5003ST) {
const uint16_t formaldehyde = this->get_16_bit_uint_(28);
const uint16_t formaldehyde = encode_value<uint16_t>(frame + 28);
ESP_LOGD(TAG, "Got Formaldehyde: %u µg/m^3", formaldehyde);
@@ -286,8 +243,8 @@ void PMSX003Component::parse_data_() {
if (this->type_ == Type::PMS5003T || this->type_ == Type::PMS5003ST) {
const uint8_t temperature_offset = (this->type_ == Type::PMS5003T) ? 24 : 30;
const float temperature = static_cast<int16_t>(this->get_16_bit_uint_(temperature_offset)) / 10.0f;
const float humidity = this->get_16_bit_uint_(temperature_offset + 2) / 10.0f;
const float temperature = encode_value<int16_t>(frame + temperature_offset) / 10.0f;
const float humidity = encode_value<uint16_t>(frame + temperature_offset + 2) / 10.0f;
ESP_LOGD(TAG, "Got Temperature: %.1f°C, Humidity: %.1f%%", temperature, humidity);
@@ -298,8 +255,8 @@ void PMSX003Component::parse_data_() {
// Firmware Version and Error Code
if (this->type_ == Type::PMS1003 || this->type_ == Type::PMS5003ST || this->type_ == Type::PMS9003M) {
const uint8_t firmware_error_code_offset = (this->type_ == Type::PMS5003ST) ? 36 : 28;
const uint8_t firmware_version = this->data_[firmware_error_code_offset];
const uint8_t error_code = this->data_[firmware_error_code_offset + 1];
const uint8_t firmware_version = frame[firmware_error_code_offset];
const uint8_t error_code = frame[firmware_error_code_offset + 1];
ESP_LOGD(TAG, "Got Firmware Version: 0x%02X, Error Code: 0x%02X", firmware_version, error_code);
}
+15 -7
View File
@@ -1,12 +1,24 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
namespace esphome::pmsx003 {
static constexpr uint8_t START_CHARACTER_1 = 0x42;
static constexpr uint8_t START_CHARACTER_2 = 0x4D;
// PMS5003ST: 36 byte payload after the 2 start and 2 length bytes
static constexpr uint8_t MAX_FRAME_SIZE = 40;
// 42 4D, payload length (2, BE), payload ending in its checksum (2)
using PayloadLength = PayloadLengthU16BE<LengthField{.offset = 2}>;
/// False, with the wrong-type warning, for a frame longer than any supported type sends
bool frame_fits(const uint8_t *buf);
using PmsFrame = FrameFormat<FrameHeader<START_CHARACTER_1, START_CHARACTER_2>,
CheckedLength<PayloadLength, PayloadLength::KNOWN_AT, frame_fits>>;
enum class Type : uint8_t {
PMS1003 = 0,
PMS3003,
@@ -67,19 +79,15 @@ class PMSX003Component final : public uart::UARTDevice, public Component {
SUB_SENSOR(humidity)
protected:
optional<bool> check_byte_();
void parse_data_();
bool check_frame_(const uint8_t *frame, size_t total_size);
void parse_data_(const uint8_t *frame);
bool check_payload_length_(uint16_t payload_length);
void send_command_(Command cmd, uint16_t data);
uint16_t get_16_bit_uint_(uint8_t start_index) const {
return encode_uint16(this->data_[start_index], this->data_[start_index + 1]);
}
Type type_;
State state_{State::IDLE};
bool initialised_{false};
uint8_t data_[64];
uint8_t data_index_{0};
LengthFrameReader<MAX_FRAME_SIZE, PmsFrame> reader_;
uint32_t fan_on_time_{0};
uint32_t last_update_{0};
uint32_t last_transmission_{0};
+11 -13
View File
@@ -10,12 +10,10 @@ CODEOWNERS = ["@kahrendt"]
qwiic_pir_ns = cg.esphome_ns.namespace("qwiic_pir")
DebounceMode = qwiic_pir_ns.enum("DebounceMode")
DEBOUNCE_MODE_OPTIONS = {
"RAW": DebounceMode.RAW_DEBOUNCE_MODE,
"NATIVE": DebounceMode.NATIVE_DEBOUNCE_MODE,
"HYBRID": DebounceMode.HYBRID_DEBOUNCE_MODE,
}
DebounceMode = qwiic_pir_ns.enum("DebounceMode", is_class=True)
DEBOUNCE_MODE_OPTIONS = DebounceMode.options(
"RAW", "NATIVE", "HYBRID", prefix="DEBOUNCE_MODE_"
)
CONF_DEBOUNCE_MODE = "debounce_mode"
@@ -47,12 +45,12 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
# Without a debounce time the device is set to 1 ms; NATIVE is the only mode that takes one
debounce = config.get(CONF_DEBOUNCE)
var = await binary_sensor.new_binary_sensor(
config,
config[CONF_DEBOUNCE_MODE],
1 if debounce is None else debounce.total_milliseconds,
)
await cg.register_component(var, config)
await i2c.register_i2c_device(var, config)
if debounce_time_setting := config.get(CONF_DEBOUNCE):
cg.add(var.set_debounce_time(debounce_time_setting.total_milliseconds))
else:
cg.add(var.set_debounce_time(1)) # default to 1 ms if not configured
cg.add(var.set_debounce_mode(config[CONF_DEBOUNCE_MODE]))
+51 -65
View File
@@ -1,99 +1,85 @@
#include "qwiic_pir.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
namespace esphome::qwiic_pir {
ESPHOME_LOG_TAG(TAG, "qwiic_pir");
static constexpr uint8_t REG_CHIP_ID = 0x00;
static constexpr uint8_t REG_EVENT_STATUS = 0x03;
static constexpr uint8_t REG_DEBOUNCE_TIME = 0x05; // milliseconds, 16 bits little endian
static constexpr uint8_t DEVICE_ID = 0x72;
// REG_EVENT_STATUS bits
static constexpr uint8_t EVENT_RAW_READING = 0x01; // raw state of the PIR sensor
static constexpr uint8_t EVENT_AVAILABLE = 0x02; // a debounced object was detected or removed
static constexpr uint8_t EVENT_OBJECT_REMOVED = 0x04; // a debounced object is no longer detected
static constexpr uint8_t EVENT_OBJECT_DETECTED = 0x08; // a debounced object has been detected
// Indexed by DebounceMode
PROGMEM_STRING_TABLE(DebounceModeStrings, "RAW", "NATIVE", "HYBRID");
void QwiicPIRComponent::setup() {
if (!this->check_chip_id(this, QWIIC_PIR_CHIP_ID, QWIIC_PIR_DEVICE_ID))
if (!this->check_chip_id(this, REG_CHIP_ID, DEVICE_ID))
return;
if (!this->setup_check(this->write_byte_16(QWIIC_PIR_DEBOUNCE_TIME, this->debounce_time_),
if (!this->setup_check(this->write_byte_16_le(REG_DEBOUNCE_TIME, this->debounce_time_),
LOG_STR("Failed to configure debounce time")))
return;
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
// Publish the starting raw state of the PIR sensor
// If NATIVE mode, the binary_sensor state would be unknown until a motion event
if (!this->setup_check(this->read_byte(QWIIC_PIR_EVENT_STATUS, &this->event_register_.reg),
LOG_STR("Failed to read initial state")))
if (this->debounce_mode_ == DebounceMode::DEBOUNCE_MODE_NATIVE) {
// NATIVE only publishes on motion events, so start from the raw state
uint8_t event;
if (!this->setup_check(this->read_byte(REG_EVENT_STATUS, &event), LOG_STR("Failed to read initial state")))
return;
this->publish_state(this->event_register_.raw_reading);
this->publish_state((event & EVENT_RAW_READING) != 0);
}
}
void QwiicPIRComponent::loop() {
// Read Event Register
if (!this->read_byte(QWIIC_PIR_EVENT_STATUS, &this->event_register_.reg)) {
ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
uint8_t event;
if (!this->status_comm_check(this->read_byte(REG_EVENT_STATUS, &event)))
return;
switch (this->debounce_mode_) {
case DebounceMode::DEBOUNCE_MODE_HYBRID:
// The device debounces for 1 ms and ESPHome filters do the rest; any event means motion since the last loop
this->publish_state((event & (EVENT_RAW_READING | EVENT_AVAILABLE)) != 0);
break;
case DebounceMode::DEBOUNCE_MODE_NATIVE:
// The device's own debounce, as in SparkFun's Example2_PrintPIRStatus; it often misses objects being removed
if (event & EVENT_AVAILABLE) {
if (event & EVENT_OBJECT_DETECTED)
this->publish_state(true);
if (event & EVENT_OBJECT_REMOVED)
this->publish_state(false);
}
break;
case DebounceMode::DEBOUNCE_MODE_RAW:
// Can miss a very short detection when the loop is slow
this->publish_state((event & EVENT_RAW_READING) != 0);
break;
}
if (this->debounce_mode_ == HYBRID_DEBOUNCE_MODE) {
// Use a combination of the raw sensor reading and the device's event detection to determine state
// - The device is hardcoded to use a debounce time of 1 ms in this mode
// - Any event, even if it is object_removed, implies motion was active since the last loop, so publish true
// - Use ESPHome's built-in filters for debouncing
this->publish_state(this->event_register_.raw_reading || this->event_register_.event_available);
if (this->event_register_.event_available) {
this->clear_events_();
}
} else if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
// Uses the device's firmware to debounce the signal
// - Follows the logic of SparkFun's example implementation:
// https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library/blob/master/examples/Example2_PrintPIRStatus/Example2_PrintPIRStatus.ino
// (accessed July 2023)
// - Is unreliable at detecting an object being removed, especially at debounce rates even slightly large
if (this->event_register_.event_available) {
// If an object is detected, publish true
if (this->event_register_.object_detected)
this->publish_state(true);
// If an object has been removed, publish false
if (this->event_register_.object_removed)
this->publish_state(false);
this->clear_events_();
}
} else if (this->debounce_mode_ == RAW_DEBOUNCE_MODE) {
// Publishes the raw PIR sensor reading with no further logic
// - May miss a very short motion detection if the ESP's loop time is slow
this->publish_state(this->event_register_.raw_reading);
}
// HYBRID and NATIVE clear a handled event; the last bus step of the poll decides the warning
bool ok = true;
if (this->debounce_mode_ != DebounceMode::DEBOUNCE_MODE_RAW && (event & EVENT_AVAILABLE))
ok = this->write_byte(REG_EVENT_STATUS, 0x00);
this->status_comm_result(ok);
}
void QwiicPIRComponent::dump_config() {
static const char *const RAW = "RAW";
static const char *const NATIVE = "NATIVE";
static const char *const HYBRID = "HYBRID";
const char *debounce_mode_str = RAW;
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
debounce_mode_str = NATIVE;
} else if (this->debounce_mode_ == HYBRID_DEBOUNCE_MODE) {
debounce_mode_str = HYBRID;
}
ESP_LOGCONFIG(TAG,
"Qwiic PIR:\n"
" Debounce Mode: %s",
debounce_mode_str);
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
LOG_STR_ARG(DebounceModeStrings::get_log_str(static_cast<uint8_t>(this->debounce_mode_), 0)));
if (this->debounce_mode_ == DebounceMode::DEBOUNCE_MODE_NATIVE) {
ESP_LOGCONFIG(TAG, " Debounce Time: %ums", this->debounce_time_);
}
LOG_I2C_DEVICE(this);
LOG_BINARY_SENSOR(" ", "Binary Sensor", this);
}
void QwiicPIRComponent::clear_events_() {
// Clear event status register
if (!this->write_byte(QWIIC_PIR_EVENT_STATUS, 0x00)) {
ESP_LOGW(TAG, "Failed to clear events");
}
}
} // namespace esphome::qwiic_pir
+11 -35
View File
@@ -2,8 +2,8 @@
* Adds support for Qwiic PIR motion sensors that communicate over an I2C bus.
* These sensors use Sharp PIR motion sensors to detect motion. A firmware running on an ATTiny84 translates the digital
* output to I2C communications.
* ATTiny84 firmware: https://github.com/sparkfun/Qwiic_PIR (accessed July 2023)
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library (accessed July 2023)
* ATTiny84 firmware: https://github.com/sparkfun/Qwiic_PIR
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library
*/
#pragma once
@@ -14,48 +14,24 @@
namespace esphome::qwiic_pir {
// Qwiic PIR I2C Register Addresses
enum {
QWIIC_PIR_CHIP_ID = 0x00,
QWIIC_PIR_EVENT_STATUS = 0x03,
QWIIC_PIR_DEBOUNCE_TIME = 0x05, // uint16_t debounce time in milliseconds
enum class DebounceMode : uint8_t {
DEBOUNCE_MODE_RAW,
DEBOUNCE_MODE_NATIVE,
DEBOUNCE_MODE_HYBRID,
};
enum DebounceMode {
RAW_DEBOUNCE_MODE,
NATIVE_DEBOUNCE_MODE,
HYBRID_DEBOUNCE_MODE,
};
static const uint8_t QWIIC_PIR_DEVICE_ID = 0x72;
class QwiicPIRComponent final : public Component, public i2c::I2CDevice, public binary_sensor::BinarySensor {
public:
QwiicPIRComponent(DebounceMode debounce_mode, uint16_t debounce_time)
: debounce_time_(debounce_time), debounce_mode_(debounce_mode) {}
void setup() override;
void loop() override;
void dump_config() override;
void set_debounce_time(uint16_t debounce_time) { this->debounce_time_ = debounce_time; }
void set_debounce_mode(DebounceMode mode) { this->debounce_mode_ = mode; }
protected:
uint16_t debounce_time_{};
DebounceMode debounce_mode_{};
union {
struct {
bool raw_reading : 1; // raw state of PIR sensor
bool event_available : 1; // a debounced object has been detected or removed
bool object_removed : 1; // a debounced object is no longer detected
bool object_detected : 1; // a debounced object has been detected
bool : 4;
};
uint8_t reg;
} event_register_ = {.reg = 0};
void clear_events_();
uint16_t debounce_time_;
DebounceMode debounce_mode_;
};
} // namespace esphome::qwiic_pir
-8
View File
@@ -2,10 +2,6 @@
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#ifdef USE_ESP8266
#include <Wire.h>
#endif
namespace esphome::scd30 {
ESPHOME_LOG_TAG(TAG, "scd30");
@@ -27,10 +23,6 @@ static const uint16_t SCD30_CMD_TEMPERATURE_OFFSET = 0x5403;
static const uint16_t SCD30_CMD_SOFT_RESET = 0xD304;
void SCD30Component::setup() {
#ifdef USE_ESP8266
Wire.setClockStretchLimit(150000);
#endif
/// Firmware version identification
uint16_t raw_firmware_version[3];
if (!this->setup_check(this->get_register(SCD30_CMD_GET_FIRMWARE_VERSION, raw_firmware_version, 3),
@@ -1,6 +1,7 @@
#include "seeed_mr24hpc1.h"
#include "esphome/core/helpers.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
@@ -82,17 +83,12 @@ void MR24HPC1Component::setup() {
this->poll_time_base_func_check_ = false;
this->check_dev_inf_sign_ = true;
this->sg_start_query_data_ = STANDARD_FUNCTION_QUERY_PRODUCT_MODE;
this->sg_data_len_ = 0;
this->sg_frame_len_ = 0;
this->sg_recv_data_state_ = FRAME_IDLE;
this->s_output_info_switch_flag_ = OUTPUT_SWITCH_INIT;
memset(this->c_product_mode_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->c_product_id_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->c_firmware_version_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->c_hardware_model_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->sg_frame_prase_buf_, 0, FRAME_BUF_MAX_SIZE);
memset(this->sg_frame_buf_, 0, FRAME_BUF_MAX_SIZE);
// The module locks up when queried during its own boot, so hold all TX for a second
this->set_timeout(STARTUP_DELAY_MS, [this]() {
@@ -109,9 +105,29 @@ void MR24HPC1Component::update_() {
this->poll_time_base_func_check_ = true; // Query the base functionality information at regular intervals
}
// The reader keeps frames at MIN_FRAME_SIZE or more, so the three trailing bytes can always be left out
static uint8_t get_frame_crc_sum(const uint8_t *data, size_t len) { return sum_bytes(data, len - 3); }
// Footer and sum
static bool frame_valid(const uint8_t *data, size_t len) {
if (data[len - 2] != FRAME_TAIL1_VALUE || data[len - 1] != FRAME_TAIL2_VALUE)
return false;
if (data[len - 3] != get_frame_crc_sum(data, len)) {
ESP_LOGD(TAG, "frame check failure!");
return false;
}
return true;
}
// main loop
void MR24HPC1Component::loop() {
this->read_available([this](uint8_t b) { this->r24_split_data_frame_(b); });
auto handler = [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
return false;
this->r24_parse_data_frame_(frame, len);
return true;
};
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
if ((this->s_output_info_switch_flag_ == OUTPUT_SWITCH_OFF) &&
(this->sg_start_query_data_ > CUSTOM_FUNCTION_QUERY_TIME_OF_ENTER_UNMANNED) && (!this->check_dev_inf_sign_)) {
@@ -246,109 +262,8 @@ void MR24HPC1Component::loop() {
}
}
// Frames are at least 10 bytes, so the three trailing bytes can always be left out
static uint8_t get_frame_crc_sum(const uint8_t *data, size_t len) { return sum_bytes(data, len - 3); }
// Check that the check digit is correct
static int get_frame_check_status(const uint8_t *data, size_t len) {
uint8_t crc_sum = get_frame_crc_sum(data, len);
uint8_t verified = data[len - 3];
return (verified == crc_sum) ? 1 : 0;
}
// split data frame
void MR24HPC1Component::r24_split_data_frame_(uint8_t value) {
switch (this->sg_recv_data_state_) {
case FRAME_IDLE: // starting value
if (FRAME_HEADER1_VALUE == value) {
this->sg_recv_data_state_ = FRAME_HEADER2;
}
break;
case FRAME_HEADER2:
if (FRAME_HEADER2_VALUE == value) {
this->sg_frame_buf_[0] = FRAME_HEADER1_VALUE;
this->sg_frame_buf_[1] = FRAME_HEADER2_VALUE;
this->sg_recv_data_state_ = FRAME_CTL_WORD;
} else {
this->sg_recv_data_state_ = FRAME_IDLE;
ESP_LOGD(TAG, "FRAME_IDLE ERROR value:%x", value);
}
break;
case FRAME_CTL_WORD:
this->sg_frame_buf_[2] = value;
this->sg_recv_data_state_ = FRAME_CMD_WORD;
break;
case FRAME_CMD_WORD:
this->sg_frame_buf_[3] = value;
this->sg_recv_data_state_ = FRAME_DATA_LEN_H;
break;
case FRAME_DATA_LEN_H:
if (value == 0) {
this->sg_frame_buf_[4] = value;
this->sg_recv_data_state_ = FRAME_DATA_LEN_L;
} else {
this->sg_recv_data_state_ = FRAME_IDLE;
ESP_LOGD(TAG, "FRAME_DATA_LEN_H ERROR value:%x", value);
}
break;
case FRAME_DATA_LEN_L:
this->sg_data_len_ = value;
if (this->sg_data_len_ == 0 || this->sg_data_len_ > 32) {
ESP_LOGD(TAG, "len=%d, FRAME_DATA_LEN_L ERROR value:%x", this->sg_data_len_, value);
this->sg_data_len_ = 0;
this->sg_recv_data_state_ = FRAME_IDLE;
} else {
this->sg_frame_buf_[5] = value;
this->sg_frame_len_ = 6;
this->sg_recv_data_state_ = FRAME_DATA_BYTES;
}
break;
case FRAME_DATA_BYTES:
this->sg_frame_buf_[this->sg_frame_len_++] = value;
if (--this->sg_data_len_ == 0) {
this->sg_recv_data_state_ = FRAME_DATA_CRC;
}
break;
case FRAME_DATA_CRC:
this->sg_frame_buf_[this->sg_frame_len_++] = value;
this->sg_recv_data_state_ = FRAME_TAIL1;
break;
case FRAME_TAIL1:
if (FRAME_TAIL1_VALUE == value) {
this->sg_recv_data_state_ = FRAME_TAIL2;
} else {
this->sg_recv_data_state_ = FRAME_IDLE;
this->sg_frame_len_ = 0;
this->sg_data_len_ = 0;
ESP_LOGD(TAG, "FRAME_TAIL1 ERROR value:%x", value);
}
break;
case FRAME_TAIL2:
if (FRAME_TAIL2_VALUE == value) {
this->sg_frame_buf_[this->sg_frame_len_++] = FRAME_TAIL1_VALUE;
this->sg_frame_buf_[this->sg_frame_len_++] = FRAME_TAIL2_VALUE;
memcpy(this->sg_frame_prase_buf_, this->sg_frame_buf_, this->sg_frame_len_);
if (get_frame_check_status(this->sg_frame_prase_buf_, this->sg_frame_len_)) {
this->r24_parse_data_frame_(this->sg_frame_prase_buf_, this->sg_frame_len_);
} else {
ESP_LOGD(TAG, "frame check failure!");
}
} else {
ESP_LOGD(TAG, "FRAME_TAIL2 ERROR value:%x", value);
}
memset(this->sg_frame_prase_buf_, 0, FRAME_BUF_MAX_SIZE);
memset(this->sg_frame_buf_, 0, FRAME_BUF_MAX_SIZE);
this->sg_frame_len_ = 0;
this->sg_data_len_ = 0;
this->sg_recv_data_state_ = FRAME_IDLE;
break;
default:
this->sg_recv_data_state_ = FRAME_IDLE;
}
}
// Parses data frames related to product information
void MR24HPC1Component::r24_frame_parse_product_information_(uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_product_information_(const uint8_t *data) {
#ifdef USE_TEXT_SENSOR
uint16_t product_len = encode_uint16(data[FRAME_COMMAND_WORD_INDEX + 1], data[FRAME_COMMAND_WORD_INDEX + 2]);
if (data[FRAME_COMMAND_WORD_INDEX] == COMMAND_PRODUCT_MODE) {
@@ -389,7 +304,7 @@ void MR24HPC1Component::r24_frame_parse_product_information_(uint8_t *data) {
}
// Parsing the underlying open parameters
void MR24HPC1Component::r24_frame_parse_open_underlying_information_(uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_open_underlying_information_(const uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
case 0x00:
case 0x80:
@@ -482,7 +397,7 @@ void MR24HPC1Component::r24_frame_parse_open_underlying_information_(uint8_t *da
}
}
void MR24HPC1Component::r24_parse_data_frame_(uint8_t *data, uint8_t len) {
void MR24HPC1Component::r24_parse_data_frame_(const uint8_t *data, uint8_t len) {
switch (data[FRAME_CONTROL_WORD_INDEX]) {
case 0x01: {
if (data[FRAME_COMMAND_WORD_INDEX] == 0x02) {
@@ -512,7 +427,7 @@ void MR24HPC1Component::r24_parse_data_frame_(uint8_t *data, uint8_t len) {
}
}
void MR24HPC1Component::r24_frame_parse_work_status_(uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_work_status_(const uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
case 0x01:
case 0x81:
@@ -569,7 +484,7 @@ void MR24HPC1Component::r24_frame_parse_work_status_(uint8_t *data) {
}
}
void MR24HPC1Component::r24_frame_parse_human_information_(uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_human_information_(const uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
#ifdef USE_BINARY_SENSOR
case 0x01:
@@ -24,6 +24,7 @@
#endif
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "seeed_mr24hpc1_constants.h"
@@ -32,19 +33,6 @@
namespace esphome::seeed_mr24hpc1 {
enum FrameState {
FRAME_IDLE,
FRAME_HEADER2,
FRAME_CTL_WORD,
FRAME_CMD_WORD,
FRAME_DATA_LEN_H,
FRAME_DATA_LEN_L,
FRAME_DATA_BYTES,
FRAME_DATA_CRC,
FRAME_TAIL1,
FRAME_TAIL2,
};
enum PollingState {
STANDARD_FUNCTION_QUERY_PRODUCT_MODE = 0,
STANDARD_FUNCTION_QUERY_PRODUCT_ID,
@@ -134,24 +122,24 @@ class MR24HPC1Component final : public Component,
char c_product_id_[PRODUCT_BUF_MAX_SIZE + 1];
char c_hardware_model_[PRODUCT_BUF_MAX_SIZE + 1];
char c_firmware_version_[PRODUCT_BUF_MAX_SIZE + 1];
uint8_t s_output_info_switch_flag_;
uint8_t sg_recv_data_state_;
uint8_t sg_frame_len_;
uint8_t sg_data_len_;
uint8_t sg_frame_buf_[FRAME_BUF_MAX_SIZE];
uint8_t sg_frame_prase_buf_[FRAME_BUF_MAX_SIZE];
uint32_t last_rx_{0};
// 53 59, control, command, payload length (2, BE), payload (at least 1), sum, 54 43
LengthFrameReader<FRAME_BUF_MAX_SIZE, FrameFormat<FrameHeader<FRAME_HEADER1_VALUE, FRAME_HEADER2_VALUE>,
PayloadLengthU16BE<LengthField{.offset = 4, .trailer = 3}>,
FrameMinLength<MIN_FRAME_SIZE>>>
reader_;
int sg_start_query_data_;
uint8_t s_output_info_switch_flag_;
bool check_dev_inf_sign_;
bool poll_time_base_func_check_;
bool module_ready_{false};
void update_();
void r24_split_data_frame_(uint8_t value);
void r24_parse_data_frame_(uint8_t *data, uint8_t len);
void r24_frame_parse_open_underlying_information_(uint8_t *data);
void r24_frame_parse_work_status_(uint8_t *data);
void r24_frame_parse_product_information_(uint8_t *data);
void r24_frame_parse_human_information_(uint8_t *data);
void r24_parse_data_frame_(const uint8_t *data, uint8_t len);
void r24_frame_parse_open_underlying_information_(const uint8_t *data);
void r24_frame_parse_work_status_(const uint8_t *data);
void r24_frame_parse_product_information_(const uint8_t *data);
void r24_frame_parse_human_information_(const uint8_t *data);
void send_query_(const uint8_t *query, size_t string_length);
public:
@@ -4,7 +4,9 @@
namespace esphome::seeed_mr24hpc1 {
static const uint8_t FRAME_BUF_MAX_SIZE = 128;
// 6 header bytes, up to 32 data bytes, sum and 2 footer bytes
static constexpr uint8_t FRAME_BUF_MAX_SIZE = 41;
static constexpr uint8_t MIN_FRAME_SIZE = 10; // header (2), control, command, length (2), 1 data byte, sum, footer (2)
static const uint8_t PRODUCT_BUF_MAX_SIZE = 32;
static const uint8_t FRAME_CONTROL_WORD_INDEX = 2;
@@ -1,5 +1,6 @@
#include "seeed_mr60bha2.h"
#include "esphome/core/helpers.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include <cinttypes>
@@ -27,16 +28,6 @@ void MR60BHA2Component::dump_config() {
#endif
}
// main loop
void MR60BHA2Component::loop() {
this->read_available([this](uint8_t b) {
this->rx_message_.push_back(b);
if (!this->validate_message_()) {
this->rx_message_.clear();
}
});
}
/**
* @brief Validate the checksum of a byte array.
*
@@ -52,75 +43,57 @@ static bool validate_checksum(const uint8_t *data, size_t len, uint8_t expected_
return static_cast<uint8_t>(~xor_bytes(data, len)) == expected_checksum;
}
bool MR60BHA2Component::validate_message_() {
size_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
static bool is_known_type(uint16_t type) {
return type == BREATH_RATE_TYPE_BUFFER || type == HEART_RATE_TYPE_BUFFER || type == DISTANCE_TYPE_BUFFER ||
type == PEOPLE_EXIST_TYPE_BUFFER || type == PRINT_CLOUD_BUFFER;
}
if (at == 0) {
return new_byte == FRAME_HEADER_BUFFER;
// An unknown type or a bad header checksum gives no length, so the header is dropped at once
size_t TinyFrameLength::get(const uint8_t *buf) {
if (!is_known_type(encode_uint16(buf[5], buf[6])))
return 0;
constexpr size_t cksum_pos = TinyFrameLength::KNOWN_AT - 1;
if (!validate_checksum(buf, cksum_pos, buf[cksum_pos])) {
ESP_LOGE(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", buf[cksum_pos]);
ESP_LOGV_HEX(TAG, buf, TinyFrameLength::KNOWN_AT, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
return 0;
}
return encode_uint16(buf[3], buf[4]) + FRAME_OVERHEAD;
}
if (at <= 2) {
return true;
}
uint16_t frame_id = encode_uint16(data[1], data[2]);
if (at <= 4) {
return true;
}
uint16_t length = encode_uint16(data[3], data[4]);
if (at <= 6) {
return true;
}
uint16_t frame_type = encode_uint16(data[5], data[6]);
if (frame_type != BREATH_RATE_TYPE_BUFFER && frame_type != HEART_RATE_TYPE_BUFFER &&
frame_type != DISTANCE_TYPE_BUFFER && frame_type != PEOPLE_EXIST_TYPE_BUFFER &&
frame_type != PRINT_CLOUD_BUFFER) {
// The reader checks the type and the header; the data checksum is checked here
static bool frame_valid(const uint8_t *frame, size_t len) {
if (!validate_checksum(frame + TinyFrameLength::KNOWN_AT, len - FRAME_OVERHEAD, frame[len - 1])) {
ESP_LOGE(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", frame[len - 1]);
ESP_LOGV_HEX(TAG, frame, len - 1, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
return false;
}
return true;
}
uint8_t header_checksum = new_byte;
if (at == 7) {
if (!validate_checksum(data, 7, header_checksum)) {
ESP_LOGE(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", header_checksum);
ESP_LOGV_HEX(TAG, data, 8, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
void MR60BHA2Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
return false;
}
this->handle_frame_(frame, len);
return true;
}
};
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
}
// Wait until all data is read
if (at - 8 < length) {
return true;
}
uint8_t data_checksum = new_byte;
if (at == 8 + length) {
if (!validate_checksum(data + 8, length, data_checksum)) {
ESP_LOGE(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", data_checksum);
ESP_LOGV_HEX(TAG, data, 8 + length, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
return false;
}
}
const uint8_t *frame_data = data + 8;
void MR60BHA2Component::handle_frame_(const uint8_t *frame, size_t len) {
const uint16_t frame_id = encode_uint16(frame[1], frame[2]);
const uint16_t frame_type = encode_uint16(frame[5], frame[6]);
const uint8_t *frame_data = frame + TinyFrameLength::KNOWN_AT;
const size_t length = len - FRAME_OVERHEAD;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf1[format_hex_pretty_size(MR60BHA2_MAX_LOG_BYTES)];
char hex_buf2[format_hex_pretty_size(MR60BHA2_MAX_LOG_BYTES)];
#endif
ESP_LOGV(TAG, "Received Frame: ID: 0x%04x, Type: 0x%04x, Data: [%s] Raw Data: [%s]", frame_id, frame_type,
format_hex_pretty_to(hex_buf1, sizeof(hex_buf1), frame_data, length),
format_hex_pretty_to(hex_buf2, sizeof(hex_buf2), this->rx_message_.data(), this->rx_message_.size()));
this->process_frame_(frame_id, frame_type, data + 8, length);
// Return false to reset rx buffer
return false;
format_hex_pretty_to(hex_buf2, sizeof(hex_buf2), frame, len));
this->process_frame_(frame_id, frame_type, frame_data, length);
}
void MR60BHA2Component::process_frame_(uint16_t frame_id, uint16_t frame_type, const uint8_t *data, size_t length) {
@@ -9,12 +9,23 @@
#endif
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <map>
namespace esphome::seeed_mr60bha2 {
static const uint8_t FRAME_HEADER_BUFFER = 0x01;
static constexpr uint8_t FRAME_HEADER_BUFFER = 0x01;
/// 01, id (2), data length (2, BE), type (2), header checksum, data, data checksum; 0 for a bad header
struct TinyFrameLength {
static constexpr size_t KNOWN_AT = 8;
static size_t get(const uint8_t *buf);
};
// Header, id, length and type bytes, header checksum, then the data and its checksum
static constexpr uint8_t FRAME_OVERHEAD = 9;
// A point cloud frame is 13 bytes plus 16 per target and only its count is read; 128 holds up to 7 targets
static constexpr uint8_t FRAME_MAX_SIZE = 128;
static const uint16_t BREATH_RATE_TYPE_BUFFER = 0x0A14;
static const uint16_t PEOPLE_EXIST_TYPE_BUFFER = 0x0F09;
static const uint16_t HEART_RATE_TYPE_BUFFER = 0x0A15;
@@ -39,10 +50,11 @@ class MR60BHA2Component final : public Component,
void loop() override;
protected:
bool validate_message_();
void handle_frame_(const uint8_t *frame, size_t len);
void process_frame_(uint16_t frame_id, uint16_t frame_type, const uint8_t *data, size_t length);
std::vector<uint8_t> rx_message_;
uint32_t last_rx_{0};
LengthFrameReader<FRAME_MAX_SIZE, FrameFormat<FrameHeader<FRAME_HEADER_BUFFER>, TinyFrameLength>> reader_;
};
} // namespace esphome::seeed_mr60bha2
@@ -1,6 +1,7 @@
#include "seeed_mr60fda2.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include <cinttypes>
@@ -33,22 +34,7 @@ void MR60FDA2Component::dump_config() {
}
// Initialisation functions
void MR60FDA2Component::setup() {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
this->current_frame_id_ = 0;
this->current_frame_len_ = 0;
this->current_data_frame_len_ = 0;
this->current_frame_type_ = 0;
this->get_radar_parameters();
memset(this->current_frame_buf_, 0, FRAME_BUF_MAX_SIZE);
memset(this->current_data_buf_, 0, DATA_BUF_MAX_SIZE);
}
// main loop
void MR60FDA2Component::loop() {
this->read_available([this](uint8_t b) { this->split_frame_(b); });
}
void MR60FDA2Component::setup() { this->get_radar_parameters(); }
// The checksum is the inverted XOR of the bytes
static uint8_t calculate_checksum(const uint8_t *data, size_t len) { return ~xor_bytes(data, len); }
@@ -68,6 +54,45 @@ static bool validate_checksum(const uint8_t *data, size_t len, uint8_t expected_
return calculate_checksum(data, len) == expected_checksum;
}
static bool is_known_type(uint16_t type) {
return type == IS_FALL_TYPE_BUFFER || type == PEOPLE_EXIST_TYPE_BUFFER || type == RESULT_INSTALL_HEIGHT ||
type == RESULT_PARAMETERS || type == RESULT_HEIGHT_THRESHOLD || type == RESULT_SENSITIVITY;
}
// An unknown type or a bad header checksum gives no length, so the header is dropped at once
size_t TinyFrameLength::get(const uint8_t *buf) {
const uint16_t type = encode_uint16(buf[5], buf[6]);
const uint16_t data_len = encode_uint16(buf[3], buf[4]);
// A parameter reply is read for 12 data bytes
if (!is_known_type(type) || (type == RESULT_PARAMETERS && data_len < 12))
return 0;
if (!validate_checksum(buf, LEN_TO_HEAD_CKSUM - 1, buf[LEN_TO_HEAD_CKSUM - 1])) {
ESP_LOGD(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", buf[LEN_TO_HEAD_CKSUM - 1]);
ESP_LOGV_HEX(TAG, buf, LEN_TO_HEAD_CKSUM, MR60FDA2_MAX_LOG_BYTES, "CURRENT_FRAME: %s");
return 0;
}
return data_len + LEN_TO_DATA_FRAME;
}
static bool frame_valid(const uint8_t *frame, size_t len) {
if (!validate_checksum(frame + LEN_TO_HEAD_CKSUM, len - LEN_TO_DATA_FRAME, frame[len - 1])) {
ESP_LOGD(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", frame[len - 1]);
ESP_LOGV_HEX(TAG, frame, len, MR60FDA2_MAX_LOG_BYTES, "GET CURRENT_FRAME: %s");
return false;
}
return true;
}
void MR60FDA2Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
return false;
this->process_frame_(frame);
return true;
};
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
}
#ifdef USE_SELECT
static uint8_t find_nearest_index(float value, const float *arr, int size) {
int nearest_index = 0;
@@ -88,152 +113,43 @@ alignas(4) static const float INSTALL_HEIGHT[7] PROGMEM = {2.4f, 2.5f, 2.6f, 2.7
alignas(4) static const float HEIGHT_THRESHOLD[7] PROGMEM = {0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f};
alignas(4) static const float SENSITIVITY[3] PROGMEM = {3, 15, 30};
void MR60FDA2Component::split_frame_(uint8_t buffer) {
switch (this->current_frame_locate_) {
case LOCATE_FRAME_HEADER: // starting buffer
if (buffer == FRAME_HEADER_BUFFER) {
this->current_frame_len_ = 0;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
}
break;
case LOCATE_ID_FRAME1:
this->current_frame_id_ = buffer << 8;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
break;
case LOCATE_ID_FRAME2:
this->current_frame_id_ += buffer;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
break;
case LOCATE_LENGTH_FRAME_H:
this->current_data_frame_len_ = buffer << 8;
if (this->current_data_frame_len_ == 0) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
} else {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
case LOCATE_LENGTH_FRAME_L:
this->current_data_frame_len_ += buffer;
if (this->current_data_frame_len_ > DATA_BUF_MAX_SIZE) {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
} else {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
}
break;
case LOCATE_TYPE_FRAME1:
this->current_frame_type_ = buffer << 8;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
break;
case LOCATE_TYPE_FRAME2:
this->current_frame_type_ += buffer;
if ((this->current_frame_type_ == IS_FALL_TYPE_BUFFER) ||
(this->current_frame_type_ == PEOPLE_EXIST_TYPE_BUFFER) ||
(this->current_frame_type_ == RESULT_INSTALL_HEIGHT) || (this->current_frame_type_ == RESULT_PARAMETERS) ||
(this->current_frame_type_ == RESULT_HEIGHT_THRESHOLD) || (this->current_frame_type_ == RESULT_SENSITIVITY)) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
} else {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
case LOCATE_HEAD_CKSUM_FRAME:
if (validate_checksum(this->current_frame_buf_, this->current_frame_len_, buffer)) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
} else {
ESP_LOGD(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", buffer);
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char frame_buf[format_hex_pretty_size(MR60FDA2_MAX_LOG_BYTES)];
char byte_buf[format_hex_pretty_size(1)];
#endif
ESP_LOGV(TAG, "CURRENT_FRAME: %s %s",
format_hex_pretty_to(frame_buf, this->current_frame_buf_, this->current_frame_len_),
format_hex_pretty_to(byte_buf, &buffer, 1));
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
case LOCATE_DATA_FRAME:
if (this->current_frame_len_ >= FRAME_BUF_MAX_SIZE) {
ESP_LOGD(TAG, "PRACTICE_DATA_FRAME_LEN ERROR: %d", this->current_frame_len_ - LEN_TO_HEAD_CKSUM);
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
}
this->current_data_buf_[this->current_frame_len_ - LEN_TO_DATA_FRAME + 1] = buffer;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
if (this->current_frame_len_ - LEN_TO_HEAD_CKSUM == this->current_data_frame_len_) {
this->current_frame_locate_++;
}
break;
case LOCATE_DATA_CKSUM_FRAME:
if (validate_checksum(this->current_data_buf_, this->current_data_frame_len_, buffer)) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
this->process_frame_();
} else {
ESP_LOGD(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", buffer);
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char frame_buf[format_hex_pretty_size(MR60FDA2_MAX_LOG_BYTES)];
char byte_buf[format_hex_pretty_size(1)];
#endif
ESP_LOGV(TAG, "GET CURRENT_FRAME: %s %s",
format_hex_pretty_to(frame_buf, this->current_frame_buf_, this->current_frame_len_),
format_hex_pretty_to(byte_buf, &buffer, 1));
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
default:
break;
}
}
void MR60FDA2Component::process_frame_() {
switch (this->current_frame_type_) {
void MR60FDA2Component::process_frame_(const uint8_t *frame) {
const uint8_t *data = frame + LEN_TO_HEAD_CKSUM;
switch (encode_uint16(frame[5], frame[6])) {
case IS_FALL_TYPE_BUFFER:
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->fall_detected_binary_sensor_, this->current_frame_buf_[LEN_TO_HEAD_CKSUM]);
PUBLISH_STATE(this->fall_detected_binary_sensor_, data[0]);
#endif
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case PEOPLE_EXIST_TYPE_BUFFER:
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->people_exist_binary_sensor_, this->current_frame_buf_[LEN_TO_HEAD_CKSUM]);
PUBLISH_STATE(this->people_exist_binary_sensor_, data[0]);
#endif
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_INSTALL_HEIGHT:
if (this->current_data_buf_[0]) {
if (data[0]) {
ESP_LOGD(TAG, "Successfully set the mounting height");
} else {
ESP_LOGD(TAG, "Failed to set the mounting height");
}
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_HEIGHT_THRESHOLD:
if (this->current_data_buf_[0]) {
if (data[0]) {
ESP_LOGD(TAG, "Successfully set the height threshold");
} else {
ESP_LOGD(TAG, "Failed to set the height threshold");
}
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_SENSITIVITY:
if (this->current_data_buf_[0]) {
if (data[0]) {
ESP_LOGD(TAG, "Successfully set the sensitivity");
} else {
ESP_LOGD(TAG, "Failed to set the sensitivity");
}
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_PARAMETERS: {
@@ -242,8 +158,7 @@ void MR60FDA2Component::process_frame_() {
uint32_t current_sensitivity = 0;
#ifdef USE_SELECT
if (this->install_height_select_ != nullptr) {
uint32_t current_install_height_int =
encode_uint32(current_data_buf_[3], current_data_buf_[2], current_data_buf_[1], current_data_buf_[0]);
uint32_t current_install_height_int = encode_uint32(data[3], data[2], data[1], data[0]);
install_height_float = bit_cast<float>(current_install_height_int);
uint32_t select_index = find_nearest_index(install_height_float, INSTALL_HEIGHT, 7);
@@ -251,8 +166,7 @@ void MR60FDA2Component::process_frame_() {
}
if (this->height_threshold_select_ != nullptr) {
uint32_t current_height_threshold_int =
encode_uint32(current_data_buf_[7], current_data_buf_[6], current_data_buf_[5], current_data_buf_[4]);
uint32_t current_height_threshold_int = encode_uint32(data[7], data[6], data[5], data[4]);
height_threshold_float = bit_cast<float>(current_height_threshold_int);
size_t select_index = find_nearest_index(height_threshold_float, HEIGHT_THRESHOLD, 7);
@@ -260,8 +174,7 @@ void MR60FDA2Component::process_frame_() {
}
if (this->sensitivity_select_ != nullptr) {
current_sensitivity =
encode_uint32(current_data_buf_[11], current_data_buf_[10], current_data_buf_[9], current_data_buf_[8]);
current_sensitivity = encode_uint32(data[11], data[10], data[9], data[8]);
uint32_t select_index = find_nearest_index(current_sensitivity, SENSITIVITY, 3);
this->sensitivity_select_->publish_state(select_index);
@@ -270,7 +183,6 @@ void MR60FDA2Component::process_frame_() {
ESP_LOGD(TAG, "Mounting height: %.2f, Height threshold: %.2f, Sensitivity: %" PRIu32, install_height_float,
height_threshold_float, current_sensitivity);
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
}
default:
@@ -15,18 +15,25 @@
#endif
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <map>
namespace esphome::seeed_mr60fda2 {
static const uint8_t DATA_BUF_MAX_SIZE = 28;
static const uint8_t FRAME_BUF_MAX_SIZE = 37;
static const uint8_t LEN_TO_HEAD_CKSUM = 8;
static const uint8_t LEN_TO_DATA_FRAME = 9;
static constexpr uint8_t DATA_BUF_MAX_SIZE = 28;
static constexpr uint8_t LEN_TO_HEAD_CKSUM = 8;
static constexpr uint8_t LEN_TO_DATA_FRAME = 9;
static constexpr uint8_t FRAME_BUF_MAX_SIZE = DATA_BUF_MAX_SIZE + LEN_TO_DATA_FRAME;
static const uint8_t FRAME_HEADER_BUFFER = 0x01;
static constexpr uint8_t FRAME_HEADER_BUFFER = 0x01;
/// 01, id (2), data length (2, BE), type (2), header checksum, data, data checksum; 0 for a bad header
struct TinyFrameLength {
static constexpr size_t KNOWN_AT = LEN_TO_HEAD_CKSUM;
static size_t get(const uint8_t *buf);
};
static const uint16_t IS_FALL_TYPE_BUFFER = 0x0E02;
static const uint16_t PEOPLE_EXIST_TYPE_BUFFER = 0x0F09;
static const uint16_t RESULT_INSTALL_HEIGHT = 0x0E04;
@@ -34,20 +41,6 @@ static const uint16_t RESULT_PARAMETERS = 0x0E06;
static const uint16_t RESULT_HEIGHT_THRESHOLD = 0x0E08;
static const uint16_t RESULT_SENSITIVITY = 0x0E0A;
enum FrameLocation {
LOCATE_FRAME_HEADER,
LOCATE_ID_FRAME1,
LOCATE_ID_FRAME2,
LOCATE_LENGTH_FRAME_H,
LOCATE_LENGTH_FRAME_L,
LOCATE_TYPE_FRAME1,
LOCATE_TYPE_FRAME2,
LOCATE_HEAD_CKSUM_FRAME, // Header checksum: [from the first byte to the previous byte of the HEAD_CKSUM bit]
LOCATE_DATA_FRAME,
LOCATE_DATA_CKSUM_FRAME, // Data checksum: [from the first to the previous byte of the DATA_CKSUM bit]
LOCATE_PROCESS_FRAME,
};
class MR60FDA2Component final : public Component,
public uart::UARTDevice { // The class name must be the name defined by text_sensor.py
#ifdef USE_BINARY_SENSOR
@@ -65,16 +58,12 @@ class MR60FDA2Component final : public Component,
#endif
protected:
uint8_t current_frame_locate_;
uint8_t current_frame_buf_[FRAME_BUF_MAX_SIZE];
uint8_t current_data_buf_[DATA_BUF_MAX_SIZE];
uint16_t current_frame_id_;
size_t current_frame_len_;
size_t current_data_frame_len_;
uint16_t current_frame_type_;
uint32_t last_rx_{0};
LengthFrameReader<FRAME_BUF_MAX_SIZE, FrameFormat<FrameHeader<FRAME_HEADER_BUFFER>, TinyFrameLength,
FrameMinLength<LEN_TO_DATA_FRAME + 1>>>
reader_;
void split_frame_(uint8_t buffer);
void process_frame_();
void process_frame_(const uint8_t *frame);
public:
float get_setup_priority() const override { return esphome::setup_priority::LATE; }
@@ -98,7 +98,7 @@ CONFIG_SCHEMA = cv.All(
cv.positive_time_period_milliseconds,
cv.Range(max=cv.TimePeriod(milliseconds=5000)),
),
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=False): cv.boolean,
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): cv.boolean,
cv.Optional(CONF_FIXED_DELAY, default="0us"): cv.All(
cv.positive_time_period_microseconds,
cv.Range(max=cv.TimePeriod(microseconds=10000)),
@@ -61,7 +61,7 @@ class SendspinMediaSource final : public SendspinChild,
bool cached_muted_{false};
bool pending_start_{false};
bool static_delay_adjustable_{false};
bool static_delay_adjustable_{true};
};
} // namespace esphome::sendspin_
@@ -15,20 +15,17 @@
#include <algorithm>
#include <cstring>
#include <memory>
#include <numeric>
namespace {
ESPHOME_LOG_TAG(TAG, "shelly_dimmer");
constexpr uint8_t SHELLY_DIMMER_ACK_TIMEOUT = 200; // ms
// A partial frame left this long without a byte is given up, so a stray header cannot hide the reply
constexpr uint8_t SHELLY_DIMMER_RX_GAP = 20; // ms
constexpr uint8_t SHELLY_DIMMER_MAX_RETRIES = 3;
constexpr uint16_t SHELLY_DIMMER_MAX_BRIGHTNESS = 1000; // 100%
// Protocol framing.
constexpr uint8_t SHELLY_DIMMER_PROTO_START_BYTE = 0x01;
constexpr uint8_t SHELLY_DIMMER_PROTO_END_BYTE = 0x04;
// Supported commands.
constexpr uint8_t SHELLY_DIMMER_PROTO_CMD_SWITCH = 0x01;
constexpr uint8_t SHELLY_DIMMER_PROTO_CMD_POLL = 0x10;
@@ -58,11 +55,6 @@ template<typename T, size_t N> constexpr size_t size(const T (& /*unused*/)[N])
namespace esphome::shelly_dimmer {
/// Computes a crappy checksum as defined by the Shelly Dimmer protocol.
uint16_t shelly_dimmer_checksum(const uint8_t *buf, int len) {
return std::accumulate<decltype(buf), uint16_t>(buf, buf + len, 0);
}
bool ShellyDimmer::is_running_configured_version() const {
return this->version_major_ == USE_SHD_FIRMWARE_MAJOR_VERSION &&
this->version_minor_ == USE_SHD_FIRMWARE_MINOR_VERSION;
@@ -278,8 +270,9 @@ bool ShellyDimmer::send_command_(uint8_t cmd, const uint8_t *const payload, uint
ESP_LOGD(TAG, "Command sent, waiting for reply");
const uint32_t tx_time = millis();
while (millis() - tx_time < SHELLY_DIMMER_ACK_TIMEOUT) {
if (this->read_frame_()) {
uint32_t last_rx = tx_time;
for (uint32_t now = tx_time; now - tx_time < SHELLY_DIMMER_ACK_TIMEOUT; now = millis()) {
if (this->read_frame_(now, last_rx)) {
return true;
}
delay(1);
@@ -303,83 +296,31 @@ size_t ShellyDimmer::frame_command_(uint8_t *data, uint8_t cmd, const uint8_t *c
}
// Checksum over the sequence, command, length and payload bytes
p = put_be16(p, shelly_dimmer_checksum(data + 1, 3 + len));
p = put_be16(p, sum16_bytes(data + 1, 3 + len));
*p++ = SHELLY_DIMMER_PROTO_END_BYTE;
return p - data;
}
int ShellyDimmer::handle_byte_(uint8_t c) {
const uint8_t pos = this->buffer_pos_;
if (pos == 0) {
// Must be start byte.
return c == SHELLY_DIMMER_PROTO_START_BYTE ? 1 : -1;
} else if (pos < 4) {
// Header.
return 1;
}
// Decode payload length from header.
const uint8_t payload_len = this->buffer_[3];
if ((4 + payload_len + 3) > SHELLY_DIMMER_BUFFER_SIZE) {
return -1;
}
if (pos < 4 + payload_len + 1) {
// Payload.
return 1;
}
if (pos == 4 + payload_len + 1) {
// Verify checksum.
const uint16_t csum = encode_uint16(this->buffer_[pos - 1], c);
const uint16_t csum_verify = shelly_dimmer_checksum(&this->buffer_[1], 3 + payload_len);
if (csum != csum_verify) {
return -1;
bool ShellyDimmer::read_frame_(uint32_t now, uint32_t &last_rx) {
bool received = false;
auto handler = [this, &received](const uint8_t *frame, size_t len) {
// The checksum covers seq, cmd, length and payload
if (frame[len - 1] != SHELLY_DIMMER_PROTO_END_BYTE ||
encode_uint16(frame[len - 3], frame[len - 2]) != sum16_bytes(frame + 1, len - 4)) {
return false;
}
return 1;
}
if (pos == 4 + payload_len + 2) {
// Must be end byte.
return c == SHELLY_DIMMER_PROTO_END_BYTE ? 0 : -1;
}
return -1;
this->handle_frame_(frame);
received = true;
return true;
};
this->read_frames(this->reader_, handler, now, last_rx, SHELLY_DIMMER_RX_GAP);
return received;
}
bool ShellyDimmer::read_frame_() {
while (this->available()) {
const uint8_t c = this->read();
this->buffer_[this->buffer_pos_] = c;
ESP_LOGV(TAG, "Read byte: 0x%02x (pos %d)", c, this->buffer_pos_);
switch (this->handle_byte_(c)) {
case 0: {
// Frame successfully received.
this->handle_frame_();
this->buffer_pos_ = 0;
return true;
}
case -1: {
// Failure.
this->buffer_pos_ = 0;
break;
}
case 1: {
// Need more data.
this->buffer_pos_++;
break;
}
}
}
return false;
}
bool ShellyDimmer::handle_frame_() {
const uint8_t seq = this->buffer_[1];
const uint8_t cmd = this->buffer_[2];
const uint8_t payload_len = this->buffer_[3];
bool ShellyDimmer::handle_frame_(const uint8_t *frame) {
const uint8_t seq = frame[1];
const uint8_t cmd = frame[2];
const uint8_t payload_len = frame[3];
ESP_LOGD(TAG, "Got frame: 0x%02x", cmd);
@@ -389,7 +330,7 @@ bool ShellyDimmer::handle_frame_() {
return false;
}
const uint8_t *payload = &this->buffer_[4];
const uint8_t *payload = frame + PayloadLength::KNOWN_AT;
// Handle response.
switch (cmd) {
@@ -8,7 +8,7 @@
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
#include <array>
#include "esphome/core/frame_reader.h"
namespace esphome::shelly_dimmer {
@@ -18,7 +18,10 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
SUB_SENSOR(current)
private:
static constexpr uint16_t SHELLY_DIMMER_BUFFER_SIZE = 256;
// Holds the largest reply, a 24 byte poll
static constexpr uint16_t SHELLY_DIMMER_BUFFER_SIZE = 32;
static constexpr uint8_t SHELLY_DIMMER_PROTO_START_BYTE = 0x01;
static constexpr uint8_t SHELLY_DIMMER_PROTO_END_BYTE = 0x04;
public:
float get_setup_priority() const override { return setup_priority::LATE; }
@@ -52,10 +55,11 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
GPIOPin *pin_nrst_;
GPIOPin *pin_boot0_;
// Frame parser state.
uint8_t seq_{0};
std::array<uint8_t, SHELLY_DIMMER_BUFFER_SIZE> buffer_;
uint8_t buffer_pos_{0};
// Start byte, seq, cmd, payload length, payload, checksum (2), end byte
using PayloadLength = PayloadLengthU8<LengthField{.offset = 3, .trailer = 3}>;
LengthFrameReader<SHELLY_DIMMER_BUFFER_SIZE, FrameFormat<FrameHeader<SHELLY_DIMMER_PROTO_START_BYTE>, PayloadLength>>
reader_;
// Firmware version.
uint8_t version_major_;
@@ -92,16 +96,11 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
/// Frames a given command payload.
size_t frame_command_(uint8_t *data, uint8_t cmd, const uint8_t *payload, size_t len);
/// Handles a single byte as part of a protocol frame.
///
/// Returns -1 on failure, 0 when finished and 1 when more bytes needed.
int handle_byte_(uint8_t c);
/// Reads a response frame.
bool read_frame_();
bool read_frame_(uint32_t now, uint32_t &last_rx);
/// Handles a complete frame.
bool handle_frame_();
bool handle_frame_(const uint8_t *frame);
/// Reset STM32 with the BOOT0 pin set to the given value.
void reset_(bool boot0);
+68 -30
View File
@@ -4,13 +4,22 @@ import esphome.codegen as cg
from esphome.components import time, uart
import esphome.config_validation as cv
from esphome.const import CONF_SENSOR_DATAPOINT, CONF_TIME_ID
from esphome.core import CORE, CoroPriority, coroutine_with_priority
from esphome.core import CORE, AutoLoad, CoroPriority, coroutine_with_priority
from esphome.cpp_generator import MockObj
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
from esphome.types import ConfigType
DEPENDENCIES = ["uart"]
CODEOWNERS = ["@dwmw2", "@ssieb"]
DOMAIN = "tuya"
# AutoLoad: another transport pulled in only the base class. None: CI dependency probe.
def AUTO_LOAD(config: ConfigType | AutoLoad | None) -> list[str]:
if isinstance(config, AutoLoad):
return []
return ["uart"]
CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS = "ignore_mcu_update_on_datapoints"
CONF_ON_DATAPOINT_UPDATE = "on_datapoint_update"
@@ -20,7 +29,8 @@ CONF_FORCE_TIME_SYNC = "force_time_sync"
tuya_ns = cg.esphome_ns.namespace("tuya")
TuyaDatapointType = tuya_ns.enum("TuyaDatapointType", is_class=True)
Tuya = tuya_ns.class_("Tuya", cg.Component, uart.UARTDevice)
Tuya = tuya_ns.class_("Tuya", cg.Component)
TuyaUART = tuya_ns.class_("TuyaUART", Tuya, uart.UARTDevice)
TuyaDatapoint = tuya_ns.struct("TuyaDatapoint")
@@ -72,42 +82,50 @@ def _validate_time_options(config: ConfigType) -> ConfigType:
return config
CONFIG_SCHEMA = cv.All(
cv.Schema(
TUYA_SCHEMA = cv.Schema(
{
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(cv.uint8_t),
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
{
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
*DATAPOINT_TYPES, lower=True
),
}
),
}
).extend(cv.COMPONENT_SCHEMA)
UART_SCHEMA = cv.All(
TUYA_SCHEMA.extend(
{
cv.GenerateID(): cv.declare_id(Tuya),
cv.GenerateID(): cv.declare_id(TuyaUART),
cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
cv.Optional(CONF_FORCE_TIME_SYNC, default=False): cv.boolean,
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(
cv.uint8_t
),
cv.Optional(CONF_STATUS_PIN): pins.gpio_output_pin_schema,
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
{
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
*DATAPOINT_TYPES, lower=True
),
}
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(uart.UART_DEVICE_SCHEMA),
).extend(uart.UART_DEVICE_SCHEMA),
_validate_time_options,
)
async def to_code(config):
var = await uart.new_uart_component(config)
if (time_id := config.get(CONF_TIME_ID)) is not None:
await cg.add_variable(var.set_time_id, time_id)
if config[CONF_FORCE_TIME_SYNC]:
cg.add(var.set_force_time_sync(True))
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
if CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS in config:
for dp in config[CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS]:
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
@schema_extractor("schema")
def _validate_config(value: ConfigType | AutoLoad) -> ConfigType | AutoLoad | cv.Schema:
if value is SCHEMA_EXTRACT:
# Expose the UART schema to the language-schema dumper
return UART_SCHEMA
if isinstance(value, AutoLoad):
return value
return UART_SCHEMA(value)
CONFIG_SCHEMA = _validate_config
async def setup_tuya(var: MockObj, config: ConfigType) -> None:
"""Apply the base-class options; called from a transport's to_code()."""
for dp in config.get(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS, []):
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
for conf in config.get(CONF_ON_DATAPOINT_UPDATE, []):
type_, expected, field = DATAPOINT_TYPES[conf[CONF_DATAPOINT_TYPE]]
forward = None
@@ -117,3 +135,23 @@ async def to_code(config):
[(type_, "x")], conf, params=[(TuyaDatapoint, "x")], forward=forward
)
cg.add(var.register_listener(conf[CONF_SENSOR_DATAPOINT], callback))
async def to_code(config: ConfigType | AutoLoad) -> None:
if isinstance(config, AutoLoad):
return
var = await uart.new_uart_component(config)
if (time_id := config.get(CONF_TIME_ID)) is not None:
await cg.add_variable(var.set_time_id, time_id)
if config[CONF_FORCE_TIME_SYNC]:
cg.add(var.set_force_time_sync(True))
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
await setup_tuya(var, config)
def FILTER_SOURCE_FILES() -> list[str]:
# When only auto-loaded as a base class, the UART implementation is unused
if isinstance(CORE.config.get(DOMAIN), AutoLoad):
return ["tuya_uart.cpp", "tuya_uart.h"]
return []
+37 -683
View File
@@ -1,85 +1,13 @@
#include "tuya.h"
#include <cstring>
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#ifdef USE_NETWORK
#include "esphome/components/network/util.h"
#endif
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"
#endif
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/components/captive_portal/captive_portal.h"
#endif
namespace esphome::tuya {
ESPHOME_LOG_TAG(TAG, "tuya");
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
static const int COMMAND_DELAY = 10;
static const int RECEIVE_TIMEOUT = 300;
static const int MAX_RETRIES = 5;
// Max bytes to log for datapoint values (larger values are truncated)
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
static bool network_is_connected() {
#ifdef USE_NETWORK
return network::is_connected();
#else
return false;
#endif
}
void Tuya::setup() {
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
#ifdef USE_TIME
if (this->force_time_sync_) {
this->register_local_time_sync_callback_();
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
[this] { this->check_force_time_sync_(); });
}
#endif
if (this->status_pin_ != nullptr) {
this->status_pin_->digital_write(false);
}
}
void Tuya::loop() {
this->read_available([this](uint8_t b) { this->handle_char_(b); });
process_command_queue_();
}
void Tuya::dump_config() {
this->dump_mcu_config_();
#ifdef USE_TUYA_DUMP_PUBLISHER
if (this->dump_publisher_ != nullptr)
this->dump_publisher_();
#endif
}
// Also logged again once the MCU reports its datapoints
void Tuya::dump_mcu_config_() {
ESP_LOGCONFIG(TAG, "Tuya:");
if (this->init_state_ != TuyaInitState::INIT_DONE) {
if (this->init_failed_) {
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
} else {
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
static_cast<uint8_t>(this->init_state_));
}
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
return;
}
void Tuya::dump_datapoints_() {
for (auto &info : this->datapoints_) {
if (info.type == TuyaDatapointType::RAW) {
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
@@ -99,595 +27,36 @@ void Tuya::dump_mcu_config_() {
ESP_LOGCONFIG(TAG, " Datapoint %u: unknown", info.id);
}
}
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
this->reset_pin_reported_);
}
LOG_PIN(" Status Pin: ", this->status_pin_);
ESP_LOGCONFIG(TAG, " Product: '%s'",
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
}
#endif
}
bool Tuya::validate_message_() {
uint32_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
// Byte 0: HEADER1 (always 0x55)
if (at == 0)
return new_byte == 0x55;
// Byte 1: HEADER2 (always 0xAA)
if (at == 1)
return new_byte == 0xAA;
// Byte 2: VERSION
// no validation for the following fields:
uint8_t version = data[2];
if (at == 2)
return true;
// Byte 3: COMMAND
uint8_t command = data[3];
if (at == 3)
return true;
// Byte 4: LENGTH1
// Byte 5: LENGTH2
if (at <= 5) {
// no validation for these fields
return true;
}
uint16_t length = encode_uint16(data[4], data[5]);
// wait until all data is read
if (at - 6 < length)
return true;
// Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
uint8_t rx_checksum = new_byte;
const uint8_t calc_checksum = sum_bytes(data, 6 + length);
if (rx_checksum != calc_checksum) {
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
return false;
}
// valid message
const uint8_t *message_data = data + 6;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
#endif
this->handle_command_(command, version, message_data, length);
// return false to reset rx buffer
return false;
}
void Tuya::handle_char_(uint8_t c) {
this->rx_message_.push_back(c);
if (!this->validate_message_()) {
this->rx_message_.clear();
} else {
this->last_rx_char_timestamp_ = millis();
}
}
void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
TuyaCommandType command_type = (TuyaCommandType) command;
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
this->expected_response_.reset();
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
switch (command_type) {
case TuyaCommandType::HEARTBEAT:
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
this->protocol_version_ = version;
if (buffer[0] == 0) {
ESP_LOGI(TAG, "MCU restarted");
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
}
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
this->init_state_ = TuyaInitState::INIT_PRODUCT;
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
}
break;
case TuyaCommandType::PRODUCT_QUERY: {
// check it is a valid string made up of printable characters
bool valid = true;
for (size_t i = 0; i < len; i++) {
if (!std::isprint(buffer[i])) {
valid = false;
break;
}
}
if (valid) {
this->product_ = std::make_unique<char[]>(len + 1);
memcpy(this->product_.get(), buffer, len);
} else {
this->product_.reset();
}
this->product_invalid_ = !valid;
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
this->init_state_ = TuyaInitState::INIT_CONF;
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
}
break;
}
case TuyaCommandType::CONF_QUERY: {
if (len >= 2) {
this->status_pin_reported_ = buffer[0];
this->reset_pin_reported_ = buffer[1];
}
if (this->init_state_ == TuyaInitState::INIT_CONF) {
// If mcu returned status gpio, then we can omit sending wifi state
if (this->status_pin_reported_ != -1) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
if (this->status_pin_ != nullptr) {
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
this->status_pin_reported_);
}
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
} else {
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
this->status_pin_reported_);
}
} else {
this->init_state_ = TuyaInitState::INIT_WIFI;
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
}
}
break;
}
case TuyaCommandType::WIFI_STATE:
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
}
break;
case TuyaCommandType::WIFI_SELECT:
case TuyaCommandType::WIFI_RESET: {
const bool is_select = (len >= 1);
// Send WIFI_SELECT ACK
TuyaCommand ack;
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
ack.payload.clear();
this->send_command_(ack);
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
uint8_t first = 0x00;
const char *mode_str = "EZ";
if (is_select && buffer[0] == 0x01) {
first = 0x01;
mode_str = "AP";
}
// Send WIFI_STATE response, MCU exits pairing mode
TuyaCommand st;
st.cmd = TuyaCommandType::WIFI_STATE;
st.payload.resize(1);
st.payload[0] = first;
this->send_command_(st);
st.payload[0] = 0x02;
this->send_command_(st);
st.payload[0] = 0x03;
this->send_command_(st);
st.payload[0] = 0x04;
this->send_command_(st);
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
break;
}
case TuyaCommandType::DATAPOINT_DELIVER:
break;
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
this->init_state_ = TuyaInitState::INIT_DONE;
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
this->initialized_callback_.call();
}
this->handle_datapoints_(buffer, len);
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
}
break;
case TuyaCommandType::DATAPOINT_QUERY:
break;
case TuyaCommandType::WIFI_TEST:
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
break;
case TuyaCommandType::WIFI_RSSI:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
break;
case TuyaCommandType::LOCAL_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_local_time_();
this->register_local_time_sync_callback_();
} else
#endif
{
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::GMT_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_gmt_time_();
if (!this->gmt_time_sync_callback_registered_) {
// tuya mcu supports time, so we let them know when our time changed
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
this->gmt_time_sync_callback_registered_ = true;
}
} else
#endif
{
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::VACUUM_MAP_UPLOAD:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
break;
case TuyaCommandType::GET_NETWORK_STATUS: {
uint8_t wifi_status = this->get_wifi_status_code_();
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
break;
}
case TuyaCommandType::EXTENDED_SERVICES: {
uint8_t subcommand = buffer[0];
switch ((TuyaExtendedServicesCommandType) subcommand) {
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
.payload = std::vector<uint8_t>{
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
ESP_LOGV(TAG, "Reset status notification enabled");
break;
}
case TuyaExtendedServicesCommandType::MODULE_RESET: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
break;
}
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
break;
}
default:
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
}
break;
}
default:
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
}
}
void Tuya::handle_datapoints_(const uint8_t *buffer, size_t len) {
while (len >= 4) {
TuyaDatapoint datapoint{};
datapoint.id = buffer[0];
datapoint.type = (TuyaDatapointType) buffer[1];
datapoint.value_uint = 0;
size_t data_size = encode_uint16(buffer[2], buffer[3]);
const uint8_t *data = buffer + 4;
size_t data_len = len - 4;
if (data_size > data_len) {
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
void Tuya::handle_datapoint_(const TuyaDatapoint &datapoint) {
// drop update if datapoint is in ignore_mcu_datapoint_update list
for (auto i : this->ignore_mcu_update_on_datapoints_) {
if (datapoint.id == i) {
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
return;
}
datapoint.len = data_size;
switch (datapoint.type) {
case TuyaDatapointType::RAW:
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
{
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
}
break;
case TuyaDatapointType::BOOLEAN:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
return;
}
datapoint.value_bool = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
break;
case TuyaDatapointType::INTEGER:
if (data_size != 4) {
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
return;
}
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
break;
case TuyaDatapointType::STRING:
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
break;
case TuyaDatapointType::ENUM:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
return;
}
datapoint.value_enum = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
break;
case TuyaDatapointType::BITMASK:
switch (data_size) {
case 1:
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
break;
case 2:
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
break;
case 4:
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
return;
}
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
return;
}
len -= data_size + 4;
buffer = data + data_size;
// drop update if datapoint is in ignore_mcu_datapoint_update list
bool skip = false;
for (auto i : this->ignore_mcu_update_on_datapoints_) {
if (datapoint.id == i) {
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
skip = true;
break;
}
}
if (skip)
continue;
// Update internal datapoints
bool found = false;
for (auto &other : this->datapoints_) {
if (other.id == datapoint.id) {
other = datapoint;
found = true;
}
}
if (!found) {
this->datapoints_.push_back(datapoint);
}
// Run through listeners
for (auto &listener : this->listeners_) {
if (listener.datapoint_id == datapoint.id)
listener.on_datapoint.call(datapoint);
}
}
}
void Tuya::send_raw_command_(TuyaCommand command) {
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
uint8_t version = 0;
this->last_command_timestamp_ = millis();
switch (command.cmd) {
case TuyaCommandType::HEARTBEAT:
this->expected_response_ = TuyaCommandType::HEARTBEAT;
break;
case TuyaCommandType::PRODUCT_QUERY:
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
break;
case TuyaCommandType::CONF_QUERY:
this->expected_response_ = TuyaCommandType::CONF_QUERY;
break;
case TuyaCommandType::DATAPOINT_DELIVER:
case TuyaCommandType::DATAPOINT_QUERY:
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
break;
default:
break;
}
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
static_cast<uint8_t>(this->init_state_));
#endif
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
if (!command.payload.empty())
this->write_array(command.payload.data(), command.payload.size());
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
}
void Tuya::process_command_queue_() {
uint32_t now = millis();
uint32_t delay = now - this->last_command_timestamp_;
if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
this->rx_message_.clear();
}
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
this->expected_response_.reset();
if (init_state_ != TuyaInitState::INIT_DONE) {
if (++this->init_retries_ >= MAX_RETRIES) {
this->init_failed_ = true;
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
} else {
this->command_queue_.erase(command_queue_.begin());
// Update internal datapoints
bool found = false;
for (auto &other : this->datapoints_) {
if (other.id == datapoint.id) {
other = datapoint;
found = true;
}
}
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
!this->expected_response_.has_value()) {
this->send_raw_command_(command_queue_.front());
if (!this->expected_response_.has_value())
this->command_queue_.erase(command_queue_.begin());
}
}
void Tuya::send_command_(const TuyaCommand &command) {
command_queue_.push_back(command);
process_command_queue_();
}
void Tuya::send_empty_command_(TuyaCommandType command) {
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
}
void Tuya::set_status_pin_() {
bool is_network_ready = network_is_connected() && remote_is_connected();
this->status_pin_->digital_write(is_network_ready);
}
uint8_t Tuya::get_wifi_status_code_() {
uint8_t status = 0x02;
if (network_is_connected()) {
status = 0x03;
// Protocol version 3 also supports specifying when connected to "the cloud"
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
status = 0x04;
}
} else {
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
status = 0x01;
}
#endif
};
return status;
}
uint8_t Tuya::get_wifi_rssi_() {
#ifdef USE_WIFI
if (wifi::global_wifi_component != nullptr)
return wifi::global_wifi_component->wifi_rssi();
#endif
return 0;
}
void Tuya::send_wifi_status_() {
uint8_t status = this->get_wifi_status_code_();
if (status == this->wifi_status_) {
return;
if (!found) {
this->datapoints_.push_back(datapoint);
}
ESP_LOGD(TAG, "Sending WiFi Status");
this->wifi_status_ = status;
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
}
#ifdef USE_TIME
void Tuya::register_local_time_sync_callback_() {
if (this->time_sync_callback_registered_) {
return;
// Run through listeners
for (auto &listener : this->listeners_) {
if (listener.datapoint_id == datapoint.id)
listener.on_datapoint.call(datapoint);
}
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
this->time_sync_callback_registered_ = true;
}
void Tuya::check_force_time_sync_() {
ESPTime now = this->time_id_->now();
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
return;
this->last_force_time_sync_minute_ = now.minute;
this->send_local_time_(true);
}
void Tuya::send_local_time_(bool periodic) {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->now();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
// Tuya days starts from Monday, esphome uses Sunday as day 1
uint8_t day_of_week = now.day_of_week - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
// The forced send repeats every minute, so it stays out of the debug log
if (periodic) {
ESP_LOGV(TAG, "Sending local time");
} else {
ESP_LOGD(TAG, "Sending local time");
}
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing local time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
}
void Tuya::send_gmt_time_() {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->utcnow();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
ESP_LOGD(TAG, "Sending gmt time");
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing gmt time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
}
#endif
void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
this->set_raw_datapoint_value_(datapoint_id, value, false);
}
@@ -744,19 +113,19 @@ void Tuya::force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t valu
this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BITMASK, value, length, true);
}
optional<TuyaDatapoint> Tuya::get_datapoint_(uint8_t datapoint_id) {
for (auto &datapoint : this->datapoints_) {
const TuyaDatapoint *Tuya::get_datapoint_(uint8_t datapoint_id) const {
for (const auto &datapoint : this->datapoints_) {
if (datapoint.id == datapoint_id)
return datapoint;
return &datapoint;
}
return {};
return nullptr;
}
void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint32_t value,
uint8_t length, bool forced) {
ESP_LOGD(TAG, "Setting datapoint %u to %" PRIu32, datapoint_id, value);
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != datapoint_type) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -766,30 +135,29 @@ void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType
return;
}
std::vector<uint8_t> data;
uint8_t data[4];
switch (length) {
case 4:
data.push_back(value >> 24);
data.push_back(value >> 16);
[[fallthrough]];
put_be32(data, value);
break;
case 2:
data.push_back(value >> 8);
[[fallthrough]];
put_be16(data, value);
break;
case 1:
data.push_back(value >> 0);
data[0] = value;
break;
default:
ESP_LOGE(TAG, "Unexpected datapoint length %u", length);
return;
}
this->send_datapoint_command_(datapoint_id, datapoint_type, data);
this->send_datapoint_command(datapoint_id, datapoint_type, data, length);
}
void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced) {
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, format_hex_pretty_to(hex_buf, value.data(), value.size()));
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != TuyaDatapointType::RAW) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -798,13 +166,13 @@ void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint
ESP_LOGV(TAG, "Not sending unchanged value");
return;
}
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::RAW, value);
this->send_datapoint_command(datapoint_id, TuyaDatapointType::RAW, value.data(), value.size());
}
void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced) {
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, value);
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != TuyaDatapointType::STRING) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -814,19 +182,7 @@ void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value,
ESP_LOGV(TAG, "Not sending unchanged value");
return;
}
std::vector<uint8_t> data(value, value + len);
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::STRING, data);
}
void Tuya::send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data) {
std::vector<uint8_t> buffer;
buffer.push_back(datapoint_id);
buffer.push_back(static_cast<uint8_t>(datapoint_type));
buffer.push_back(data.size() >> 8);
buffer.push_back(data.size() >> 0);
buffer.insert(buffer.end(), data.begin(), data.end());
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = buffer});
this->send_datapoint_command(datapoint_id, TuyaDatapointType::STRING, reinterpret_cast<const uint8_t *>(value), len);
}
void Tuya::register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func) {
@@ -850,6 +206,4 @@ const TuyaDatapoint &TuyaDatapoint::expect_type(TuyaDatapointType expected) cons
return *this;
}
TuyaInitState Tuya::get_init_state() { return this->init_state_; }
} // namespace esphome::tuya
+24 -100
View File
@@ -1,21 +1,17 @@
#pragma once
#include <cinttypes>
#include <memory>
#include <vector>
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#include "esphome/components/uart/uart.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#include "esphome/core/time.h"
#endif
namespace esphome::tuya {
// Max bytes to log for datapoint values (larger values are truncated)
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
enum class TuyaDatapointType : uint8_t {
RAW = 0x00, // variable length
BOOLEAN = 0x01, // 1 byte (0/1)
@@ -48,53 +44,18 @@ struct TuyaDatapointListener {
Callback<void(const TuyaDatapoint &)> on_datapoint;
};
enum class TuyaCommandType : uint8_t {
HEARTBEAT = 0x00,
PRODUCT_QUERY = 0x01,
CONF_QUERY = 0x02,
WIFI_STATE = 0x03,
WIFI_RESET = 0x04,
WIFI_SELECT = 0x05,
DATAPOINT_DELIVER = 0x06,
DATAPOINT_REPORT_ASYNC = 0x07,
DATAPOINT_QUERY = 0x08,
GMT_TIME_QUERY = 0x0C,
WIFI_TEST = 0x0E,
LOCAL_TIME_QUERY = 0x1C,
DATAPOINT_REPORT_SYNC = 0x22,
DATAPOINT_REPORT_ACK = 0x23,
WIFI_RSSI = 0x24,
VACUUM_MAP_UPLOAD = 0x28,
GET_NETWORK_STATUS = 0x2B,
EXTENDED_SERVICES = 0x34,
};
enum class TuyaExtendedServicesCommandType : uint8_t {
RESET_NOTIFICATION = 0x04,
MODULE_RESET = 0x05,
UPDATE_IN_PROGRESS = 0x0A,
};
enum class TuyaInitState : uint8_t {
INIT_HEARTBEAT = 0x00,
INIT_PRODUCT,
INIT_CONF,
INIT_WIFI,
INIT_DATAPOINT,
INIT_DONE,
};
struct TuyaCommand {
TuyaCommandType cmd;
std::vector<uint8_t> payload;
};
class Tuya final : public Component, public uart::UARTDevice {
/// Transport-agnostic Tuya controller. Subclasses implement send_datapoint_command(), feed received datapoints
/// to handle_datapoint_(), and call mark_initialized_() once the MCU has reported.
class Tuya : public Component {
public:
float get_setup_priority() const override { return setup_priority::LATE; }
void setup() override;
void loop() override;
void dump_config() override;
/// Prints each child entity's dump; a transport that overrides it prints its own block first, then calls this
void dump_config() override {
#ifdef USE_TUYA_DUMP_PUBLISHER
if (this->dump_publisher_ != nullptr)
this->dump_publisher_();
#endif
}
#ifdef USE_TUYA_DUMP_PUBLISHER
HUB_PUBLISHER(dump)
#endif
@@ -104,7 +65,6 @@ class Tuya final : public Component, public uart::UARTDevice {
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value);
void set_boolean_datapoint_value(uint8_t datapoint_id, bool value);
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value);
void set_status_pin(InternalGPIOPin *status_pin) { this->status_pin_ = status_pin; }
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value);
void set_string_datapoint_value(uint8_t datapoint_id, const char *value);
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
@@ -116,11 +76,6 @@ class Tuya final : public Component, public uart::UARTDevice {
void force_set_string_datapoint_value(uint8_t datapoint_id, const char *value);
void force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
void force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length);
TuyaInitState get_init_state();
#ifdef USE_TIME
void set_time_id(time::RealTimeClock *time_id) { this->time_id_ = time_id; }
void set_force_time_sync(bool force_time_sync) { this->force_time_sync_ = force_time_sync; }
#endif
void add_ignore_mcu_update_on_datapoints(uint8_t ignore_mcu_update_on_datapoints) {
this->ignore_mcu_update_on_datapoints_.push_back(ignore_mcu_update_on_datapoints);
}
@@ -130,56 +85,25 @@ class Tuya final : public Component, public uart::UARTDevice {
protected:
void register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func);
void dump_mcu_config_();
void handle_char_(uint8_t c);
void handle_datapoints_(const uint8_t *buffer, size_t len);
optional<TuyaDatapoint> get_datapoint_(uint8_t datapoint_id);
bool validate_message_();
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
void send_raw_command_(TuyaCommand command);
void process_command_queue_();
void send_command_(const TuyaCommand &command);
void send_empty_command_(TuyaCommandType command);
/// Store a datapoint received from the MCU and notify listeners.
void handle_datapoint_(const TuyaDatapoint &datapoint);
void mark_initialized_() { this->initialized_callback_.call(); }
const TuyaDatapoint *get_datapoint_(uint8_t datapoint_id) const;
void dump_datapoints_();
void set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, uint32_t value,
uint8_t length, bool forced);
void set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced);
void set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced);
void send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data);
void set_status_pin_();
void send_wifi_status_();
uint8_t get_wifi_status_code_();
uint8_t get_wifi_rssi_();
/// Deliver a datapoint value to the MCU over the subclass's transport.
/// The payload is borrowed for the duration of the call only.
virtual void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) = 0;
#ifdef USE_TIME
void register_local_time_sync_callback_();
void check_force_time_sync_();
void send_local_time_(bool periodic = false);
void send_gmt_time_();
time::RealTimeClock *time_id_{nullptr};
bool force_time_sync_{false};
uint8_t last_force_time_sync_minute_{0xFF}; // 0xFF: no minute seen yet
bool time_sync_callback_registered_{false};
bool gmt_time_sync_callback_registered_{false};
#endif
TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT;
bool init_failed_{false};
int init_retries_{0};
uint8_t protocol_version_ = -1;
InternalGPIOPin *status_pin_{nullptr};
int status_pin_reported_ = -1;
int reset_pin_reported_ = -1;
uint32_t last_command_timestamp_ = 0;
uint32_t last_rx_char_timestamp_ = 0;
std::unique_ptr<char[]> product_;
std::vector<TuyaDatapointListener> listeners_;
std::vector<TuyaDatapoint> datapoints_;
std::vector<uint8_t> rx_message_;
std::vector<uint8_t> ignore_mcu_update_on_datapoints_{};
std::vector<TuyaCommand> command_queue_;
optional<TuyaCommandType> expected_response_{};
uint8_t wifi_status_ = -1;
bool product_invalid_{false};
private:
CallbackManager<void()> initialized_callback_{};
};
+624
View File
@@ -0,0 +1,624 @@
#include "tuya_uart.h"
#include "esphome/core/application.h"
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#include <cctype>
#include <cstring>
#ifdef USE_NETWORK
#include "esphome/components/network/util.h"
#endif
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"
#endif
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/components/captive_portal/captive_portal.h"
#endif
namespace esphome::tuya {
ESPHOME_LOG_TAG(TAG, "tuya");
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
static const int COMMAND_DELAY = 10;
static constexpr uint32_t RECEIVE_TIMEOUT = 300;
static const int MAX_RETRIES = 5;
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
static bool network_is_connected() {
#ifdef USE_NETWORK
return network::is_connected();
#else
return false;
#endif
}
void TuyaUART::setup() {
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
#ifdef USE_TIME
if (this->force_time_sync_) {
this->register_local_time_sync_callback_();
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
[this] { this->check_force_time_sync_(); });
}
#endif
if (this->status_pin_ != nullptr) {
this->status_pin_->digital_write(false);
}
}
void TuyaUART::loop() {
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
// Holds commands back for the whole read, the idle search and its log lines included
this->handling_frame_ = true;
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_char_timestamp_,
RECEIVE_TIMEOUT);
this->handling_frame_ = false;
process_command_queue_();
}
void TuyaUART::dump_config() {
this->dump_mcu_config_();
Tuya::dump_config();
}
// Also logged again once the MCU reports its datapoints
void TuyaUART::dump_mcu_config_() {
ESP_LOGCONFIG(TAG, "Tuya:");
if (this->init_state_ != TuyaInitState::INIT_DONE) {
if (this->init_failed_) {
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
} else {
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
static_cast<uint8_t>(this->init_state_));
}
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
return;
}
this->dump_datapoints_();
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
this->reset_pin_reported_);
}
LOG_PIN(" Status Pin: ", this->status_pin_);
ESP_LOGCONFIG(TAG, " Product: '%s'",
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
}
#endif
}
bool frame_fits(const uint8_t *buf) {
const size_t len = TuyaLength::get(buf);
if (len <= MAX_FRAME_SIZE)
return true;
ESP_LOGW(TAG, "Skipped a %u byte frame, longer than the %u byte buffer", static_cast<unsigned>(len),
static_cast<unsigned>(MAX_FRAME_SIZE));
return false;
}
bool TuyaUART::handle_frame_(const uint8_t *frame, size_t len) {
// Last byte: sum of all bytes before it, header included, modulo 256
const uint8_t rx_checksum = frame[len - 1];
const uint8_t calc_checksum = sum_bytes(frame, len - 1);
if (rx_checksum != calc_checksum) {
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
return false;
}
const uint8_t version = frame[2];
const uint8_t command = frame[3];
const uint8_t *message_data = frame + TuyaLength::KNOWN_AT;
const size_t length = len - TuyaLength::KNOWN_AT - 1;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
#endif
this->handle_command_(command, version, message_data, length);
return true;
}
void TuyaUART::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
TuyaCommandType command_type = (TuyaCommandType) command;
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
this->expected_response_.reset();
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
switch (command_type) {
case TuyaCommandType::HEARTBEAT:
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
this->protocol_version_ = version;
if (buffer[0] == 0) {
ESP_LOGI(TAG, "MCU restarted");
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
}
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
this->init_state_ = TuyaInitState::INIT_PRODUCT;
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
}
break;
case TuyaCommandType::PRODUCT_QUERY: {
// check it is a valid string made up of printable characters
bool valid = true;
for (size_t i = 0; i < len; i++) {
if (!std::isprint(buffer[i])) {
valid = false;
break;
}
}
if (valid) {
this->product_ = std::make_unique<char[]>(len + 1);
memcpy(this->product_.get(), buffer, len);
} else {
this->product_.reset();
}
this->product_invalid_ = !valid;
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
this->init_state_ = TuyaInitState::INIT_CONF;
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
}
break;
}
case TuyaCommandType::CONF_QUERY: {
if (len >= 2) {
this->status_pin_reported_ = buffer[0];
this->reset_pin_reported_ = buffer[1];
}
if (this->init_state_ == TuyaInitState::INIT_CONF) {
// If mcu returned status gpio, then we can omit sending wifi state
if (this->status_pin_reported_ != -1) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
if (this->status_pin_ != nullptr) {
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
this->status_pin_reported_);
}
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
} else {
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
this->status_pin_reported_);
}
} else {
this->init_state_ = TuyaInitState::INIT_WIFI;
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
}
}
break;
}
case TuyaCommandType::WIFI_STATE:
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
}
break;
case TuyaCommandType::WIFI_SELECT:
case TuyaCommandType::WIFI_RESET: {
const bool is_select = (len >= 1);
// Send WIFI_SELECT ACK
TuyaCommand ack;
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
ack.payload.clear();
this->send_command_(ack);
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
uint8_t first = 0x00;
const char *mode_str = "EZ";
if (is_select && buffer[0] == 0x01) {
first = 0x01;
mode_str = "AP";
}
// Send WIFI_STATE response, MCU exits pairing mode
TuyaCommand st;
st.cmd = TuyaCommandType::WIFI_STATE;
st.payload.resize(1);
st.payload[0] = first;
this->send_command_(st);
st.payload[0] = 0x02;
this->send_command_(st);
st.payload[0] = 0x03;
this->send_command_(st);
st.payload[0] = 0x04;
this->send_command_(st);
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
break;
}
case TuyaCommandType::DATAPOINT_DELIVER:
break;
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
this->init_state_ = TuyaInitState::INIT_DONE;
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
this->mark_initialized_();
}
this->handle_datapoints_(buffer, len);
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
}
break;
case TuyaCommandType::DATAPOINT_QUERY:
break;
case TuyaCommandType::WIFI_TEST:
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
break;
case TuyaCommandType::WIFI_RSSI:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
break;
case TuyaCommandType::LOCAL_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_local_time_();
this->register_local_time_sync_callback_();
} else
#endif
{
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::GMT_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_gmt_time_();
if (!this->gmt_time_sync_callback_registered_) {
// tuya mcu supports time, so we let them know when our time changed
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
this->gmt_time_sync_callback_registered_ = true;
}
} else
#endif
{
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::VACUUM_MAP_UPLOAD:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
break;
case TuyaCommandType::GET_NETWORK_STATUS: {
uint8_t wifi_status = this->get_wifi_status_code_();
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
break;
}
case TuyaCommandType::EXTENDED_SERVICES: {
uint8_t subcommand = buffer[0];
switch ((TuyaExtendedServicesCommandType) subcommand) {
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
.payload = std::vector<uint8_t>{
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
ESP_LOGV(TAG, "Reset status notification enabled");
break;
}
case TuyaExtendedServicesCommandType::MODULE_RESET: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
break;
}
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
break;
}
default:
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
}
break;
}
default:
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
}
}
void TuyaUART::handle_datapoints_(const uint8_t *buffer, size_t len) {
while (len >= 4) {
TuyaDatapoint datapoint{};
datapoint.id = buffer[0];
datapoint.type = (TuyaDatapointType) buffer[1];
datapoint.value_uint = 0;
size_t data_size = encode_uint16(buffer[2], buffer[3]);
const uint8_t *data = buffer + 4;
size_t data_len = len - 4;
if (data_size > data_len) {
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
return;
}
datapoint.len = data_size;
switch (datapoint.type) {
case TuyaDatapointType::RAW:
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
{
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
}
break;
case TuyaDatapointType::BOOLEAN:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
return;
}
datapoint.value_bool = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
break;
case TuyaDatapointType::INTEGER:
if (data_size != 4) {
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
return;
}
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
break;
case TuyaDatapointType::STRING:
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
break;
case TuyaDatapointType::ENUM:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
return;
}
datapoint.value_enum = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
break;
case TuyaDatapointType::BITMASK:
switch (data_size) {
case 1:
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
break;
case 2:
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
break;
case 4:
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
return;
}
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
return;
}
len -= data_size + 4;
buffer = data + data_size;
this->handle_datapoint_(datapoint);
}
}
void TuyaUART::send_raw_command_(TuyaCommand command) {
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
uint8_t version = 0;
this->last_command_timestamp_ = millis();
switch (command.cmd) {
case TuyaCommandType::HEARTBEAT:
this->expected_response_ = TuyaCommandType::HEARTBEAT;
break;
case TuyaCommandType::PRODUCT_QUERY:
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
break;
case TuyaCommandType::CONF_QUERY:
this->expected_response_ = TuyaCommandType::CONF_QUERY;
break;
case TuyaCommandType::DATAPOINT_DELIVER:
case TuyaCommandType::DATAPOINT_QUERY:
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
break;
default:
break;
}
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
static_cast<uint8_t>(this->init_state_));
#endif
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
if (!command.payload.empty())
this->write_array(command.payload.data(), command.payload.size());
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
}
void TuyaUART::process_command_queue_() {
uint32_t now = millis();
uint32_t delay = now - this->last_command_timestamp_;
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
this->expected_response_.reset();
if (init_state_ != TuyaInitState::INIT_DONE) {
if (++this->init_retries_ >= MAX_RETRIES) {
this->init_failed_ = true;
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
} else {
this->command_queue_.erase(command_queue_.begin());
}
}
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
// A partial frame the line has gone quiet on may be kept for its late bytes; it does not hold commands back
const bool rx_idle = this->reader_.length() == 0 || now - this->last_rx_char_timestamp_ >= RECEIVE_TIMEOUT;
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && rx_idle && !this->handling_frame_ &&
!this->expected_response_.has_value()) {
this->send_raw_command_(command_queue_.front());
if (!this->expected_response_.has_value())
this->command_queue_.erase(command_queue_.begin());
}
}
void TuyaUART::send_command_(TuyaCommand command) {
command_queue_.push_back(std::move(command));
process_command_queue_();
}
void TuyaUART::send_empty_command_(TuyaCommandType command) {
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
}
void TuyaUART::send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) {
std::vector<uint8_t> buffer;
buffer.reserve(4 + len);
buffer.push_back(datapoint_id);
buffer.push_back(static_cast<uint8_t>(datapoint_type));
buffer.push_back(len >> 8);
buffer.push_back(len >> 0);
buffer.insert(buffer.end(), data, data + len);
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = std::move(buffer)});
}
void TuyaUART::set_status_pin_() {
bool is_network_ready = network_is_connected() && remote_is_connected();
this->status_pin_->digital_write(is_network_ready);
}
uint8_t TuyaUART::get_wifi_status_code_() {
uint8_t status = 0x02;
if (network_is_connected()) {
status = 0x03;
// Protocol version 3 also supports specifying when connected to "the cloud"
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
status = 0x04;
}
} else {
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
status = 0x01;
}
#endif
};
return status;
}
uint8_t TuyaUART::get_wifi_rssi_() {
#ifdef USE_WIFI
if (wifi::global_wifi_component != nullptr)
return wifi::global_wifi_component->wifi_rssi();
#endif
return 0;
}
void TuyaUART::send_wifi_status_() {
uint8_t status = this->get_wifi_status_code_();
if (status == this->wifi_status_) {
return;
}
ESP_LOGD(TAG, "Sending WiFi Status");
this->wifi_status_ = status;
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
}
#ifdef USE_TIME
void TuyaUART::register_local_time_sync_callback_() {
if (this->time_sync_callback_registered_) {
return;
}
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
this->time_sync_callback_registered_ = true;
}
void TuyaUART::check_force_time_sync_() {
ESPTime now = this->time_id_->now();
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
return;
this->last_force_time_sync_minute_ = now.minute;
this->send_local_time_(true);
}
void TuyaUART::send_local_time_(bool periodic) {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->now();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
// Tuya days starts from Monday, esphome uses Sunday as day 1
uint8_t day_of_week = now.day_of_week - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
// The forced send repeats every minute, so it stays out of the debug log
if (periodic) {
ESP_LOGV(TAG, "Sending local time");
} else {
ESP_LOGD(TAG, "Sending local time");
}
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing local time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
}
void TuyaUART::send_gmt_time_() {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->utcnow();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
ESP_LOGD(TAG, "Sending gmt time");
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing gmt time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
}
#endif
TuyaInitState TuyaUART::get_init_state() { return this->init_state_; }
} // namespace esphome::tuya
+130
View File
@@ -0,0 +1,130 @@
#pragma once
#include <cinttypes>
#include <memory>
#include <vector>
#include "tuya.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#include "esphome/core/time.h"
#endif
namespace esphome::tuya {
// Longest frame accepted, as in Tasmota; keeps the reader's positions 8 bit
static constexpr size_t MAX_FRAME_SIZE = 255;
// 55 AA, version, command, payload length (2, BE), payload, checksum
using TuyaLength = PayloadLengthU16BE<LengthField{.offset = 4, .trailer = 1}>;
/// False, with a warning, for a frame longer than the buffer
bool frame_fits(const uint8_t *buf);
using TuyaFrame = FrameFormat<FrameHeader<0x55, 0xAA>, CheckedLength<TuyaLength, TuyaLength::KNOWN_AT, frame_fits>>;
enum class TuyaCommandType : uint8_t {
HEARTBEAT = 0x00,
PRODUCT_QUERY = 0x01,
CONF_QUERY = 0x02,
WIFI_STATE = 0x03,
WIFI_RESET = 0x04,
WIFI_SELECT = 0x05,
DATAPOINT_DELIVER = 0x06,
DATAPOINT_REPORT_ASYNC = 0x07,
DATAPOINT_QUERY = 0x08,
GMT_TIME_QUERY = 0x0C,
WIFI_TEST = 0x0E,
LOCAL_TIME_QUERY = 0x1C,
DATAPOINT_REPORT_SYNC = 0x22,
DATAPOINT_REPORT_ACK = 0x23,
WIFI_RSSI = 0x24,
VACUUM_MAP_UPLOAD = 0x28,
GET_NETWORK_STATUS = 0x2B,
EXTENDED_SERVICES = 0x34,
};
enum class TuyaExtendedServicesCommandType : uint8_t {
RESET_NOTIFICATION = 0x04,
MODULE_RESET = 0x05,
UPDATE_IN_PROGRESS = 0x0A,
};
enum class TuyaInitState : uint8_t {
INIT_HEARTBEAT = 0x00,
INIT_PRODUCT,
INIT_CONF,
INIT_WIFI,
INIT_DATAPOINT,
INIT_DONE,
};
struct TuyaCommand {
TuyaCommandType cmd;
std::vector<uint8_t> payload;
};
/// Tuya MCU controller connected over UART (the standard Tuya serial protocol).
class TuyaUART final : public Tuya, public uart::UARTDevice {
public:
void setup() override;
void loop() override;
void dump_config() override;
void set_status_pin(InternalGPIOPin *status_pin) { this->status_pin_ = status_pin; }
TuyaInitState get_init_state();
#ifdef USE_TIME
void set_time_id(time::RealTimeClock *time_id) { this->time_id_ = time_id; }
void set_force_time_sync(bool force_time_sync) { this->force_time_sync_ = force_time_sync; }
#endif
protected:
void dump_mcu_config_();
/// Returns false for a frame that fails the checksum
bool handle_frame_(const uint8_t *frame, size_t len);
void handle_datapoints_(const uint8_t *buffer, size_t len);
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
void send_raw_command_(TuyaCommand command);
void process_command_queue_();
void send_command_(TuyaCommand command);
void send_empty_command_(TuyaCommandType command);
void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) override;
void set_status_pin_();
void send_wifi_status_();
uint8_t get_wifi_status_code_();
uint8_t get_wifi_rssi_();
#ifdef USE_TIME
void register_local_time_sync_callback_();
void check_force_time_sync_();
void send_local_time_(bool periodic = false);
void send_gmt_time_();
time::RealTimeClock *time_id_{nullptr};
bool force_time_sync_{false};
uint8_t last_force_time_sync_minute_{0xFF}; // 0xFF: no minute seen yet
bool time_sync_callback_registered_{false};
bool gmt_time_sync_callback_registered_{false};
#endif
TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT;
bool init_failed_{false};
int init_retries_{0};
uint8_t protocol_version_ = -1;
InternalGPIOPin *status_pin_{nullptr};
int status_pin_reported_ = -1;
int reset_pin_reported_ = -1;
uint32_t last_command_timestamp_ = 0;
uint32_t last_rx_char_timestamp_ = 0;
std::unique_ptr<char[]> product_;
std::vector<TuyaCommand> command_queue_;
optional<TuyaCommandType> expected_response_{};
uint8_t wifi_status_ = -1;
bool product_invalid_{false};
// Holds commands back while a received frame is handled
bool handling_frame_{false};
LengthFrameReader<MAX_FRAME_SIZE, TuyaFrame> reader_;
};
} // namespace esphome::tuya
+96 -1
View File
@@ -3,7 +3,7 @@ from dataclasses import dataclass, field
from logging import getLogger
import math
import re
from typing import Any
from typing import TYPE_CHECKING, Any
from esphome import automation, pins
import esphome.codegen as cg
@@ -42,8 +42,12 @@ from esphome.const import (
CONF_FLOW_CONTROL_PIN,
CONF_ID,
CONF_LAMBDA,
CONF_MODE,
CONF_NUMBER,
CONF_OPEN_DRAIN,
CONF_PORT,
CONF_PULLDOWN,
CONF_PULLUP,
CONF_RX_BUFFER_SIZE,
CONF_RX_PIN,
CONF_SEQUENCE,
@@ -60,6 +64,9 @@ import esphome.final_validate as fv
from esphome.types import ConfigType
from esphome.yaml_util import make_data_base
if TYPE_CHECKING:
from esphome.components.libretiny import HardwareUart
_LOGGER = getLogger(__name__)
CODEOWNERS = ["@esphome/core"]
@@ -333,6 +340,89 @@ CONFIG_SCHEMA = cv.All(
)
def _libretiny_hardware_uart(config: ConfigType) -> "HardwareUart | None":
"""Hardware UART the board can route the configured pins to; None if none can or the board is unknown."""
from esphome.components.libretiny import get_hardware_uarts, has_software_serial
# Pin flags make setup() use SoftwareSerial where the family has it
if has_software_serial() and any(
pin[CONF_MODE].get(flag)
for pin in (config.get(CONF_TX_PIN), config.get(CONF_RX_PIN))
if pin is not None
for flag in (CONF_OPEN_DRAIN, CONF_PULLUP, CONF_PULLDOWN)
):
return None
tx = config[CONF_TX_PIN][CONF_NUMBER] if CONF_TX_PIN in config else None
rx = config[CONF_RX_PIN][CONF_NUMBER] if CONF_RX_PIN in config else None
return next(
(
uart
for uart in get_hardware_uarts()
if tx in (None, *uart.tx_pins) and rx in (None, *uart.rx_pins)
),
None,
)
def _final_validate(config: ConfigType) -> None:
if CORE.is_libretiny:
_validate_libretiny_pins(config)
def _validate_libretiny_pins(config: ConfigType) -> None:
from esphome.components.libretiny import (
can_choose_uart_pins,
get_hardware_uarts,
get_libretiny_board,
has_software_serial,
)
# A board without pin data is matched against its default pins at boot
if not (uarts := get_hardware_uarts()):
return
board = get_libretiny_board()
uart = _libretiny_hardware_uart(config)
if uart is None:
if has_software_serial():
return
choices = "; ".join(
f"UART{u.port}: TX={'/'.join(map(str, u.tx_pins)) or 'none'}, "
f"RX={'/'.join(map(str, u.rx_pins)) or 'none'}"
for u in uarts
)
raise cv.Invalid(
f"Board {board} has no hardware UART on these pins. Pin numbers per UART: {choices}"
)
# Two entries on one port would share the Serial object, and the second begin() would move its pins
for other in fv.full_config.get().get(DOMAIN, []):
if other is config or other[CONF_ID] == config[CONF_ID]:
continue
if (
other_uart := _libretiny_hardware_uart(other)
) and other_uart.port == uart.port:
raise cv.Invalid(
f"UART {other[CONF_ID]} already uses hardware UART{uart.port} of board {board}"
)
if not uart.pin_choices:
return
# A left-out direction with no default pin is opened on an invalid pin, which hangs at boot
for key, role, choices in (
(CONF_TX_PIN, "TX", uart.tx_pin_choices),
(CONF_RX_PIN, "RX", uart.rx_pin_choices),
):
if choices and key not in config:
raise cv.Invalid(
f"UART{uart.port} of board {board} has no default {role} pin, so it needs {key}"
)
if not can_choose_uart_pins():
raise cv.Invalid(
f"Choosing the pins of UART{uart.port} on board {board} needs LibreTiny 1.12.0 or later"
)
FINAL_VALIDATE_SCHEMA = _final_validate
async def debug_to_code(config, parent):
trigger = cg.new_Pvariable(config[CONF_TRIGGER_ID], parent)
await cg.register_component(trigger, config)
@@ -426,6 +516,11 @@ async def to_code(config):
enable_serial1()
cg.add_define("USE_ESP8266_UART_SERIAL1")
if CORE.is_libretiny and (uart := _libretiny_hardware_uart(config)) is not None:
cg.add(var.set_hardware_port(uart.port))
if uart.pin_choices:
cg.add_define("USE_UART_LIBRETINY_PIN_ROUTING")
CORE.add_job(final_step)
+11
View File
@@ -90,6 +90,17 @@ class UARTDevice {
count);
}
/// Feed the waiting bytes to a LengthFrameReader; on a pass with none, gap_ms after last_rx, flush a stalled frame.
template<size_t N = 64, typename R, typename F>
void read_frames(R &reader, F &&handle, uint32_t now, uint32_t &last_rx, uint32_t gap_ms = 250) {
if (const size_t count = this->available()) {
last_rx = now;
this->read_available<N>([&reader, &handle](uint8_t c) { reader.feed(c, handle); }, count);
} else if (reader.length() != 0 && now - last_rx >= gap_ms) {
reader.flush(handle);
}
}
/// Read and drop every byte waiting in the receive buffer.
void discard_available();
@@ -25,6 +25,42 @@ static const char *const UART_TYPE[] = {
"software",
};
// Port whose default pins match, for a board codegen has no pin data for; PIN_INVALID means not configured.
static int8_t default_port(pin_size_t tx, pin_size_t rx) {
#if LT_HW_UART0
if ((tx == PIN_INVALID || tx == PIN_SERIAL0_TX) && (rx == PIN_INVALID || rx == PIN_SERIAL0_RX))
return 0;
#endif
#if LT_HW_UART1
if ((tx == PIN_INVALID || tx == PIN_SERIAL1_TX) && (rx == PIN_INVALID || rx == PIN_SERIAL1_RX))
return 1;
#endif
#if LT_HW_UART2
if ((tx == PIN_INVALID || tx == PIN_SERIAL2_TX) && (rx == PIN_INVALID || rx == PIN_SERIAL2_RX))
return 2;
#endif
return -1;
}
static SerialClass *hardware_serial(int8_t port) {
switch (port) {
#if LT_HW_UART0
case 0:
return &Serial0;
#endif
#if LT_HW_UART1
case 1:
return &Serial1;
#endif
#if LT_HW_UART2
case 2:
return &Serial2;
#endif
default:
return nullptr;
}
}
uint16_t LibreTinyUARTComponent::get_config() {
uint16_t config = 0;
@@ -49,8 +85,8 @@ uint16_t LibreTinyUARTComponent::get_config() {
}
void LibreTinyUARTComponent::setup() {
int16_t tx_pin = tx_pin_ == nullptr ? -1 : tx_pin_->get_pin();
int16_t rx_pin = rx_pin_ == nullptr ? -1 : rx_pin_->get_pin();
const pin_size_t tx_pin = this->tx_pin_ == nullptr ? PIN_INVALID : this->tx_pin_->get_pin();
const pin_size_t rx_pin = this->rx_pin_ == nullptr ? PIN_INVALID : this->rx_pin_->get_pin();
auto should_fallback_to_software_serial = [&]() -> bool {
auto has_flags = [](InternalGPIOPin *pin, const gpio::Flags mask) -> bool {
@@ -70,61 +106,49 @@ void LibreTinyUARTComponent::setup() {
return false;
};
if (false) { // NOLINT(readability-simplify-boolean-expr)
return;
}
#if LT_HW_UART0
else if ((tx_pin == -1 || tx_pin == PIN_SERIAL0_TX) && (rx_pin == -1 || rx_pin == PIN_SERIAL0_RX) &&
!should_fallback_to_software_serial()) {
this->serial_ = &Serial0;
this->hardware_idx_ = 0;
}
#endif
#if LT_HW_UART1
else if ((tx_pin == -1 || tx_pin == PIN_SERIAL1_TX) && (rx_pin == -1 || rx_pin == PIN_SERIAL1_RX) &&
!should_fallback_to_software_serial()) {
this->serial_ = &Serial1;
this->hardware_idx_ = 1;
}
#endif
#if LT_HW_UART2
else if ((tx_pin == -1 || tx_pin == PIN_SERIAL2_TX) && (rx_pin == -1 || rx_pin == PIN_SERIAL2_RX) &&
!should_fallback_to_software_serial()) {
this->serial_ = &Serial2;
this->hardware_idx_ = 2;
}
#endif
else {
#if LT_ARD_HAS_SOFTSERIAL
if (this->rx_pin_) {
this->rx_pin_->setup();
}
if (this->tx_pin_ && this->rx_pin_ != this->tx_pin_) {
this->tx_pin_->setup();
}
bool tx_inverted = tx_pin_ != nullptr && tx_pin_->is_inverted();
bool rx_inverted = rx_pin_ != nullptr && rx_pin_->is_inverted();
this->serial_ = new SoftwareSerial(rx_pin, tx_pin, rx_inverted || tx_inverted);
#else
this->serial_ = &Serial;
ESP_LOGE(TAG, " SoftwareSerial is not implemented for this chip. Only hardware pins are supported:");
#if LT_HW_UART0
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL0_TX, PIN_SERIAL0_RX);
#endif
#if LT_HW_UART1
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL1_TX, PIN_SERIAL1_RX);
#endif
#if LT_HW_UART2
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL2_TX, PIN_SERIAL2_RX);
#endif
this->mark_failed(LOG_STR("SoftwareSerial is not implemented for this chip."));
return;
#endif
}
if (this->hardware_idx_ >= 0)
// Codegen picks the port from the board's pin lists; a board it has no pin data for matches the defaults here.
if (this->hardware_idx_ < 0)
this->hardware_idx_ = default_port(tx_pin, rx_pin);
SerialClass *hardware = should_fallback_to_software_serial() ? nullptr : hardware_serial(this->hardware_idx_);
if (hardware != nullptr) {
this->serial_ = hardware;
libretiny::ensure_serial_handle(this->hardware_idx_);
this->serial_->begin(this->baud_rate_, get_config());
#ifdef USE_UART_LIBRETINY_PIN_ROUTING
// Routes a port with pin choices to the configured pins (LibreTiny 1.12+, checked in codegen). setPins()
// replaces a left-out pin (PIN_INVALID) with the port's default, so default-pin ports start as before.
hardware->begin(this->baud_rate_, this->get_config(), rx_pin, tx_pin);
#else
hardware->begin(this->baud_rate_, this->get_config());
#endif
return;
}
this->hardware_idx_ = -1;
#if LT_ARD_HAS_SOFTSERIAL
if (this->rx_pin_) {
this->rx_pin_->setup();
}
if (this->tx_pin_ && this->rx_pin_ != this->tx_pin_) {
this->tx_pin_->setup();
}
bool tx_inverted = tx_pin_ != nullptr && tx_pin_->is_inverted();
bool rx_inverted = rx_pin_ != nullptr && rx_pin_->is_inverted();
this->serial_ = new SoftwareSerial(rx_pin, tx_pin, rx_inverted || tx_inverted);
this->serial_->begin(this->baud_rate_, this->get_config());
#else
this->serial_ = &Serial;
ESP_LOGE(TAG, " SoftwareSerial is not implemented for this chip. Only hardware pins are supported:");
#if LT_HW_UART0
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL0_TX, PIN_SERIAL0_RX);
#endif
#if LT_HW_UART1
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL1_TX, PIN_SERIAL1_RX);
#endif
#if LT_HW_UART2
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL2_TX, PIN_SERIAL2_RX);
#endif
this->mark_failed(LOG_STR("SoftwareSerial is not implemented for this chip."));
#endif
}
void LibreTinyUARTComponent::dump_config() {
@@ -25,6 +25,8 @@ class LibreTinyUARTComponent final : public UARTComponent, public Component {
UARTFlushResult flush() override;
uint16_t get_config();
/// Hardware port codegen picked from the board's pin lists.
void set_hardware_port(int8_t port) { this->hardware_idx_ = port; }
HardwareSerial *get_hw_serial() { return this->serial_; }
int8_t get_hw_serial_number() { return this->hardware_idx_; }
@@ -15,6 +15,9 @@ namespace esphome::uart {
ESPHOME_LOG_TAG(TAG, "uart");
// GPIO32-47 (RP2350B) and GPIO64 (CYW43) are in no mask; a 32-bit shift by them is undefined.
static constexpr bool pin_in_mask(uint8_t pin, uint32_t mask) { return pin < 32 && (mask & (1U << pin)) != 0; }
uint16_t RP2UartComponent::get_config() {
uint16_t config = 0;
@@ -81,9 +84,9 @@ void RP2UartComponent::setup() {
if (this->tx_pin_->is_inverted()) {
ESP_LOGD(TAG, "An inverted TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
} else {
if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_0) != 0) {
if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_0)) {
tx_hw = 0;
} else if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_1) != 0) {
} else if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_1)) {
tx_hw = 1;
} else {
ESP_LOGD(TAG, "TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
@@ -95,9 +98,9 @@ void RP2UartComponent::setup() {
if (this->rx_pin_->is_inverted()) {
ESP_LOGD(TAG, "An inverted RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
} else {
if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_0) != 0) {
if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_0)) {
rx_hw = 0;
} else if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_1) != 0) {
} else if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_1)) {
rx_hw = 1;
} else {
ESP_LOGD(TAG, "RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
+88
View File
@@ -0,0 +1,88 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.i2c import CONF_I2C_ID
import esphome.config_validation as cv
from esphome.const import CONF_ADDRESS, CONF_ENABLE_PIN
import esphome.final_validate as fv
from esphome.types import ConfigType
AUTO_LOAD = ["sensor"]
CODEOWNERS = ["@NonaSuomy"]
DEPENDENCIES = ["i2c"]
DOMAIN = "vl6180x"
MULTI_CONF = True
CONF_VL6180X_ID = "vl6180x_id"
vl6180x_ns = cg.esphome_ns.namespace("vl6180x")
VL6180XComponent = vl6180x_ns.class_(
"VL6180XComponent", cg.PollingComponent, i2c.I2CDevice
)
_request_enable_pin_slot = cg.slot_counter("VL6180X_ENABLE_PIN_COUNT")
DEFAULT_ADDRESS = 0x29
def _validate_address(config: ConfigType) -> ConfigType:
# The sensor always boots at 0x29; only an enable pin lets it move elsewhere
if config[CONF_ADDRESS] != DEFAULT_ADDRESS and CONF_ENABLE_PIN not in config:
raise cv.Invalid(
f"An address other than 0x{DEFAULT_ADDRESS:02X} needs an enable_pin"
)
return config
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(VL6180XComponent),
cv.Optional(CONF_ENABLE_PIN): pins.gpio_output_pin_schema,
}
)
.extend(cv.polling_component_schema("60s"))
.extend(i2c.i2c_device_schema(DEFAULT_ADDRESS)),
_validate_address,
)
def _final_validate(config: ConfigType) -> ConfigType:
# With several sensors on one bus each needs its own enable_pin so it can be held in reset
# while the others are re-addressed, and none may stay at 0x29, or a later sibling boots at
# the same address and the re-address write reaches both chips.
addresses = [
conf[CONF_ADDRESS]
for conf in fv.full_config.get()[DOMAIN]
if conf[CONF_I2C_ID] == config[CONF_I2C_ID]
]
if len(addresses) < 2:
return config
if CONF_ENABLE_PIN not in config:
raise cv.Invalid(
"Every VL6180X on a shared I2C bus needs an enable_pin",
path=[CONF_ENABLE_PIN],
)
address = config[CONF_ADDRESS]
if address == DEFAULT_ADDRESS:
raise cv.Invalid(
f"VL6180X sensors sharing an I2C bus must all be re-addressed away "
f"from 0x{DEFAULT_ADDRESS:02X}",
path=[CONF_ADDRESS],
)
if addresses.count(address) > 1:
raise cv.Invalid(
f"Address 0x{address:02X} is used by more than one VL6180X on this bus",
path=[CONF_ADDRESS],
)
return config
FINAL_VALIDATE_SCHEMA = _final_validate
async def to_code(config: ConfigType) -> None:
var = await i2c.new_i2c_component(config)
if pin := await cg.add_pin(var.set_enable_pin, config.get(CONF_ENABLE_PIN)):
_request_enable_pin_slot()
cg.add(var.register_enable_pin(pin))
+80
View File
@@ -0,0 +1,80 @@
import esphome.codegen as cg
from esphome.components import sensor
import esphome.config_validation as cv
from esphome.const import (
CONF_DISTANCE,
CONF_GAIN,
CONF_ILLUMINANCE,
CONF_INTEGRATION_TIME,
DEVICE_CLASS_DISTANCE,
DEVICE_CLASS_ILLUMINANCE,
STATE_CLASS_MEASUREMENT,
UNIT_LUX,
UNIT_MILLIMETER,
)
import esphome.final_validate as fv
from esphome.types import ConfigType
from . import CONF_VL6180X_ID, DOMAIN, VL6180XComponent
DEPENDENCIES = ["vl6180x"]
CONF_SCALER = "scaler"
# Gain factor to the SYSALS_ANALOGUE_GAIN code
ALS_GAINS = {1: 6, 1.25: 5, 1.67: 4, 2.5: 3, 5: 2, 10: 1, 20: 0, 40: 7}
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(CONF_VL6180X_ID): cv.use_id(VL6180XComponent),
cv.Optional(CONF_DISTANCE): sensor.sensor_schema(
unit_of_measurement=UNIT_MILLIMETER,
accuracy_decimals=0,
device_class=DEVICE_CLASS_DISTANCE,
state_class=STATE_CLASS_MEASUREMENT,
).extend(
{cv.Optional(CONF_SCALER, default=1): cv.one_of(1, 2, 3, int=True)}
),
cv.Optional(CONF_ILLUMINANCE): sensor.sensor_schema(
unit_of_measurement=UNIT_LUX,
accuracy_decimals=1,
device_class=DEVICE_CLASS_ILLUMINANCE,
state_class=STATE_CLASS_MEASUREMENT,
).extend(
{
cv.Optional(CONF_GAIN, default=1): cv.enum(ALS_GAINS),
cv.Optional(CONF_INTEGRATION_TIME, default="100ms"): cv.All(
cv.positive_time_period_milliseconds,
cv.Range(
min=cv.TimePeriod(milliseconds=1),
max=cv.TimePeriod(milliseconds=512),
),
),
}
),
}
),
cv.has_at_least_one_key(CONF_DISTANCE, CONF_ILLUMINANCE),
)
FINAL_VALIDATE_SCHEMA = fv.unique_platform_key(
domain=sensor.DOMAIN,
platform=DOMAIN,
keys=(CONF_VL6180X_ID,),
message="Only one VL6180X sensor platform entry is allowed per hub",
)
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_VL6180X_ID])
sensors = sensor.sub_sensors(config)
if (distance_config := config.get(CONF_DISTANCE)) is not None:
await sensors(CONF_DISTANCE, hub.set_distance_sensor)
cg.add(hub.set_scaler(distance_config[CONF_SCALER]))
if (illuminance_config := config.get(CONF_ILLUMINANCE)) is not None:
await sensors(CONF_ILLUMINANCE, hub.set_illuminance_sensor)
gain = illuminance_config[CONF_GAIN]
time_ms = illuminance_config[CONF_INTEGRATION_TIME].total_milliseconds
# The datasheet scale is 0.32 lux per count at 1x gain and 100 ms
cg.add(hub.set_als(gain.enum_value, time_ms, 32.0 / (float(gain) * time_ms)))
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more