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
86 changed files with 2963 additions and 2738 deletions

No files matched your search

+46 -1
View File
@@ -120,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)` |
@@ -128,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
+28 -2
View File
@@ -246,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()`,
@@ -311,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
@@ -357,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:**
+1
View File
@@ -701,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
@@ -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",
+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.
@@ -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);
}
}
+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
@@ -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_;
@@ -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));
+7 -15
View File
@@ -19,8 +19,6 @@ static constexpr uint8_t MAX_ATTEMPTS = 4;
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;
// A frame arrives in one burst; after a pause this long a partly received frame is dropped.
static constexpr uint32_t RX_GAP_MS = 100;
static constexpr float MIN_TEMPERATURE_C = 16.0f;
static constexpr float MAX_TEMPERATURE_C = 31.0f;
@@ -68,21 +66,15 @@ climate::ClimateTraits PioneerWT::traits() {
void PioneerWT::loop() {
const uint32_t now = App.get_loop_component_start_time();
if (const size_t count = this->available()) {
this->last_rx_ = now;
this->read_available(
[this](uint8_t byte) {
if (const size_t len = this->reader_.feed(byte))
this->handle_frame_(this->reader_.frame(), len);
},
count);
if (this->reader_.take_checksum_error()) {
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;
}
} else if (this->reader_.partial() && now - this->last_rx_ >= RX_GAP_MS) {
// Only on an idle pass: after a slow loop the rest of the frame may already be buffered.
this->reader_.reset();
}
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.
@@ -11,31 +11,6 @@ uint16_t frame_crc(const uint8_t *frame, size_t len) {
return crc16be(frame + HEADER_SIZE, len - HEADER_SIZE, head);
}
size_t PacketReader::feed(uint8_t byte) {
if (this->pos_ == 0 && byte != 0xA5)
return 0;
if (this->pos_ == 1 && byte != 0x01) {
this->pos_ = byte == 0xA5 ? 1 : 0;
return 0;
}
this->buf_[this->pos_++] = byte;
if (this->pos_ < 8)
return 0;
const uint8_t len = this->buf_[7];
if (len < HEADER_SIZE) {
this->pos_ = 0;
return 0;
}
if (this->pos_ < len)
return 0;
this->pos_ = 0;
if (frame_crc(this->buf_.data(), len) != encode_uint16(this->buf_[8], this->buf_[9])) {
this->checksum_error_ = true;
return 0;
}
return len;
}
enum class AttrKind : uint8_t {
ATTR_KIND_UNKNOWN,
ATTR_KIND_ONE_BYTE,
@@ -128,19 +103,19 @@ bool AttributeReader::next() {
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] = 0xA5;
out[1] = 0x01;
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[7] = total;
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 + 8, frame_crc(out, total));
put_be16(out + CRC_POS, frame_crc(out, total));
return total;
}
@@ -1,16 +1,20 @@
#pragma once
#include <array>
#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;
@@ -45,28 +49,15 @@ 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);
/// Collects bytes from the serial line into complete frames with a valid checksum.
class PacketReader final {
public:
/// Feeds one byte. Returns the frame length once a complete, valid frame is in frame().
size_t feed(uint8_t byte);
const uint8_t *frame() const { return this->buf_.data(); }
/// True while part of a frame has been collected.
bool partial() const { return this->pos_ != 0; }
/// Drops a partly collected frame, so the next byte can start a new one.
void reset() { this->pos_ = 0; }
/// True once after a complete frame was dropped for a wrong checksum.
bool take_checksum_error() {
const bool error = this->checksum_error_;
this->checksum_error_ = false;
return error;
}
// 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>>>;
protected:
std::array<uint8_t, MAX_FRAME_SIZE> buf_{};
uint8_t pos_{0};
bool checksum_error_{false};
};
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 {
+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};
@@ -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
+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();
+287 -13
View File
@@ -1,11 +1,30 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <type_traits>
// Out of line, one copy: the frame readers' rare paths call each other, and GCC would add specialised clones
#if defined(__clang__)
#define ESPHOME_FRAME_READER_COLD __attribute__((noinline))
#else
#define ESPHOME_FRAME_READER_COLD __attribute__((noinline, noclone))
#endif
namespace esphome {
namespace frame_reader_detail {
// A fold, not an array, so no header table lands in RAM on ESP8266
template<uint8_t... HEADER> constexpr uint8_t header_byte(size_t i) {
size_t j = 0;
uint8_t r = 0;
((r = (j++ == i) ? HEADER : r), ...);
return r;
}
} // namespace frame_reader_detail
/// Collects fixed length binary frames of N bytes that start with the header bytes HEADER...; the binary twin of
/// LineReader. Bytes before a header are skipped; checksums are left to the caller.
template<size_t N, uint8_t... HEADER> class FrameReader {
@@ -18,11 +37,12 @@ template<size_t N, uint8_t... HEADER> class FrameReader {
/// Feed one byte; returns the completed frame, header included, valid until the next call, or nullptr.
const uint8_t *feed(uint8_t c) {
pos_t pos = this->pos_;
if (pos < HEADER_LEN && c != header_byte(pos)) {
if (pos < HEADER_LEN && c != frame_reader_detail::header_byte<HEADER...>(pos)) {
// A later byte of the broken header, or c, may start the real one
if (pos == 0)
return nullptr;
this->buf_[pos] = c;
this->replay_(pos);
return nullptr;
return this->replay_(pos);
}
this->buf_[pos++] = c;
if (pos < N) {
@@ -44,24 +64,278 @@ template<size_t N, uint8_t... HEADER> class FrameReader {
void resync() { this->replay_(N - 1); }
protected:
// A fold, not an array, so no header table lands in RAM on ESP8266
static constexpr uint8_t header_byte(size_t i) {
size_t j = 0;
uint8_t r = 0;
((r = (j++ == i) ? HEADER : r), ...);
return r;
}
// Start over and feed buf_[1..last] again; never completes a frame as last < N
void replay_(size_t last) {
// Start over and feed buf_[1..last] again; never completes a frame as last < N, so it returns nullptr, which lets
// feed() end in a tail call. Out of line, as feed() and replay_() call each other.
const uint8_t *ESPHOME_FRAME_READER_COLD replay_(size_t last) {
this->pos_ = 0;
for (size_t i = 1; i <= last; i++) {
this->feed(this->buf_[i]);
}
return nullptr;
}
uint8_t buf_[N];
pos_t pos_{0};
};
// Length rules: get() gives the whole frame length once KNOWN_AT bytes are in, or 0 to reject the header.
/// offset: where the length field starts, counted from the first header byte; trailer: the bytes after the payload
/// (checksum, footer), for a payload length only.
struct LengthField {
size_t offset;
size_t trailer = 0;
};
/// Whole-frame length: the field counts every byte of the frame, header included.
template<LengthField F> struct FrameLengthU8 {
static_assert(F.trailer == 0, "A whole-frame length has no trailer");
static constexpr size_t KNOWN_AT = F.offset + 1;
static constexpr size_t get(const uint8_t *buf) { return buf[F.offset]; }
};
template<LengthField F> struct FrameLengthU16BE {
static_assert(F.trailer == 0, "A whole-frame length has no trailer");
static constexpr size_t KNOWN_AT = F.offset + 2;
static constexpr size_t get(const uint8_t *buf) { return (size_t(buf[F.offset]) << 8) | buf[F.offset + 1]; }
};
template<LengthField F> struct FrameLengthU16LE {
static_assert(F.trailer == 0, "A whole-frame length has no trailer");
static constexpr size_t KNOWN_AT = F.offset + 2;
static constexpr size_t get(const uint8_t *buf) { return buf[F.offset] | (size_t(buf[F.offset + 1]) << 8); }
};
/// Payload length: the field counts the payload right after it.
template<LengthField F> struct PayloadLengthU8 {
static constexpr size_t KNOWN_AT = F.offset + 1;
static constexpr size_t get(const uint8_t *buf) { return KNOWN_AT + buf[F.offset] + F.trailer; }
};
template<LengthField F> struct PayloadLengthU16BE {
static constexpr size_t KNOWN_AT = F.offset + 2;
static constexpr size_t get(const uint8_t *buf) {
return KNOWN_AT + FrameLengthU16BE<LengthField{.offset = F.offset}>::get(buf) + F.trailer;
}
};
template<LengthField F> struct PayloadLengthU16LE {
static constexpr size_t KNOWN_AT = F.offset + 2;
static constexpr size_t get(const uint8_t *buf) {
return KNOWN_AT + FrameLengthU16LE<LengthField{.offset = F.offset}>::get(buf) + F.trailer;
}
};
/// A frame type that always has LEN bytes.
template<size_t LEN> struct FrameFixedLength {
static_assert(LEN >= 2, "A fixed length frame has at least 2 bytes");
static constexpr size_t KNOWN_AT = 1;
static constexpr size_t get(const uint8_t * /*buf*/) { return LEN; }
};
/// Wraps a length rule: CHECK(buf) runs once AT bytes are in, and a header it fails gives length 0 (rejected).
template<class LENGTH, size_t AT, bool (*CHECK)(const uint8_t *)> struct CheckedLength {
static_assert(AT >= LENGTH::KNOWN_AT, "AT must cover the length field");
static constexpr size_t KNOWN_AT = AT;
static size_t get(const uint8_t *buf) { return CHECK(buf) ? LENGTH::get(buf) : 0; }
};
/// The shortest frame of a FrameFormat, when that is more than its header and length field.
template<size_t LEN> struct FrameMinLength {
static constexpr size_t VALUE = LEN;
};
namespace frame_reader_detail {
// The length of a FrameFixedLength rule, 0 for every other rule
template<class LENGTH> constexpr size_t FIXED_LENGTH = 0;
template<size_t LEN> constexpr size_t FIXED_LENGTH<FrameFixedLength<LEN>> = LEN;
template<class LENGTH, size_t AT, bool (*CHECK)(const uint8_t *)>
constexpr size_t FIXED_LENGTH<CheckedLength<LENGTH, AT, CHECK>> = FIXED_LENGTH<LENGTH>;
} // namespace frame_reader_detail
/// The bytes every frame of a FrameFormat starts with.
template<uint8_t... BYTES> struct FrameHeader {
static constexpr size_t LEN = sizeof...(BYTES);
static_assert(LEN >= 1 && LEN <= 8, "A FrameHeader has 1 to 8 bytes");
static constexpr uint8_t byte(size_t i) { return frame_reader_detail::header_byte<BYTES...>(i); }
};
/// One frame type for LengthFrameReader: a FrameHeader, a length rule from above and an optional FrameMinLength.
template<class HEADER, class LENGTH, class MIN = FrameMinLength<0>> struct FrameFormat {
using Length = LENGTH;
static constexpr size_t HEADER_LEN = HEADER::LEN;
static constexpr uint8_t FIRST = HEADER::byte(0);
// Bytes collected when the length is checked
static constexpr size_t MIN_LEN = std::max<size_t>({LENGTH::KNOWN_AT, HEADER_LEN, 2});
// A shorter length is not a frame
static constexpr size_t SHORTEST = std::max(MIN_LEN, MIN::VALUE);
static_assert(LENGTH::KNOWN_AT == 1 || LENGTH::KNOWN_AT > HEADER_LEN, "The length field must follow the header");
static constexpr uint8_t header_byte(size_t i) { return HEADER::byte(i); }
};
/// Collects binary frames that give their own length, of up to N bytes, in one or more FrameFormats; the first byte
/// picks the format, so each format needs a different first header byte. Bytes before a header are skipped. A length
/// that ends the frame before its length field, or is longer than N, is not a frame, and the reader looks for a
/// header after its first byte. Checksums and footers are left to the caller, which passes a handler that returns
/// false for a frame it rejects:
///
/// this->reader_.feed(c, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
///
/// For frames of one fixed size, FrameReader is smaller.
template<size_t N, class... FORMATS> class LengthFrameReader {
using pos_t = std::conditional_t<(N <= 0xFF), uint8_t, uint16_t>;
static_assert(sizeof...(FORMATS) >= 1, "LengthFrameReader takes at least one FrameFormat");
static_assert(N >= 2 && N <= 1024,
"LengthFrameReader size out of range"); // flush_() copies a partial frame on the stack
static constexpr bool distinct_first() {
const uint8_t first[] = {FORMATS::FIRST...};
for (size_t i = 0; i < sizeof...(FORMATS); i++) {
for (size_t j = i + 1; j < sizeof...(FORMATS); j++) {
if (first[i] == first[j])
return false;
}
}
return true;
}
static_assert(distinct_first(), "Each FrameFormat needs a different first header byte");
static_assert(((FORMATS::SHORTEST <= N) && ...), "N must hold the shortest frame of every FrameFormat");
static_assert(((frame_reader_detail::FIXED_LENGTH<typename FORMATS::Length> == 0 ||
(frame_reader_detail::FIXED_LENGTH<typename FORMATS::Length> >= FORMATS::SHORTEST &&
frame_reader_detail::FIXED_LENGTH<typename FORMATS::Length> <= N)) &&
...),
"A fixed length must hold the header and fit in N");
public:
/// Feed one byte; calls handle(frame, length) for each frame it completes, header included. A rejected frame
/// (handle returns false) is searched for frames inside it and after it, which go to handle the same way.
/// handle must not feed this reader again: the frame and the bytes held behind it live in its buffer.
template<class F> void __attribute__((always_inline)) feed(uint8_t c, F &&handle) {
// Most bytes are in the middle of a frame whose length is known, and not its last byte
const pos_t pos = this->pos_;
if (pos + 1u < this->end_) {
this->buf_[pos] = c;
this->pos_ = pos + 1;
} else if (const size_t len = this->feed_edge_(c)) {
this->drain_(len, handle);
}
}
/// For a partial frame left too long without a byte: when it holds frames that handle takes, which a corrupt length
/// can cause, give it up and pass them on; otherwise keep it, as a slow UART may still deliver the rest. A UART
/// component gets this from UARTDevice::read_frames().
template<class F> void flush(F &&handle) {
// held_end_ marks a partial frame already searched; new bytes move pos_ past it
if (this->pos_ != 0 && this->held_end_ != this->pos_)
this->flush_(handle);
}
/// Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
size_t length() const { return this->pos_; }
/// Forget the partial frame, for a request/response protocol starting a new exchange.
void reset() {
this->pos_ = 0;
this->end_ = 0;
this->held_end_ = 0;
}
protected:
// Hands each frame (len bytes at buf_) to handle, then goes on after a handled frame or from the second byte of a
// rejected one
template<class F> bool ESPHOME_FRAME_READER_COLD drain_(size_t len, F &handle) {
bool handled = false;
while (len != 0) {
const bool ok = handle(this->buf_, len);
handled |= ok;
len = this->replay_(ok ? len : 1, this->held_end_);
}
this->held_end_ = 0;
return handled;
}
// Searches the partial frame for frames; when handle takes none, puts the partial frame back and marks it searched
template<class F> void ESPHOME_FRAME_READER_COLD flush_(F &handle) {
const pos_t pos = this->pos_;
const pos_t end = this->end_;
uint8_t saved[N];
std::memcpy(saved, this->buf_, pos);
while (this->pos_ != 0) {
// A partial frame left behind the handed over ones is searched on the next idle pass
if (this->drain_(this->replay_(1, this->pos_), handle))
return;
}
std::memcpy(this->buf_, saved, pos);
this->pos_ = pos;
this->end_ = end;
this->held_end_ = pos;
}
// Every byte but the middle of a frame; returns the length of a completed frame, or 0
size_t ESPHOME_FRAME_READER_COLD feed_edge_(uint8_t c) {
const pos_t pos = this->pos_;
if (pos == 0) {
const bool header = ((c == FORMATS::FIRST) || ...);
if (header) {
this->buf_[0] = c;
this->pos_ = 1;
}
return 0;
}
if constexpr (sizeof...(FORMATS) == 1) {
return this->feed_as_<FORMATS...>(pos, c);
} else {
const uint8_t first = this->buf_[0];
size_t len = 0;
(void) ((first == FORMATS::FIRST && ((len = this->feed_as_<FORMATS>(pos, c)), true)) || ...);
return len;
}
}
template<class F> size_t feed_as_(pos_t pos, uint8_t c) {
if (pos < F::HEADER_LEN && c != F::header_byte(pos)) {
// A later byte of the broken header, or c, may start the real one
this->buf_[pos] = c;
return this->replay_(1, pos + 1);
}
this->buf_[pos++] = c;
if (pos == F::MIN_LEN) {
const size_t len = F::Length::get(this->buf_);
if (len < F::SHORTEST || len > N)
return this->replay_(1, pos);
this->end_ = len;
}
if (pos == this->end_) {
this->pos_ = 0;
this->end_ = 0;
this->held_end_ = pos;
return pos;
}
this->pos_ = pos;
return 0;
}
// Start over and feed buf_[from..to) again; writes stay behind the read position. On a completed frame, moves the
// bytes not fed yet right behind it, for drain_(), and returns its length; 0 otherwise.
size_t ESPHOME_FRAME_READER_COLD replay_(size_t from, size_t to) {
this->pos_ = 0;
this->end_ = 0;
for (size_t i = from; i < to; i++) {
const size_t len = this->feed_edge_(this->buf_[i]);
if (len == 0)
continue;
// A nested replay may already have put bytes of its own behind the frame
const size_t held = this->held_end_;
const size_t rest = to - i - 1;
std::memmove(this->buf_ + held, this->buf_ + i + 1, rest);
this->held_end_ = held + rest;
return len;
}
return 0;
}
// Before buf_, so they stay within a short load offset of the reader when N is large
pos_t pos_{0};
// Length of the frame being collected once its length is known; 0 otherwise
pos_t end_{0};
// End of a held frame plus the bytes after it not fed yet, set when a frame completes; or a searched partial frame
pos_t held_end_{0};
uint8_t buf_[N];
};
} // namespace esphome
#undef ESPHOME_FRAME_READER_COLD
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies:
esphome/micro-decoder:
version: 0.4.0
esphome/micro-flac:
version: 0.3.0
version: 0.3.1
esphome/micro-mp3:
version: 0.4.0
esphome/micro-opus:
@@ -20,6 +20,12 @@ static constexpr uint8_t FRAME_30[30] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB
static constexpr uint8_t ULTRASONIC_NOISY[] = {0x12, 0xFF, 0x07, 0xA1, 0xA7, 0x34, 0xFF, 0xFF, 0x07, 0xA1, 0xA7,
0x00, 0xFF, 0x07, 0xA1, 0xA7, 0x56, 0xFF, 0x07, 0xA1, 0xA7};
// Pioneer WT shaped frames (A5 01 header, whole-frame length at byte 7) of 12, 20 and 12 bytes among noise
static constexpr uint8_t LENGTH_FRAMES[] = {0x00, 0xA5, 0x01, 0x01, 0x23, 0x00, 0xA5, 0x00, 0x0C, 0x11, 0x22, 0x33,
0x44, 0xA5, 0x01, 0x01, 0x23, 0x00, 0xA5, 0x00, 0x14, 0x11, 0x22, 0x33,
0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0x7E, 0xA5, 0x01,
0x01, 0x23, 0x00, 0xA5, 0x00, 0x0C, 0x11, 0x22, 0x33, 0x44};
// --- LineReader: one GGA sentence fed byte by byte ---
static void LineReader_NmeaLine(benchmark::State &state) {
@@ -93,4 +99,32 @@ static void FrameReader_UltrasonicNoisy(benchmark::State &state) {
}
BENCHMARK(FrameReader_UltrasonicNoisy);
// --- LengthFrameReader: frames of different lengths among noise ---
// A5 01, whole-frame length at 7
using PioneerFormat = FrameFormat<FrameHeader<0xA5, 0x01>, FrameLengthU8<LengthField{.offset = 7}>>;
static void LengthFrameReader_MixedFrames(benchmark::State &state) {
LengthFrameReader<255, PioneerFormat> reader;
const uint8_t *bytes = LENGTH_FRAMES;
uint32_t frames = 0;
auto handle = [&frames](const uint8_t *frame, size_t /*len*/) {
benchmark::DoNotOptimize(frame);
frames++;
return true;
};
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(LENGTH_FRAMES); j++)
reader.feed(bytes[j], handle);
}
benchmark::DoNotOptimize(frames);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LengthFrameReader_MixedFrames);
} // namespace esphome::benchmarks
@@ -0,0 +1,19 @@
esphome:
name: test
esp32:
board: esp32dev
external_components:
- source:
type: local
path: ../../../components/tuya/components
fake_tuya_transport:
id: my_tuya
switch:
- platform: tuya
tuya_id: my_tuya
name: Fake Switch
switch_datapoint: 1
@@ -0,0 +1,25 @@
"""End-to-end test of the base-class split through the config pipeline."""
from collections.abc import Callable
from pathlib import Path
from esphome.components.tuya import FILTER_SOURCE_FILES
from esphome.core import CORE
def test_non_uart_transport_loads_base_only(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("fake_transport.yaml"))
# The fake transport and the tuya switch resolve through the base class
assert "fake_tuya_transport::FakeTuyaTransport" in main_cpp
assert "tuya::TuyaSwitch" in main_cpp
# The UART transport is neither loaded nor instantiated...
assert "uart" not in CORE.loaded_integrations
assert "TuyaUART" not in main_cpp
# ...and its sources are excluded from the build
assert sorted(FILTER_SOURCE_FILES()) == ["tuya_uart.cpp", "tuya_uart.h"]
+6 -1
View File
@@ -3,7 +3,7 @@
import pytest
from esphome import config_validation as cv
from esphome.components.tuya import CONF_FORCE_TIME_SYNC, CONFIG_SCHEMA
from esphome.components.tuya import AUTO_LOAD, CONF_FORCE_TIME_SYNC, CONFIG_SCHEMA
from esphome.const import CONF_TIME_ID
@@ -21,3 +21,8 @@ def test_force_time_sync_accepts_time_id() -> None:
def test_force_time_sync_requires_time_id() -> None:
with pytest.raises(cv.Invalid, match="force_time_sync requires time_id"):
CONFIG_SCHEMA({CONF_FORCE_TIME_SYNC: True})
def test_auto_load_requests_uart_for_probe_and_config() -> None:
assert AUTO_LOAD(None) == ["uart"]
assert AUTO_LOAD({"id": "x"}) == ["uart"]
@@ -165,9 +165,9 @@ TEST_F(AirtonSerialFrameTest, StalledPartialFrameReleasedAfterGap) {
this->uart_.push_rx(a3_frame());
this->loop_at_(1000);
EXPECT_EQ(this->sut_.mode, climate::CLIMATE_MODE_OFF);
this->loop_at_(1049);
this->loop_at_(1249);
EXPECT_EQ(this->sut_.mode, climate::CLIMATE_MODE_OFF);
this->loop_at_(1050);
this->loop_at_(1250);
this->expect_a3_applied_();
}
+294
View File
@@ -140,4 +140,298 @@ TEST(FrameReaderTest, SixteenBitIndex) {
EXPECT_EQ(frames[0][299], 0x42);
}
// Feeds bytes and collects every frame the reader hands over, rejecting those reject() picks.
template<size_t N, class... F, class R>
static Frames feed_all(LengthFrameReader<N, F...> &reader, const Bytes &input, R reject) {
Frames frames;
auto handle = [&](const uint8_t *frame, size_t len) {
frames.emplace_back(frame, frame + len);
return !reject(frames.back());
};
for (uint8_t c : input)
reader.feed(c, handle);
return frames;
}
template<size_t N, class... F> static Frames feed_all(LengthFrameReader<N, F...> &reader, const Bytes &input) {
return feed_all(reader, input, [](const Bytes & /*frame*/) { return false; });
}
// pioneer_wt: A5 01, one byte at 7 holds the whole length
using OneByte = FrameFormat<FrameHeader<0xA5, 0x01>, FrameLengthU8<LengthField{.offset = 7}>>;
// tuya: 55 AA, version, command, payload length (2, BE), payload, checksum
using TwoByteBE = FrameFormat<FrameHeader<0x55, 0xAA>, PayloadLengthU16BE<LengthField{.offset = 4, .trailer = 1}>>;
// ld24xx command and data frames: header (4), payload length (2, LE), payload, footer (4)
using LdCmd =
FrameFormat<FrameHeader<0xFD, 0xFC, 0xFB, 0xFA>, PayloadLengthU16LE<LengthField{.offset = 4, .trailer = 4}>>;
using LdData =
FrameFormat<FrameHeader<0xF4, 0xF3, 0xF2, 0xF1>, PayloadLengthU16LE<LengthField{.offset = 4, .trailer = 4}>>;
// ld2410s short frame: 6E, always 5 bytes
using LdShort = FrameFormat<FrameHeader<0x6E>, FrameFixedLength<5>>;
// Small format for the recovery tests: A5, one byte at 1 holds the whole length
using Small = FrameFormat<FrameHeader<0xA5>, FrameLengthU8<LengthField{.offset = 1}>>;
static_assert(sizeof(LengthFrameReader<255, OneByte>) == 258);
static_assert(sizeof(LengthFrameReader<300, TwoByteBE>) == 306);
TEST(LengthFrameReaderTest, OneByteLength) {
LengthFrameReader<16, OneByte> reader;
EXPECT_EQ(feed_all(reader, {0x00, 0xA5, 0x01, 0x10, 0x11, 0x12, 0x13, 0x00, 0x09, 0x42}),
(Frames{{0xA5, 0x01, 0x10, 0x11, 0x12, 0x13, 0x00, 0x09, 0x42}}));
}
TEST(LengthFrameReaderTest, TwoByteBigEndianPayloadLength) {
LengthFrameReader<300, TwoByteBE> reader;
// Payload of 0x0102 = 258 bytes: 265 in all, past an 8-bit index
Bytes input{0x55, 0xAA, 0x03, 0x07, 0x01, 0x02};
input.resize(265, 0x33);
Frames frames = feed_all(reader, input);
ASSERT_EQ(frames.size(), 1u);
EXPECT_EQ(frames[0].size(), 265u);
// Too long for N: not a frame
EXPECT_EQ(feed_all(reader, {0x55, 0xAA, 0x03, 0x07, 0x01, 0x30}), Frames{});
EXPECT_EQ(reader.length(), 0u);
}
TEST(LengthFrameReaderTest, LittleEndianLengthsAboveAByte) {
// Whole-frame length 0x0102 = 258, low byte first
LengthFrameReader<300, FrameFormat<FrameHeader<0xA5>, FrameLengthU16LE<LengthField{.offset = 1}>>> whole;
Bytes input{0xA5, 0x02, 0x01};
input.resize(258, 0x33);
Frames frames = feed_all(whole, input);
ASSERT_EQ(frames.size(), 1u);
EXPECT_EQ(frames[0].size(), 258u);
// Payload length 0x0100 = 256 after the field, then a 1 byte trailer: 260 in all
LengthFrameReader<300, FrameFormat<FrameHeader<0xA5>, PayloadLengthU16LE<LengthField{.offset = 1, .trailer = 1}>>>
payload;
input = {0xA5, 0x00, 0x01};
input.resize(260, 0x44);
frames = feed_all(payload, input);
ASSERT_EQ(frames.size(), 1u);
EXPECT_EQ(frames[0].size(), 260u);
}
TEST(LengthFrameReaderTest, TwoFormatsPickedByFirstByte) {
LengthFrameReader<32, LdCmd, LdData> reader;
const Bytes cmd{0xFD, 0xFC, 0xFB, 0xFA, 0x02, 0x00, 0xA0, 0x01, 0x04, 0x03, 0x02, 0x01};
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x01, 0x00, 0x55, 0xF8, 0xF7, 0xF6, 0xF5};
Bytes input{0x00};
input.insert(input.end(), data.begin(), data.end());
input.insert(input.end(), cmd.begin(), cmd.end());
EXPECT_EQ(feed_all(reader, input), (Frames{data, cmd}));
}
TEST(LengthFrameReaderTest, FixedAndLengthFormatsTogether) {
LengthFrameReader<32, LdShort, LdData> reader;
const Bytes small{0x6E, 0x01, 0x02, 0x03, 0x62};
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x00, 0x00, 0xF8, 0xF7, 0xF6, 0xF5};
Bytes input = small;
input.insert(input.end(), data.begin(), data.end());
input.insert(input.end(), small.begin(), small.end());
EXPECT_EQ(feed_all(reader, input), (Frames{small, data, small}));
}
TEST(LengthFrameReaderTest, BrokenHeaderRealigns) {
LengthFrameReader<32, LdCmd, LdData> reader;
// FD FC then F4 breaks the command header and starts a data header
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x00, 0x00, 0xF8, 0xF7, 0xF6, 0xF5};
Bytes input{0xFD, 0xFC};
input.insert(input.end(), data.begin(), data.end());
EXPECT_EQ(feed_all(reader, input), (Frames{data}));
}
TEST(LengthFrameReaderTest, BrokenHeaderHoldsAShorterFrameOfAnotherFormat) {
// FD FC FB then 77 breaks the command header; its replay finds a whole 2 byte FC frame and keeps the 77 behind it
LengthFrameReader<32, LdCmd, FrameFormat<FrameHeader<0xFC>, FrameFixedLength<2>>> reader;
EXPECT_EQ(feed_all(reader, {0xFD, 0xFC, 0xFB, 0x77}), (Frames{{0xFC, 0xFB}}));
EXPECT_EQ(reader.length(), 0u);
// The held 77 was noise, so the next frame is found normally
EXPECT_EQ(feed_all(reader, {0xFC, 0x01}), (Frames{{0xFC, 0x01}}));
}
TEST(LengthFrameReaderTest, RejectedFrameHoldsFramesOfBothFormats) {
LengthFrameReader<32, LdShort, Small> reader;
// A rejected 12 byte A5 frame holds a whole short frame, a whole A5 frame and the start of another
auto reject_12 = [](const Bytes &frame) { return frame.size() == 12; };
EXPECT_EQ(feed_all(reader, {0xA5, 0x0C, 0x6E, 0x01, 0x02, 0x03, 0x62, 0xA5, 0x03, 0x09, 0xA5, 0x05}, reject_12),
(Frames{{0xA5, 0x0C, 0x6E, 0x01, 0x02, 0x03, 0x62, 0xA5, 0x03, 0x09, 0xA5, 0x05},
{0x6E, 0x01, 0x02, 0x03, 0x62},
{0xA5, 0x03, 0x09}}));
EXPECT_EQ(reader.length(), 2u);
EXPECT_EQ(feed_all(reader, {0x11, 0x22, 0x33}), (Frames{{0xA5, 0x05, 0x11, 0x22, 0x33}}));
}
TEST(LengthFrameReaderTest, BadLengthRealignsAfterFirstByte) {
LengthFrameReader<8, Small> reader;
// 0x01 ends the frame before its length byte and 0x09 is longer than 8: neither is a frame.
// The second A5 inside the bad one starts the real frame.
EXPECT_EQ(feed_all(reader, {0xA5, 0x01, 0xA5, 0x09, 0xA5, 0x04, 0x01, 0x02}), (Frames{{0xA5, 0x04, 0x01, 0x02}}));
}
TEST(LengthFrameReaderTest, LengthByteCanStartHeader) {
LengthFrameReader<8, FrameFormat<FrameHeader<0x09>, FrameLengthU8<LengthField{.offset = 1}>>> reader;
// Length 9 is longer than 8, so the length byte becomes the next header
EXPECT_EQ(feed_all(reader, {0x09, 0x09, 0x03, 0x07}), (Frames{{0x09, 0x03, 0x07}}));
}
TEST(LengthFrameReaderTest, LengthTracksPartialFrame) {
LengthFrameReader<8, Small> reader;
EXPECT_EQ(feed_all(reader, {0x01, 0xA5, 0x05}), Frames{});
EXPECT_EQ(reader.length(), 2u);
EXPECT_EQ(feed_all(reader, {0x10, 0x20, 0x30}), (Frames{{0xA5, 0x05, 0x10, 0x20, 0x30}}));
EXPECT_EQ(reader.length(), 0u);
}
TEST(LengthFrameReaderTest, RejectedFrameIsSearchedForAHeader) {
LengthFrameReader<8, Small> reader;
// The A5 taken as a header was payload; the real frame starts at the second A5
auto reject_long = [](const Bytes &frame) { return frame.size() == 5; };
EXPECT_EQ(feed_all(reader, {0xA5, 0x05, 0x00, 0xA5, 0x04}, reject_long), (Frames{{0xA5, 0x05, 0x00, 0xA5, 0x04}}));
EXPECT_EQ(reader.length(), 2u);
EXPECT_EQ(feed_all(reader, {0x10, 0x20}, reject_long), (Frames{{0xA5, 0x04, 0x10, 0x20}}));
}
TEST(LengthFrameReaderTest, RejectionRecoversEveryFrameInside) {
LengthFrameReader<16, Small> reader;
// The 9 byte frame is rejected; the two frames inside it are handed over too, and a partial one is kept
auto reject_9 = [](const Bytes &frame) { return frame.size() == 9; };
EXPECT_EQ(feed_all(reader, {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04}, reject_9),
(Frames{{0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04}, {0xA5, 0x03, 0x01}, {0xA5, 0x02}}));
EXPECT_EQ(reader.length(), 2u);
EXPECT_EQ(feed_all(reader, {0x01, 0x02}), (Frames{{0xA5, 0x04, 0x01, 0x02}}));
}
TEST(LengthFrameReaderTest, RecoveredFrameRejectedTooIsSearched) {
LengthFrameReader<16, Small> reader;
// The 9 byte frame holds a 4 byte candidate, which holds a 3 byte one; both outer ones are rejected
auto reject_outer = [](const Bytes &frame) { return frame.size() != 3; };
EXPECT_EQ(
feed_all(reader, {0xA5, 0x09, 0xA5, 0x04, 0xA5, 0x03, 0x01, 0x02, 0x03}, reject_outer),
(Frames{{0xA5, 0x09, 0xA5, 0x04, 0xA5, 0x03, 0x01, 0x02, 0x03}, {0xA5, 0x04, 0xA5, 0x03}, {0xA5, 0x03, 0x01}}));
EXPECT_EQ(reader.length(), 0u);
}
TEST(LengthFrameReaderTest, FlushHandsOverFramesHeldBack) {
LengthFrameReader<16, Small> reader;
Frames seen;
auto handle = [&seen](const uint8_t *frame, size_t len) {
seen.emplace_back(frame, frame + len);
return true;
};
// A corrupt length of 15 holds back two complete frames until the caller gives up on the partial one
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x03, 0x09})
reader.feed(c, handle);
EXPECT_EQ(seen, Frames{});
EXPECT_EQ(reader.length(), 9u);
reader.flush(handle);
EXPECT_EQ(seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x03, 0x09}}));
EXPECT_EQ(reader.length(), 0u);
reader.flush(handle); // nothing collected: nothing to do
EXPECT_EQ(seen.size(), 2u);
}
TEST(LengthFrameReaderTest, FlushKeepsASlowFrameUntilTheRestArrives) {
LengthFrameReader<16, Small> reader;
Frames seen;
auto handle = [&seen](const uint8_t *frame, size_t len) {
seen.emplace_back(frame, frame + len);
return true;
};
for (uint8_t c : {0xA5, 0x06, 0xA5, 0x03})
reader.feed(c, handle);
reader.flush(handle);
EXPECT_EQ(seen, Frames{});
EXPECT_EQ(reader.length(), 4u);
for (uint8_t c : {0x01, 0x02})
reader.feed(c, handle);
EXPECT_EQ(seen, (Frames{{0xA5, 0x06, 0xA5, 0x03, 0x01, 0x02}}));
}
TEST(LengthFrameReaderTest, FlushKeepsASlowFrameBehindTheFramesItHandsOver) {
LengthFrameReader<16, Small> reader;
Frames seen;
auto handle = [&seen](const uint8_t *frame, size_t len) {
seen.emplace_back(frame, frame + len);
return true;
};
// A corrupt length holds a whole frame, then the start of a slow one
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x05, 0x11})
reader.feed(c, handle);
reader.flush(handle);
reader.flush(handle);
EXPECT_EQ(seen, (Frames{{0xA5, 0x04, 0x01, 0x02}}));
EXPECT_EQ(reader.length(), 3u);
for (uint8_t c : {0x22, 0x33})
reader.feed(c, handle);
EXPECT_EQ(seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x05, 0x11, 0x22, 0x33}}));
}
TEST(LengthFrameReaderTest, FlushKeepsTheFrameWhenEveryFrameInsideIsRejected) {
LengthFrameReader<16, Small> reader;
size_t calls = 0;
auto reject = [&calls](const uint8_t *, size_t) {
calls++;
return false;
};
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x03, 0x09})
reader.feed(c, reject);
reader.flush(reject);
EXPECT_EQ(calls, 1u);
EXPECT_EQ(reader.length(), 5u);
// Searched once until a new byte comes
reader.flush(reject);
EXPECT_EQ(calls, 1u);
}
TEST(LengthFrameReaderTest, ResetForgetsThePartialFrame) {
LengthFrameReader<16, Small> reader;
EXPECT_EQ(feed_all(reader, {0xA5, 0x05, 0x11}), Frames{});
reader.reset();
EXPECT_EQ(reader.length(), 0u);
EXPECT_EQ(feed_all(reader, {0xA5, 0x03, 0x22}), (Frames{{0xA5, 0x03, 0x22}}));
}
TEST(LengthFrameReaderTest, IdleAfterHandledFrameFindsNothingInIt) {
LengthFrameReader<16, Small> reader;
Frames seen;
auto handle = [&seen](const uint8_t *frame, size_t len) {
seen.emplace_back(frame, frame + len);
return true;
};
// A handled frame whose payload looks like a frame of its own, then noise
for (uint8_t c : {0xA5, 0x06, 0xA5, 0x03, 0x01, 0x02, 0x00})
reader.feed(c, handle);
reader.flush(handle);
EXPECT_EQ(seen, (Frames{{0xA5, 0x06, 0xA5, 0x03, 0x01, 0x02}}));
}
// A custom rule known at the first byte that reads the buffer builds (only FrameFixedLength is checked up front)
struct FirstByteLength {
static constexpr size_t KNOWN_AT = 1;
static constexpr size_t get(const uint8_t *buf) { return buf[0]; }
};
TEST(LengthFrameReaderTest, CustomRuleKnownAtTheFirstByte) {
LengthFrameReader<8, FrameFormat<FrameHeader<0x03>, FirstByteLength>> reader;
EXPECT_EQ(feed_all(reader, {0x03, 0x01, 0x02, 0x03}), (Frames{{0x03, 0x01, 0x02}}));
}
// A5, payload length at 1, payload, checksum; a frame has at least 2 payload bytes
using MinTwo =
FrameFormat<FrameHeader<0xA5>, PayloadLengthU8<LengthField{.offset = 1, .trailer = 1}>, FrameMinLength<5>>;
TEST(LengthFrameReaderTest, LengthBelowTheMinimumIsRejectedAtTheHeader) {
LengthFrameReader<16, MinTwo> reader;
EXPECT_EQ(feed_all(reader, {0xA5, 0x00, 0xA5, 0x02, 0x10, 0x20, 0x30}), (Frames{{0xA5, 0x02, 0x10, 0x20, 0x30}}));
}
static bool second_byte_not_ff(const uint8_t *buf) { return buf[1] != 0xFF; }
// A5, a byte that must not be FF, payload length at 2, payload
using Checked =
FrameFormat<FrameHeader<0xA5>, CheckedLength<PayloadLengthU8<LengthField{.offset = 2}>, 3, second_byte_not_ff>>;
TEST(LengthFrameReaderTest, CheckedLengthRejectsABadHeader) {
LengthFrameReader<16, Checked> reader;
EXPECT_EQ(feed_all(reader, {0xA5, 0xFF, 0x01, 0xA5, 0x00, 0x01, 0x42}), (Frames{{0xA5, 0x00, 0x01, 0x42}}));
}
} // namespace esphome::core::testing
@@ -137,9 +137,15 @@ TEST_F(DalyBmsRequestCycleTest, PartialFrameHoldsTheNextRequest) {
loop_at(this->bms_, 1020);
loop_at(this->bms_, 1080);
EXPECT_EQ(request_count(this->uart_), 1u);
loop_at(this->bms_, 1220);
loop_at(this->bms_, 1270);
ASSERT_EQ(request_count(this->uart_), 2u);
EXPECT_EQ(last_request(this->uart_), 0x91);
// The kept bytes must not merge with the reply into a frame that passes the checksum
receive(this->uart_, {0xA5, 0x01, 0x91, 0x08, 0x0C, 0x82, 0x01, 0x0C, 0x40, 0x02, 0x00, 0x00, 0x1C});
loop_at(this->bms_, 1280);
loop_at(this->bms_, 1340);
ASSERT_EQ(request_count(this->uart_), 3u);
EXPECT_EQ(last_request(this->uart_), 0x92);
}
// More than seven probes take more than one temperature frame: the next cycle waits for all of them.
@@ -176,4 +176,23 @@ TEST_F(LD2410SStartTest, GapAcrossWrapFullRange) {
this->check_starts_on_first_pass_(START_GAP_ACROSS_WRAP, 0xFFFFFFFF);
}
// A short data frame inside a bad command frame inside a bad data frame is still read, so the link holds
TEST_F(LD2410SWriteTest, FrameInsideTwoNestedBadFramesKeepsTheLink) {
uint32_t now = START_FAR_FROM_WRAP;
for (int pass = 0; pass < 20; pass++, now += STEP_MS) {
this->loop_at_(now);
if (!this->uart_.commands.empty() && this->uart_.commands.back() == 0x00FE && this->uart_.available() == 0)
break;
}
ASSERT_EQ(this->uart_.commands, INIT_COMMANDS);
ASSERT_FALSE(this->radar_.status_has_warning());
std::vector<uint8_t> bytes = {0xF4, 0xF3, 0xF2, 0xF1, 0x20, 0x00, 0xFD, 0xFC, 0xFB, 0xFA, 0x07, 0x00};
bytes.insert(bytes.end(), {0x6E, 0x02, 0x64, 0x00, 0x62});
bytes.resize(42, 0x00);
this->uart_.queue(bytes);
this->loop_at_(now + 3000);
this->loop_at_(now + 6000);
EXPECT_FALSE(this->radar_.status_has_warning());
}
} // namespace esphome::ld2410s::testing
+17 -9
View File
@@ -1,4 +1,5 @@
#pragma once
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <vector>
@@ -14,26 +15,32 @@
namespace esphome::ld2450::testing {
// Mock UART component to satisfy UARTDevice parent requirement.
// Mock UART component; bytes in rx are what the hub reads.
class MockUARTComponent : public uart::UARTComponent {
public:
void write_array(const uint8_t *data, size_t len) override {}
MOCK_METHOD(bool, read_array, (uint8_t *data, size_t len), (override));
bool read_array(uint8_t *data, size_t len) override {
if (this->rx.size() < len)
return false;
std::copy(this->rx.begin(), this->rx.begin() + len, data);
this->rx.erase(this->rx.begin(), this->rx.begin() + len);
return true;
}
size_t available() override { return this->rx.size(); }
MOCK_METHOD(bool, peek_byte, (uint8_t *data), (override));
MOCK_METHOD(size_t, available, (), (override));
MOCK_METHOD(uart::UARTFlushResult, flush, (), (override));
MOCK_METHOD(void, check_logger_conflict, (), (override));
#if defined(USE_ESP8266) || defined(USE_ESP32)
void load_settings(bool dump_config) override {}
#endif // USE_ESP8266 || USE_ESP32
std::vector<uint8_t> rx;
};
// Expose protected members for testing.
class TestableLD2450 : public LD2450Component {
public:
using LD2450Component::buffer_data_;
using LD2450Component::bluetooth_on_;
using LD2450Component::buffer_pos_;
using LD2450Component::bytes_since_frame_;
using LD2450Component::get_timeout_status_;
using LD2450Component::invalid_frames_;
@@ -42,7 +49,7 @@ class TestableLD2450 : public LD2450Component {
using LD2450Component::link_state_;
using LD2450Component::mac_address_;
using LD2450Component::open_link_grace_;
using LD2450Component::readline_;
using LD2450Component::reader_;
using LD2450Component::timeout_;
using LD2450Component::version_;
using LD2450Component::zone_config_;
@@ -51,10 +58,11 @@ class TestableLD2450 : public LD2450Component {
using LD2450Component::pref_;
#endif
// Delivers data through the UART parent, which must be a MockUARTComponent, and one pass of loop()
void feed(const std::vector<uint8_t> &data) {
for (uint8_t byte : data) {
this->readline_(byte);
}
auto &rx = static_cast<MockUARTComponent *>(this->parent_)->rx;
rx.insert(rx.end(), data.begin(), data.end());
this->loop();
}
};
+4 -16
View File
@@ -1,4 +1,3 @@
#include <algorithm>
#include <functional>
#include <iterator>
#include <string>
@@ -7,7 +6,6 @@
namespace esphome::ld2450::testing {
using ::testing::_;
using ::testing::NiceMock;
namespace {
@@ -20,14 +18,6 @@ constexpr uint32_t NOT_LOST = 0xFFFFFFFFu;
class LD2450LinkTest : public ::testing::TestWithParam<uint32_t> {
protected:
void SetUp() override {
ON_CALL(this->mock_uart_, available()).WillByDefault([this]() { return this->rx_.size(); });
ON_CALL(this->mock_uart_, read_array(_, _)).WillByDefault([this](uint8_t *data, size_t len) {
if (this->rx_.size() < len)
return false;
std::copy(this->rx_.begin(), this->rx_.begin() + len, data);
this->rx_.erase(this->rx_.begin(), this->rx_.begin() + len);
return true;
});
this->ld2450_.set_uart_parent(&this->mock_uart_);
this->ld2450_.set_link_timeout(LINK_TIMEOUT_MS);
// As setup() leaves them, without its boot restart
@@ -41,8 +31,7 @@ class LD2450LinkTest : public ::testing::TestWithParam<uint32_t> {
/// One pass of the main loop at t0_ + `at`, with `bytes` arriving at the UART first.
void pass_(uint32_t at, const std::vector<uint8_t> &bytes = {}) {
LoopBlockingGuard clock{nullptr, nullptr, this->t0_ + at};
this->rx_.insert(this->rx_.end(), bytes.begin(), bytes.end());
this->ld2450_.loop();
this->ld2450_.feed(bytes);
}
void frame_(uint32_t at) { this->pass_(at, make_periodic_frame()); }
/// Call `action` with the loop clock at t0_ + `at`.
@@ -74,7 +63,6 @@ class LD2450LinkTest : public ::testing::TestWithParam<uint32_t> {
const uint32_t t0_ = GetParam();
NiceMock<MockUARTComponent> mock_uart_;
TestableLD2450 ld2450_;
std::vector<uint8_t> rx_;
};
INSTANTIATE_TEST_SUITE_P(ClockStart, LD2450LinkTest, ::testing::Values(10000u, 0xFFFFF000u),
@@ -101,11 +89,11 @@ TEST_P(LD2450LinkTest, AckFramesDoNotKeepTheLinkAlive) {
TEST_P(LD2450LinkTest, InvalidInputIsCountedButDoesNotKeepTheLinkAlive) {
this->frame_(0);
EXPECT_FALSE(this->ld2450_.bytes_since_frame_);
EXPECT_FALSE(this->ld2450_.bytes_since_frame_());
EXPECT_EQ(this->ld2450_.invalid_frames_, 0u);
// Bytes that never start a header are skipped by the parser, so only the frames with a bad footer are counted
this->pass_(300, {0x01, 0x02, 0x03, 0x04, 0x55, 0xCC});
EXPECT_TRUE(this->ld2450_.bytes_since_frame_);
EXPECT_TRUE(this->ld2450_.bytes_since_frame_());
EXPECT_EQ(this->ld2450_.invalid_frames_, 0u);
auto bad_footer = make_periodic_frame();
bad_footer[bad_footer.size() - 1] = 0xAB;
@@ -114,7 +102,7 @@ TEST_P(LD2450LinkTest, InvalidInputIsCountedButDoesNotKeepTheLinkAlive) {
EXPECT_EQ(this->ld2450_.invalid_frames_, 2u);
EXPECT_EQ(this->lost_at_(501, 2 * LINK_TIMEOUT_MS), LINK_TIMEOUT_MS);
this->frame_(LINK_TIMEOUT_MS + 100);
EXPECT_FALSE(this->ld2450_.bytes_since_frame_);
EXPECT_FALSE(this->ld2450_.bytes_since_frame_());
EXPECT_EQ(this->ld2450_.invalid_frames_, 0u);
}
+1 -1
View File
@@ -35,7 +35,7 @@ TEST_F(LD2450MacAckTest, BluetoothOffAckClearsStoredMac) {
ASSERT_EQ(this->mac_str_(), "81:2C:62:BE:C9:96");
this->ld2450_.feed(make_mac_ack(ld24xx::NO_MAC));
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_FALSE(this->ld2450_.bluetooth_on_);
EXPECT_THAT(this->ld2450_.mac_address_, ::testing::Each(0));
}
+32 -89
View File
@@ -7,7 +7,7 @@ class LD2450ReadlineTest : public ::testing::Test {
void SetUp() override {
this->ld2450_.set_uart_parent(&this->mock_uart_);
// Ensure clean state
ASSERT_EQ(this->ld2450_.buffer_pos_, 0);
ASSERT_EQ(this->ld2450_.reader_.length(), 0u);
}
MockUARTComponent mock_uart_;
@@ -20,20 +20,20 @@ TEST_F(LD2450ReadlineTest, ValidPeriodicFrame) {
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
// After a complete valid frame, buffer should be reset
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
TEST_F(LD2450ReadlineTest, ValidCommandAckFrame) {
auto frame = make_ack_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
TEST_F(LD2450ReadlineTest, BackToBackPeriodicFrames) {
auto frame = make_periodic_frame();
for (int i = 0; i < 5; i++) {
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0) << "Frame " << i << " not processed";
EXPECT_EQ(this->ld2450_.reader_.length(), 0u) << "Frame " << i << " not processed";
}
}
@@ -41,91 +41,34 @@ TEST_F(LD2450ReadlineTest, BackToBackMixedFrames) {
auto periodic = make_periodic_frame();
auto ack = make_ack_frame();
this->ld2450_.feed(periodic);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
this->ld2450_.feed(ack);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
this->ld2450_.feed(periodic);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
// --- Garbage then valid frame tests ---
// --- Noise then a frame ---
TEST_F(LD2450ReadlineTest, GarbageThenValidFrame) {
// Garbage bytes never open the buffer; a valid frame that follows is parsed as usual.
std::vector<uint8_t> garbage = {0x01, 0x02, 0x03, 0x42, 0x99};
this->ld2450_.feed(garbage);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
// Footer from the valid frame resyncs the parser
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
// --- Footer-based resynchronization tests ---
TEST_F(LD2450ReadlineTest, FooterInGarbageResyncs) {
// Garbage containing a periodic frame footer (0x55 0xCC) triggers
// a buffer reset, allowing the next frame to be parsed cleanly.
std::vector<uint8_t> garbage_with_footer = {0x01, 0x02, 0x03, 0x04, 0x55, 0xCC};
this->ld2450_.feed(garbage_with_footer);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0); // Footer reset the buffer
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, CmdFooterInGarbageResyncs) {
// Garbage containing a command frame footer (04 03 02 01) also resyncs.
std::vector<uint8_t> garbage_with_footer = {0x10, 0x20, 0x30, 0x40, 0x04, 0x03, 0x02, 0x01};
this->ld2450_.feed(garbage_with_footer);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
// --- Overflow recovery tests ---
TEST_F(LD2450ReadlineTest, OverflowResetsBuffer) {
// Fill the buffer to capacity with filler that won't match any footer.
// MAX_LINE_LENGTH is 45, usable is 44. The 45th byte triggers overflow.
std::vector<uint8_t> overflow_data(MAX_LINE_LENGTH, 0x11);
this->ld2450_.feed(overflow_data);
// After overflow, buffer_pos_ resets to 0 (via the < 4 early return path)
EXPECT_LT(this->ld2450_.buffer_pos_, 4);
}
TEST_F(LD2450ReadlineTest, OverflowThenValidFrame) {
// Overflow, then a valid frame should be processed.
std::vector<uint8_t> overflow_data(MAX_LINE_LENGTH, 0x11);
this->ld2450_.feed(overflow_data);
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, BufferLargeEnoughForDesyncedFooter) {
// The key fix: the buffer (45) is large enough that a desynced periodic frame's
// footer (at most 30 bytes into the stream) will land inside the buffer before overflow.
// Simulate starting 10 bytes into a periodic frame, then a full frame follows.
std::vector<uint8_t> mid_frame = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39};
// Then a complete periodic frame whose footer will land at position 40 (10 + 30),
// well within the buffer size of 45.
auto frame = make_periodic_frame();
mid_frame.insert(mid_frame.end(), frame.begin(), frame.end());
this->ld2450_.feed(mid_frame);
// The footer from the frame should have triggered a reset
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
TEST_F(LD2450ReadlineTest, NoiseIsNotBufferedAndTheNextFrameParses) {
// Plain bytes, footer bytes of both frame types, a run longer than the buffer, the tail of a frame
const std::vector<std::vector<uint8_t>> noises = {
{0x01, 0x02, 0x03, 0x42, 0x99},
{0x01, 0x02, 0x03, 0x04, 0x55, 0xCC},
{0x10, 0x20, 0x30, 0x40, 0x04, 0x03, 0x02, 0x01},
std::vector<uint8_t>(MAX_LINE_LENGTH, 0x11),
{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39},
};
for (const auto &noise : noises) {
this->ld2450_.feed(noise);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
this->ld2450_.feed(make_periodic_frame());
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
}
TEST_F(LD2450ReadlineTest, SimulatedRestartThenFrames) {
// Simulate LD2450 restart: burst of garbage followed by valid periodic frames.
// The garbage + first frame should fit in the buffer so the footer resyncs.
std::vector<uint8_t> restart_noise = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, // 8 bytes of mid-frame data
};
@@ -134,11 +77,11 @@ TEST_F(LD2450ReadlineTest, SimulatedRestartThenFrames) {
restart_noise.insert(restart_noise.end(), frame.begin(), frame.end());
this->ld2450_.feed(restart_noise);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
// Subsequent frames should work normally
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
// --- Frame payloads that look like footers ---
@@ -154,13 +97,13 @@ TEST_F(LD2450ReadlineTest, CmdFooterBytesInPeriodicPayloadDoNotEndTheFrame) {
frame[7] = 0x01;
this->ld2450_.feed(frame);
EXPECT_EQ(frames, 1);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
// The parser is still in step: the next frames are handled as usual
this->ld2450_.feed(make_ack_frame());
this->ld2450_.feed(make_periodic_frame());
EXPECT_EQ(frames, 2);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
TEST_F(LD2450ReadlineTest, BogusLengthFieldResyncsOnTheNextHeader) {
@@ -172,7 +115,7 @@ TEST_F(LD2450ReadlineTest, BogusLengthFieldResyncsOnTheNextHeader) {
stream.insert(stream.end(), frame.begin(), frame.end());
this->ld2450_.feed(stream);
EXPECT_EQ(frames, 1);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
TEST_F(LD2450ReadlineTest, LargestLengthFieldDoesNotWrapToIncomplete) {
@@ -185,7 +128,7 @@ TEST_F(LD2450ReadlineTest, LargestLengthFieldDoesNotWrapToIncomplete) {
stream.insert(stream.end(), frame.begin(), frame.end());
this->ld2450_.feed(stream);
EXPECT_EQ(frames, 1);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
TEST_F(LD2450ReadlineTest, MixedHeaderPrefixNeverOpensAFrame) {
@@ -195,16 +138,16 @@ TEST_F(LD2450ReadlineTest, MixedHeaderPrefixNeverOpensAFrame) {
// picks the command header, so the periodic bytes do not continue it and the buffer restarts on AA
std::vector<uint8_t> stream = {0xFD, 0xFF, 0x03, 0x00};
this->ld2450_.feed(stream);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
// The reverse mix is rejected the same way
this->ld2450_.feed({0xAA, 0xFC, 0xFB, 0xFA});
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
// A real frame right after is still parsed
this->ld2450_.feed(make_periodic_frame());
EXPECT_EQ(frames, 1);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
}
} // namespace esphome::ld2450::testing
+3 -3
View File
@@ -39,13 +39,13 @@ class LD2450ShortAckTest : public ::testing::Test {
TEST_F(LD2450ShortAckTest, ShortVersionAckDoesNotChangeTheVersion) {
this->ld2450_.feed(make_short_version_ack());
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
for (uint8_t byte : this->ld2450_.version_) {
EXPECT_EQ(byte, 0);
}
this->ld2450_.feed(make_version_ack());
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(std::memcmp(this->ld2450_.version_, VERSION_BYTES, sizeof(VERSION_BYTES)), 0);
}
@@ -56,7 +56,7 @@ TEST_F(LD2450ShortAckTest, ShortTargetModeAckDoesNotChangeTheSwitch) {
multi_target.publish_state(true);
this->ld2450_.feed(make_short_target_mode_ack());
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_TRUE(multi_target.state);
this->ld2450_.feed(make_target_mode_ack(0x01));
+14 -17
View File
@@ -63,13 +63,12 @@ TEST_F(LD2450ZoneAckTest, CmdFooterBytesInZonePayloadDoNotTruncateAck) {
std::vector<uint8_t> coords(24, 0);
std::memcpy(coords.data() + zone * 8, COORDINATES, sizeof(COORDINATES));
const auto frame = make_zone_ack(coords);
std::memset(this->ld2450_.buffer_data_, 0xEE, MAX_LINE_LENGTH);
const size_t split = 12 + zone * 8 + 4;
this->ld2450_.feed(std::vector<uint8_t>(frame.begin(), frame.begin() + split));
EXPECT_EQ(this->ld2450_.buffer_pos_, split) << "zone " << static_cast<int>(zone);
EXPECT_EQ(this->ld2450_.reader_.length(), split) << "zone " << static_cast<int>(zone);
this->ld2450_.feed(std::vector<uint8_t>(frame.begin() + split, frame.end()));
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
for (uint8_t i = 0; i < MAX_ZONES; i++) {
if (i == zone) {
expect_zone(this->ld2450_, i, 772, 258, 1500, 3000);
@@ -83,7 +82,7 @@ TEST_F(LD2450ZoneAckTest, CmdFooterBytesInZonePayloadDoNotTruncateAck) {
TEST_F(LD2450ZoneAckTest, CompleteZoneAckWithoutEmbeddedFooter) {
this->set_all_zones_(100, 200, 300, 400);
this->ld2450_.feed(make_zone_ack({}));
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
this->expect_all_zones_(0, 0, 0, 0);
}
@@ -93,7 +92,7 @@ TEST_F(LD2450ZoneAckTest, FailedZoneQueryAckDoesNotWaitForCoordinates) {
frame[6] = 0xC1;
frame[8] = 0x01;
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
this->expect_all_zones_(100, 200, 300, 400);
}
@@ -108,7 +107,7 @@ TEST_F(LD2450ZoneAckTest, ValidZoneAckWithEmbeddedFooterAndHeaderIsNotResynced)
ASSERT_TRUE(std::equal(frame.begin(), frame.begin() + 36, stream.begin()));
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
expect_zone(this->ld2450_, 0, 772, 258, -771, -1285);
expect_zone(this->ld2450_, 1, 30, 449, 0, 1);
expect_zone(this->ld2450_, 2, 100, 200, 1500, 3000);
@@ -117,7 +116,7 @@ TEST_F(LD2450ZoneAckTest, ValidZoneAckWithEmbeddedFooterAndHeaderIsNotResynced)
TEST_F(LD2450ZoneAckTest, TruncatedZoneAckThenCompleteZoneAckRecovers) {
this->ld2450_.feed(make_truncated_zone_ack());
this->ld2450_.feed(make_complete_zone_ack());
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
expect_zone(this->ld2450_, 0, 100, 200, 1500, 3000);
}
@@ -131,7 +130,7 @@ TEST_F(LD2450ZoneAckTest, TruncatedZoneAckThenPeriodicFrameIsParsed) {
// The truncated ACK is not decoded; the periodic frame is recovered through the data header.
EXPECT_EQ(frames, 1);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
expect_zone(this->ld2450_, 0, 100, 200, 300, 400);
}
@@ -139,7 +138,7 @@ TEST_F(LD2450ZoneAckTest, TruncatedZoneAckThenShortAckThenCompleteZoneAckRecover
this->ld2450_.feed(make_truncated_zone_ack());
this->ld2450_.feed(make_disable_conf_ack());
this->ld2450_.feed(make_complete_zone_ack());
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
expect_zone(this->ld2450_, 0, 100, 200, 1500, 3000);
}
@@ -150,10 +149,9 @@ TEST_F(LD2450ZoneAckTest, ShortAckInRetainedSuffixIsDispatchedOnResync) {
// Ten bytes of the next zone ACK bring the buffer to 40 bytes without a footer.
this->ld2450_.feed(std::vector<uint8_t>(complete.begin(), complete.begin() + 10));
// The short ACK was replayed and consumed; only the new zone ACK prefix remains.
EXPECT_EQ(this->ld2450_.buffer_pos_, 10);
EXPECT_EQ(this->ld2450_.buffer_data_[6], 0xC1);
EXPECT_EQ(this->ld2450_.reader_.length(), 10u);
this->ld2450_.feed(std::vector<uint8_t>(complete.begin() + 10, complete.end()));
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
expect_zone(this->ld2450_, 0, 100, 200, 1500, 3000);
}
@@ -166,21 +164,20 @@ TEST_F(LD2450ZoneAckTest, MultipleCompleteFramesInRetainedSuffixAreDrained) {
const auto enable_ack = make_ack_frame();
stream.insert(stream.end(), enable_ack.begin(), enable_ack.end());
this->ld2450_.feed(stream);
EXPECT_EQ(this->ld2450_.buffer_pos_, 39); // the C1 header still claims the buffer
EXPECT_EQ(this->ld2450_.reader_.length(), 39u); // the C1 header still claims the buffer
// The 40th byte triggers the resync; both buffered ACKs are drained, leaving only this byte.
const auto complete = make_complete_zone_ack();
this->ld2450_.feed({complete[0]});
EXPECT_EQ(this->ld2450_.buffer_pos_, 1);
EXPECT_EQ(this->ld2450_.buffer_data_[0], 0xFD);
EXPECT_EQ(this->ld2450_.reader_.length(), 1u);
this->ld2450_.feed(std::vector<uint8_t>(complete.begin() + 1, complete.end()));
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
expect_zone(this->ld2450_, 0, 100, 200, 1500, 3000);
}
TEST_F(LD2450ZoneAckTest, PeriodicFooterBytesInZonePayloadDoNotEndTheAck) {
// Zone 0 x1 is -13227 (0xCC55 little endian): its bytes 55 CC are the periodic frame footer
this->ld2450_.feed(make_zone_ack({0x55, 0xCC, 0xC8, 0x00, 0xDC, 0x05, 0xB8, 0x0B}));
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
expect_zone(this->ld2450_, 0, -13227, 200, 1500, 3000);
}
+23 -6
View File
@@ -1,4 +1,5 @@
#pragma once
#include <algorithm>
#include <cstdint>
#include <vector>
#include <gmock/gmock.h>
@@ -6,30 +7,46 @@
#include "esphome/components/ld2460/ld2460.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart_component.h"
#include "esphome/core/application.h"
namespace esphome::ld2460::testing {
// Mock UART component to satisfy UARTDevice parent requirement.
// Mock UART component; bytes in rx are what the hub reads.
class MockUARTComponent : public uart::UARTComponent {
public:
MOCK_METHOD(void, write_array, (const uint8_t *data, size_t len), (override));
MOCK_METHOD(bool, read_array, (uint8_t *data, size_t len), (override));
bool read_array(uint8_t *data, size_t len) override {
if (this->rx.size() < len)
return false;
std::copy(this->rx.begin(), this->rx.begin() + len, data);
this->rx.erase(this->rx.begin(), this->rx.begin() + len);
return true;
}
size_t available() override { return this->rx.size(); }
MOCK_METHOD(bool, peek_byte, (uint8_t *data), (override));
MOCK_METHOD(size_t, available, (), (override));
MOCK_METHOD(uart::UARTFlushResult, flush, (), (override));
MOCK_METHOD(void, check_logger_conflict, (), (override));
#if defined(USE_ESP8266) || defined(USE_ESP32)
void load_settings(bool dump_config) override {}
#endif
std::vector<uint8_t> rx;
};
class TestableLD2460 : public LD2460Component {
public:
// Delivers data through the UART parent, which must be a MockUARTComponent, and one pass of loop()
void feed(const std::vector<uint8_t> &data) {
for (uint8_t byte : data) {
this->readline_(byte);
}
auto &rx = static_cast<MockUARTComponent *>(this->parent_)->rx;
rx.insert(rx.end(), data.begin(), data.end());
this->loop();
}
// One pass of loop() at the given loop time, with whatever bytes are waiting
void loop_at(uint32_t now) {
LoopBlockingGuard{nullptr, nullptr, now};
this->loop();
}
InstallationMode installation_mode() const { return this->installation_mode_; }
};
struct Point {
@@ -54,9 +54,8 @@ TEST_F(LD2460ReadlineTest, FooterBytesInsideGarbage) {
EXPECT_FLOAT_EQ(this->count_.state, 1);
}
TEST_F(LD2460ReadlineTest, OverflowThenValidFrame) {
this->ld2460_.feed(std::vector<uint8_t>(MAX_LINE_LENGTH + 8, 0x11));
// The frame right after the overflow lands behind leftover bytes; the header resync skips them
TEST_F(LD2460ReadlineTest, NoiseThenValidFrame) {
this->ld2460_.feed(std::vector<uint8_t>(MAX_FRAME_LENGTH + 8, 0x11));
this->ld2460_.feed(make_periodic_frame());
EXPECT_FLOAT_EQ(this->count_.state, 1);
EXPECT_NEAR(this->x_[0].state, 1.5f, 0.001f);
@@ -154,6 +153,22 @@ TEST_F(LD2460ReadlineTest, HeaderBytesInsidePayload) {
EXPECT_NEAR(this->y_[0].state, -359.8f, 0.01f);
}
TEST_F(LD2460ReadlineTest, FooterBytesInsidePayload) {
// The target bytes F8 F7 F6 F5 repeat the data footer; the length field still ends the frame
this->ld2460_.feed(make_periodic_frame({{static_cast<int16_t>(0xF7F8), static_cast<int16_t>(0xF5F6)}, {10, 20}}));
EXPECT_FLOAT_EQ(this->count_.state, 2);
EXPECT_NEAR(this->x_[1].state, 1.0f, 0.001f);
}
TEST_F(LD2460ReadlineTest, LengthTooLongFrameInside) {
// A header whose length runs past the next frame; that frame is found inside it
this->ld2460_.feed({0xFD, 0xFC, 0xFB, 0xFA, 0x0A, 0x1F, 0x00});
this->ld2460_.feed(make_ack_frame(2));
this->ld2460_.feed(make_periodic_frame());
EXPECT_FLOAT_EQ(this->count_.state, 1);
EXPECT_NEAR(this->angle_[0].state, 56.89f, 0.05f);
}
TEST_F(LD2460ReadlineTest, PartialTargetRejected) {
// 13 bytes of payload is not a whole number of 4-byte targets
std::vector<uint8_t> frame = {0xF4, 0xF3, 0xF2, 0xF1, 0x04, 0x0D, 0x00, 0x0F, 0x00, 0xF8, 0xF7, 0xF6, 0xF5};
@@ -219,4 +234,17 @@ TEST_F(LD2460ReadlineTest, HeaderLikeGarbageThenMaxTargets) {
EXPECT_NEAR(this->x_[0].state, 1.1f, 0.001f);
}
TEST_F(LD2460ReadlineTest, AckBehindCorruptLengthIsHandledAfterSilence) {
// A command header claiming 31 bytes, then a whole installation mode ACK, then nothing
std::vector<uint8_t> bytes{0xFD, 0xFC, 0xFB, 0xFA, 0x0A, 0x1F, 0x00};
const auto ack = make_ack_frame(2);
bytes.insert(bytes.end(), ack.begin(), ack.end());
auto &rx = this->mock_uart_.rx;
rx.insert(rx.end(), bytes.begin(), bytes.end());
this->ld2460_.loop_at(1000);
EXPECT_EQ(this->ld2460_.installation_mode(), InstallationMode::INSTALLATION_MODE_SIDE);
this->ld2460_.loop_at(1000 + 250);
EXPECT_EQ(this->ld2460_.installation_mode(), InstallationMode::INSTALLATION_MODE_TOP);
}
} // namespace esphome::ld2460::testing
@@ -1,152 +0,0 @@
#include <cstdint>
#include <cstring>
#include <vector>
#include <gtest/gtest.h>
#include "esphome/components/ld24xx/ld24xx.h"
namespace esphome::ld24xx::testing {
namespace {
constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
constexpr uint8_t DATA_FRAME_SIZE = 12; // header, four payload bytes, footer
constexpr size_t BUFFER_SIZE = 40;
// Command frame around the payload
std::vector<uint8_t> make_cmd_frame(const std::vector<uint8_t> &payload) {
std::vector<uint8_t> frame(std::begin(CMD_FRAME_HEADER), std::end(CMD_FRAME_HEADER));
frame.push_back(payload.size());
frame.push_back(0x00);
frame.insert(frame.end(), payload.begin(), payload.end());
frame.insert(frame.end(), std::begin(CMD_FRAME_FOOTER), std::end(CMD_FRAME_FOOTER));
return frame;
}
std::vector<uint8_t> make_data_frame(uint8_t fill) {
std::vector<uint8_t> frame(std::begin(DATA_FRAME_HEADER), std::end(DATA_FRAME_HEADER));
frame.insert(frame.end(), DATA_FRAME_SIZE - 2 * HEADER_FOOTER_SIZE, fill);
frame.insert(frame.end(), std::begin(DATA_FRAME_FOOTER), std::end(DATA_FRAME_FOOTER));
return frame;
}
} // namespace
// Data frames are fixed size, command frames carry their count, as in the radar components
class LD24xxFrameSplitterTest : public ::testing::Test {
protected:
void feed_(const std::vector<uint8_t> &bytes) {
for (uint8_t byte : bytes) {
feed_frame_byte(
this->buffer_, this->pos_, byte, DATA_FRAME_HEADER,
[](const uint8_t *buffer, uint8_t count) -> uint32_t {
if (count < HEADER_FOOTER_SIZE) {
return 0;
}
return buffer[0] == DATA_FRAME_HEADER[0] ? DATA_FRAME_SIZE : cmd_frame_length(buffer, count);
},
[this](uint8_t frame_len) { return this->handle_frame_(frame_len); }, [this]() { this->drops_++; });
}
}
bool handle_frame_(uint8_t frame_len) {
const uint8_t *footer = this->buffer_[0] == DATA_FRAME_HEADER[0] ? DATA_FRAME_FOOTER : CMD_FRAME_FOOTER;
if (!validate_header_footer(footer, &this->buffer_[frame_len - HEADER_FOOTER_SIZE])) {
return false;
}
this->frames_.emplace_back(this->buffer_, this->buffer_ + frame_len);
return true;
}
uint8_t buffer_[BUFFER_SIZE];
uint8_t pos_{0};
std::vector<std::vector<uint8_t>> frames_;
int drops_{0};
};
TEST_F(LD24xxFrameSplitterTest, FooterBytesInThePayloadDoNotEndTheFrame) {
auto frame = make_cmd_frame({0x61, 0x01, 0x00, 0x00, 0x04, 0x03, 0x02, 0x01, 0x55});
this->feed_(frame);
ASSERT_EQ(this->frames_.size(), 1u);
EXPECT_EQ(this->frames_[0], frame);
EXPECT_EQ(this->pos_, 0);
EXPECT_EQ(this->drops_, 0);
}
TEST_F(LD24xxFrameSplitterTest, BytesBeforeAHeaderAreNeverBuffered) {
this->feed_({0x00, 0x11, 0xFC, 0xFB, 0xFA, 0x04});
EXPECT_EQ(this->pos_, 0);
this->feed_(make_data_frame(0x22));
ASSERT_EQ(this->frames_.size(), 1u);
EXPECT_EQ(this->frames_[0], make_data_frame(0x22));
}
TEST_F(LD24xxFrameSplitterTest, AHeaderRestartsWhenItsBytesStopMatching) {
// F3 cannot continue the command header, and FD after FC starts it over
this->feed_({0xFD, 0xF3, 0xFD, 0xFC, 0xFD, 0xFC, 0xFB, 0xFA, 0x00, 0x00});
EXPECT_EQ(this->pos_, 6) << "only the header that matched through and its count are buffered";
this->feed_({0x04, 0x03, 0x02, 0x01});
ASSERT_EQ(this->frames_.size(), 1u);
EXPECT_EQ(this->frames_[0], make_cmd_frame({}));
EXPECT_EQ(this->drops_, 0);
}
TEST_F(LD24xxFrameSplitterTest, ImpossibleCountsAreDroppedAndTheNextFrameParsed) {
// 0xFFF6 totals 65536, which must not wrap to 0
this->feed_({0xFD, 0xFC, 0xFB, 0xFA, 0xF6, 0xFF});
this->feed_({0xFD, 0xFC, 0xFB, 0xFA, 0xFF, 0xFF});
EXPECT_EQ(this->drops_, 2);
EXPECT_EQ(this->pos_, 0);
this->feed_(make_data_frame(0x33));
ASSERT_EQ(this->frames_.size(), 1u);
EXPECT_EQ(this->frames_[0], make_data_frame(0x33));
}
TEST_F(LD24xxFrameSplitterTest, AFrameCaughtInsideADroppedFrameIsReplayed) {
// The count reaches 20 bytes in, past the whole frame that follows
std::vector<uint8_t> bytes = {0xFD, 0xFC, 0xFB, 0xFA, 0x0A, 0x00, 0x61, 0x01};
auto inner = make_data_frame(0x44);
bytes.insert(bytes.end(), inner.begin(), inner.end());
this->feed_(bytes);
EXPECT_EQ(this->drops_, 1);
ASSERT_EQ(this->frames_.size(), 1u);
EXPECT_EQ(this->frames_[0], inner);
EXPECT_EQ(this->pos_, 0);
}
TEST_F(LD24xxFrameSplitterTest, EveryWholeFrameLeftByADropIsDrained) {
// The window holds two whole data frames and the start of a third
std::vector<uint8_t> bytes = {0xFD, 0xFC, 0xFB, 0xFA, 0x18, 0x00, 0x61, 0x01};
for (uint8_t fill : {0x55, 0x66}) {
auto inner = make_data_frame(fill);
bytes.insert(bytes.end(), inner.begin(), inner.end());
}
bytes.insert(bytes.end(), {0xF4, 0xF3});
this->feed_(bytes);
EXPECT_EQ(this->drops_, 1);
ASSERT_EQ(this->frames_.size(), 2u);
EXPECT_EQ(this->frames_[0], make_data_frame(0x55));
EXPECT_EQ(this->frames_[1], make_data_frame(0x66));
EXPECT_EQ(this->pos_, 2) << "the partial header at the end stays buffered";
}
TEST_F(LD24xxFrameSplitterTest, AWrongFooterDropsOnlyThatFrame) {
auto bad = make_cmd_frame({0x01, 0x02});
bad[bad.size() - 1] = 0xEE;
this->feed_(bad);
EXPECT_EQ(this->drops_, 1);
EXPECT_TRUE(this->frames_.empty());
this->feed_(make_cmd_frame({0x03}));
ASSERT_EQ(this->frames_.size(), 1u);
EXPECT_EQ(this->frames_[0], make_cmd_frame({0x03}));
}
TEST_F(LD24xxFrameSplitterTest, BackToBackFramesOfBothKinds) {
this->feed_(make_data_frame(0x01));
this->feed_(make_cmd_frame({0xA0, 0x01, 0x00, 0x00}));
this->feed_(make_data_frame(0x02));
ASSERT_EQ(this->frames_.size(), 3u);
EXPECT_EQ(this->frames_[1], make_cmd_frame({0xA0, 0x01, 0x00, 0x00}));
EXPECT_EQ(this->frames_[2], make_data_frame(0x02));
EXPECT_EQ(this->drops_, 0);
}
} // namespace esphome::ld24xx::testing
@@ -6,6 +6,7 @@
#include <cstdint>
#include "esphome/components/light/esp_color_correction.h"
#include "esphome/components/light/esp_color_view.h"
namespace esphome::light::testing {
@@ -67,6 +68,69 @@ TEST(GammaCorrection, DeadZoneFixedAtGamma28) {
}
}
// A whole pixel keeps its colour when dim: only the strongest channel is lifted to 1.
TEST(GammaCorrection, DimPixelKeepsDominantChannel) {
GammaFixture fixture(2.8);
fixture.correction.set_local_brightness(13);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 30, 0, 0)), Color(1, 0, 0, 0));
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 255, 30)), Color(0, 0, 1, 0));
}
// Orange at 2% brightness and below: the table reads 1 for both channels there, and at the lowest
// step both scale to the same 8-bit value, so neither can be used to compare them.
TEST(GammaCorrection, VeryDimPixelKeepsDominantChannel) {
GammaFixture fixture(2.8);
for (uint8_t brightness : {1, 2, 3, 4, 5, 6}) {
fixture.correction.set_local_brightness(brightness);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 130, 0, 0)), Color(1, 0, 0, 0))
<< "brightness=" << int(brightness);
}
}
TEST(GammaCorrection, DimPixelKeepsSimilarChannels) {
GammaFixture fixture(2.8);
fixture.correction.set_local_brightness(13);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 255, 255, 0)), Color(1, 1, 1, 0));
EXPECT_EQ(fixture.correction.color_correct(Color(255, 230, 0, 0)), Color(1, 1, 0, 0));
fixture.correction.set_local_brightness(1);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 250, 250, 0)), Color(1, 1, 1, 0));
}
// A channel that color_correct sets to 0% stays dark even when it is the strongest in the pixel.
TEST(GammaCorrection, DimPixelLeavesDisabledChannelDark) {
GammaFixture fixture(2.8);
fixture.correction.set_max_brightness(Color(255, 0, 255, 255));
EXPECT_EQ(fixture.correction.color_correct(Color(1, 255, 0, 0)), Color(1, 0, 0, 0));
}
// A strip without white drops the white level before the pixel is rounded, so it cannot outrank red.
TEST(GammaCorrection, UnusedWhiteDoesNotDarkenRgbStrip) {
GammaFixture fixture(2.8);
fixture.correction.set_local_brightness(13);
std::array<uint8_t, 3> color_data{};
std::array<uint8_t, 1> effect_data{};
CorrectedBufferColorAccessor accessor(color_data.data(), effect_data.data(), ChannelColors{0, 1, 2},
&fixture.correction);
accessor.set(0, Color(128, 0, 0, 255));
EXPECT_EQ(color_data, (std::array<uint8_t, 3>{1, 0, 0}));
}
TEST(GammaCorrection, LitPixelDropsChannelThatRoundsToZero) {
GammaFixture fixture(2.8);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 5, 0, 0)), Color(255, 0, 0, 0));
}
// The pixel-level form of esphome/esphome#18842: a non-zero pixel never goes fully dark.
TEST(GammaCorrection, NonZeroPixelStaysLit) {
for (double gamma : {1.0, 2.2, 2.8, 4.0}) {
GammaFixture fixture(gamma);
for (int i = 1; i < 256; i++) {
EXPECT_GE(fixture.correction.color_correct(Color(i, 0, 0, 0)).red, 1) << "gamma=" << gamma << " index=" << i;
}
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 0, 0)), Color(0, 0, 0, 0)) << "gamma=" << gamma;
}
}
TEST(GammaCorrection, ReverseSearchFindsLargestIndexLessEqualTarget) {
auto table = build_gamma_table(2.8);
for (uint16_t target : {0, 128, 129, 135, 1000, 32768, 65535}) {
+12
View File
@@ -0,0 +1,12 @@
import esphome.codegen as cg
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
async def to_code_testing(config):
# The accessor hooks that partitions use, and the gamma table of the light under test
cg.add_define("USE_LIGHT_PARTITION")
cg.add_define("USE_LIGHT_GAMMA_LUT")
manifest.to_code = to_code_testing
manifest.dependencies = manifest.dependencies + ["light"]
@@ -0,0 +1,56 @@
#include <gtest/gtest.h>
#include <array>
#include <cmath>
#include <cstdint>
#include "esphome/components/light/addressable_light.h"
#include "esphome/components/light/light_state.h"
#include "esphome/components/partition/light_partition.h"
namespace esphome::partition::testing {
namespace {
// One RGB pixel in memory
class RgbStrip : public light::AddressableLight {
public:
RgbStrip()
: internal_accessor_(this->buffer_.data(), this->buffer_.data() + 3, light::ChannelColors{0, 1, 2},
&this->correction_) {
this->accessor_ = &this->internal_accessor_;
}
int32_t size() const override { return 1; }
void clear_effect_data() override {}
light::LightTraits get_traits() override { return {}; }
void write_state(light::LightState *state) override {}
protected:
std::array<uint8_t, 4> buffer_{};
light::CorrectedBufferColorAccessor internal_accessor_;
};
} // namespace
// The partition corrects a pixel before the strip drops its white level, so it has to drop it first.
TEST(PartitionWhite, UnusedWhiteDoesNotDarkenRgbSegment) {
light::GammaTable table{};
for (int i = 1; i < 256; i++)
table.lut[i] = std::max(1.0, std::round(std::pow(i / 255.0, 2.8) * 65535.0));
table.gamma_x100 = 280;
RgbStrip strip;
light::LightState strip_state(&strip);
PartitionLightOutput partition({AddressableSegment(&strip_state, 0, 1, false)});
light::LightState partition_state(&partition);
partition_state.set_gamma_table(&table);
partition.setup_state(&partition_state);
partition_state.current_values.set_state(1.0f);
partition_state.current_values.set_brightness(13 / 255.0f);
partition.update_state(&partition_state);
partition[0] = Color(128, 0, 0, 255);
EXPECT_EQ(strip[0].get_raw(), Color(1, 0, 0, 0));
}
} // namespace esphome::partition::testing
@@ -40,8 +40,12 @@ Frame command(uint8_t seq, const Frame &attrs) {
size_t feed_all(PacketReader &reader, const Frame &bytes) {
size_t last = 0;
for (uint8_t b : bytes) {
if (size_t len = reader.feed(b))
reader.feed(b, [&last](const uint8_t *frame, size_t len) {
if (!checksum_valid(frame, len))
return false;
last = len;
return true;
});
}
return last;
}
@@ -82,9 +86,8 @@ TEST(PioneerWTProtocol, ReaderDropsBadChecksum) {
PacketReader reader;
Frame frame = from_hex(PRESENCE_CHECK);
frame[9] ^= 0x01;
EXPECT_FALSE(checksum_valid(frame.data(), frame.size()));
EXPECT_EQ(feed_all(reader, frame), 0u);
EXPECT_TRUE(reader.take_checksum_error());
EXPECT_FALSE(reader.take_checksum_error());
// The next good frame is still accepted.
EXPECT_EQ(feed_all(reader, from_hex(PRESENCE_CHECK)), 12u);
}
@@ -339,14 +342,28 @@ TEST_F(PioneerWTTest, WarningStaysUntilAcknowledgement) {
EXPECT_FALSE(this->sut_.status_has_warning());
}
TEST_F(PioneerWTTest, DropsPartialFrameAfterPause) {
TEST_F(PioneerWTTest, FindsFrameBehindCutOffHeaderAfterPause) {
this->start_();
// A cut-off header that claims 255 bytes would otherwise swallow the frames that follow.
// A cut-off header claiming 255 bytes is kept; the frame landing inside it is found on the next idle pass
this->uart_.push_rx_hex("a5010121000000ff");
this->loop_at_(1100);
this->loop_at_(1300); // idle pass after the gap
this->loop_at_(1400);
this->uart_.push_rx_hex(PRESENCE_CHECK);
this->loop_at_(2000);
this->loop_at_(2300); // idle pass after the gap
EXPECT_EQ(this->uart_.tx, from_hex(PRESENCE_REPLY));
}
TEST_F(PioneerWTTest, FindsFrameHeldBackByCorruptLength) {
this->start_();
// A header that claims 255 bytes, then a complete frame that is held back behind it until the pause
Frame bytes = from_hex("a5010121000000ff");
const Frame check = from_hex(PRESENCE_CHECK);
bytes.insert(bytes.end(), check.begin(), check.end());
this->uart_.push_rx(bytes);
this->loop_at_(1100);
EXPECT_TRUE(this->uart_.tx.empty());
this->loop_at_(1400); // idle pass after the gap
EXPECT_EQ(this->uart_.tx, from_hex(PRESENCE_REPLY));
}
@@ -0,0 +1,20 @@
import esphome.codegen as cg
from esphome.components import tuya
import esphome.config_validation as cv
from esphome.const import CONF_ID
from esphome.types import ConfigType
AUTO_LOAD = ["tuya"]
ns = cg.esphome_ns.namespace("fake_tuya_transport")
FakeTuyaTransport = ns.class_("FakeTuyaTransport", tuya.Tuya)
CONFIG_SCHEMA = tuya.TUYA_SCHEMA.extend(
{cv.GenerateID(): cv.declare_id(FakeTuyaTransport)}
)
async def to_code(config: ConfigType) -> None:
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await tuya.setup_tuya(var, config)
@@ -0,0 +1,19 @@
#pragma once
#include "esphome/components/tuya/tuya.h"
namespace esphome::fake_tuya_transport {
/// A Tuya controller with no transport: datapoint writes are dropped, and
/// initialization completes immediately in setup() so entities receive
/// their initial-state callbacks.
class FakeTuyaTransport : public tuya::Tuya {
public:
void setup() override { this->mark_initialized_(); }
protected:
void send_datapoint_command(uint8_t datapoint_id, tuya::TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) override {}
};
} // namespace esphome::fake_tuya_transport
@@ -0,0 +1,14 @@
# Compile the tuya base class with a non-UART transport: no uart bus anywhere,
# and the UART implementation filtered from the build.
external_components:
- source: ../../components/tuya/components
components: [fake_tuya_transport]
fake_tuya_transport:
id: fake_tuya
switch:
- platform: tuya
tuya_id: fake_tuya
name: Fake Switch
switch_datapoint: 1
@@ -1,6 +1,7 @@
#include <algorithm>
#include "common.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
namespace esphome::uart::testing {
@@ -179,4 +180,58 @@ TEST(UARTReadAvailableTest, DiscardStopsOnReadFailure) {
EXPECT_EQ(uart.read_sizes.size(), 3u);
}
// AA, length byte, then that many bytes; the handler takes every frame
using GapReader = LengthFrameReader<16, FrameFormat<FrameHeader<0xAA>, PayloadLengthU8<LengthField{.offset = 1}>>>;
TEST(UARTReadFramesTest, FeedsTheReaderAndStampsTheTime) {
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x01, 0x07});
UARTDevice dev(&uart);
GapReader reader;
std::vector<std::vector<uint8_t>> frames;
auto handle = [&frames](const uint8_t *f, size_t len) {
frames.emplace_back(f, f + len);
return true;
};
uint32_t last_rx = 0;
dev.read_frames(reader, handle, 500, last_rx);
EXPECT_EQ(last_rx, 500u);
EXPECT_EQ(frames, (std::vector<std::vector<uint8_t>>{{0xAA, 0x01, 0x07}}));
}
TEST(UARTReadFramesTest, IdlePassAfterTheGapFlushesAStalledFrame) {
// A corrupt length of 9 holds the whole frame AA 01 07 behind it
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x09, 0xAA, 0x01, 0x07});
UARTDevice dev(&uart);
GapReader reader;
std::vector<std::vector<uint8_t>> frames;
auto handle = [&frames](const uint8_t *f, size_t len) {
frames.emplace_back(f, f + len);
return f[1] != 0x09;
};
uint32_t last_rx = 0;
dev.read_frames(reader, handle, 1000, last_rx, 100);
dev.read_frames(reader, handle, 1099, last_rx, 100);
EXPECT_TRUE(frames.empty());
dev.read_frames(reader, handle, 1100, last_rx, 100);
EXPECT_EQ(frames, (std::vector<std::vector<uint8_t>>{{0xAA, 0x01, 0x07}}));
EXPECT_EQ(reader.length(), 0u);
}
TEST(UARTReadFramesTest, BytesAfterASlowLoopAreFedNotFlushed) {
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x02, 0x01});
UARTDevice dev(&uart);
GapReader reader;
std::vector<std::vector<uint8_t>> frames;
auto handle = [&frames](const uint8_t *f, size_t len) {
frames.emplace_back(f, f + len);
return true;
};
uint32_t last_rx = 0;
dev.read_frames(reader, handle, 1000, last_rx, 100);
// The rest of the frame waited out a 500 ms loop
uart.append({0x02});
dev.read_frames(reader, handle, 1500, last_rx, 100);
EXPECT_EQ(frames, (std::vector<std::vector<uint8_t>>{{0xAA, 0x02, 0x01, 0x02}}));
}
} // namespace esphome::uart::testing
@@ -65,15 +65,15 @@ uart_mock:
- delay: 100ms
inject_rx: [0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x11, 0x22]
# Phase 3 (t=300ms): Truncated frame (header + partial data, no footer)
# Phase 3 (t=450ms): Truncated frame (header + partial data, no footer)
# The header opens the buffer; the parser waits for the 23 bytes its length announces.
- delay: 100ms
- delay: 250ms
inject_rx: [0xF4, 0xF3, 0xF2, 0xF1, 0x0D, 0x00, 0x02, 0xAA]
# Phase 4 (t=500ms): 85 bytes of 0xFF
# The first 15 complete the truncated frame's 23 bytes without its footer, so it is dropped
# with an 'Invalid length' warning; the rest cannot start a header and are dropped too.
- delay: 200ms
# with an 'Invalid footer' warning; the rest cannot start a header and are dropped too.
- delay: 50ms
inject_rx:
[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
@@ -29,17 +29,18 @@ uart_mock:
- delay: 100ms
inject_rx: [0x6E, 0x02, 0x2C, 0x01, 0x62]
# Standard header with a 255 byte length field (over the 96 byte buffer), three payload bytes,
# then a short frame, state 0 -> frame dropped, presence off
# then a short frame, state 0: the length is skipped and the short frame still parses -> presence off
- delay: 100ms
inject_rx: [0xF4, 0xF3, 0xF2, 0xF1, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x6E, 0x00, 0x00, 0x00, 0x62]
# Standard frame declaring 5 payload bytes but carrying 3, then a short frame, state 2: the short
# frame is read as the rest of the declared length, so the frame stays one byte short
- delay: 100ms
inject_rx: [0xF4, 0xF3, 0xF2, 0xF1, 0x05, 0x00, 0x01, 0x02, 0x2C, 0x6E, 0x02, 0x2C, 0x01, 0x62]
# Short frame, state 0: its first byte completes the truncated frame (footer mismatch); the
# rescan of the swallowed bytes rescues the state 2 short frame -> presence on, and leaves this
# frame's header pending, so the rest of it completes -> presence off
- delay: 100ms
# Short frame, state 0, within the 250 ms the reader waits for the rest of a frame: its first byte
# completes the truncated frame (footer mismatch); the rescan of the swallowed bytes rescues the
# state 2 short frame -> presence on, and leaves this frame's header pending, so the rest of it
# completes -> presence off
- delay: 30ms
inject_rx: [0x6E, 0x00, 0x00, 0x00, 0x62]
# Short frame, state 2 -> presence on
- delay: 100ms
@@ -66,15 +66,15 @@ uart_mock:
- delay: 200ms
inject_rx: [0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x11, 0x22]
# Phase 3 (t=400ms): Truncated frame (header + partial data, no footer)
# Phase 3 (t=550ms): Truncated frame (header + partial data, no footer)
# Starts with a valid data frame header, so the parser waits for the 23 bytes its length announces.
- delay: 100ms
- delay: 250ms
inject_rx: [0xF4, 0xF3, 0xF2, 0xF1, 0x0D, 0x00, 0x02, 0xAA]
# Phase 4 (t=600ms): 60 bytes of 0xFF
# The first 15 complete the truncated frame's 23 bytes without its footer, so it is dropped
# with an 'Invalid length' warning; the rest cannot start a header and are dropped too.
- delay: 200ms
# with an 'Invalid footer' warning; the rest cannot start a header and are dropped too.
- delay: 50ms
inject_rx:
[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
@@ -92,11 +92,11 @@ uart_mock:
- delay: 100ms
inject_rx: [0xAA, 0xFF, 0x03, 0x00, 0x01, 0x02, 0x03, 0x04]
# Phase 4 (t=600ms): 75 bytes of 0xFF
# Phase 4 (t=450ms): 75 bytes of 0xFF, within the 250 ms the reader waits for the rest of a frame
# The first 22 complete the truncated frame's 30 bytes without its footer, so it is
# dropped with an 'Invalid header/footer' warning; the rest cannot start a header and
# dropped with an 'Invalid footer' warning; the rest cannot start a header and
# are dropped too, leaving the buffer empty for the recovery frame.
- delay: 200ms
- delay: 50ms
inject_rx:
[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
@@ -109,7 +109,7 @@ uart_mock:
0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
]
# Phase 5 (t=700ms): Valid frame after the garbage - recovery test
# Phase 5 (t=550ms): Valid frame after the garbage - recovery test
# The buffer is empty again, so this valid frame should parse correctly.
#
# Target 1: X=300mm, Y=400mm, Speed=30mm/s (moving away), Res=100mm
@@ -46,15 +46,14 @@ uart_mock:
- delay: 200ms
inject_rx: [0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x11, 0x22]
# Phase 3 (t=400ms): a report header with partial data and no footer
- delay: 100ms
# Phase 3 (t=550ms): a report header with partial data and no footer
- delay: 250ms
inject_rx: [0xF4, 0xF3, 0xF2, 0xF1, 0x04, 0x13, 0x00, 0x01, 0x02]
# Phase 4 (t=600ms): overflow the 32-byte frame buffer. Phases 2 and 3 left 16 bytes
# in it; 48 more make 64, so the parser fills the buffer twice. The 33rd byte logs
# "Max frame length exceeded" and restarts the buffer, the 64th leaves it full, and the
# first byte of the next frame restarts it again, so phase 5 parses from a clean buffer.
- delay: 200ms
# Phase 4 (t=600ms): 48 bytes that cannot start a header. The first 10 complete the
# 19-byte frame phase 3 started; its footer does not match, so it is dropped, the rest
# are skipped, and phase 5 parses from a clean buffer.
- delay: 50ms
inject_rx:
[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+2 -2
View File
@@ -121,8 +121,8 @@ async def test_uart_mock_ld2410(
)
# Verify the truncated frame was dropped with a warning
assert any("Invalid length" in line for line in waiter.lines), (
"Expected 'Invalid length' warning in logs"
assert any("Invalid footer" in line for line in waiter.lines), (
"Expected 'Invalid footer' warning in logs"
)
# Verify LD2410 sent setup commands (TX logging)
+3 -11
View File
@@ -121,7 +121,7 @@ EXPECTED_DROPPED_STATES = ["7", "7"]
# bytes, which publishes the swallowed frame and resumes the next one.
EXPECTED_RECOVERY_PRESENCE = [
True, # baseline short frame
False, # short frame after the dropped oversized length field
False, # short frame right after the oversized length field, still parsed
True, # rescued: short frame swallowed by the truncated standard frame
False, # short frame whose header byte completed the truncated frame
True, # short frame
@@ -132,8 +132,8 @@ EXPECTED_RECOVERY_PRESENCE = [
False, # short frame
]
# The truncated frame takes the next 6 bytes to reach its declared length
TRUNCATED_FRAME_HEX = "F4 F3 F2 F1 05 00 01 02 2C 6E 02 2C 01 62 6E"
BAD_COMMAND_FRAME_HEX = "FD FC FB FA 04 00 FE 01 00 00 00 00 00 00"
TRUNCATED_FRAME_HEX = "F4:F3:F2:F1:05:00:01:02:2C:6E:02:2C:01:62:6E"
BAD_COMMAND_FRAME_HEX = "FD:FC:FB:FA:04:00:FE:01:00:00:00:00:00:00"
def _tx_frame(line: str) -> str | None:
@@ -302,7 +302,6 @@ async def test_uart_mock_ld2410s_recovery(
tx_frames: list[tuple[float, str]] = []
resent = loop.create_future()
gave_up = loop.create_future()
oversized_dropped = loop.create_future()
footer_mismatches: list[str] = []
ignored_changes = 0
@@ -321,12 +320,6 @@ async def test_uart_mock_ld2410s_recovery(
and not gave_up.done()
):
gave_up.set_result(True)
if (
"Dropping frame with a 255 byte payload, larger than the receive buffer"
in line
and not oversized_dropped.done()
):
oversized_dropped.set_result(True)
if "Footer does not match header: " in line:
footer_mismatches.append(
ANSI_ESCAPE.sub("", line.split("header: ", 1)[1]).strip()
@@ -375,7 +368,6 @@ async def test_uart_mock_ld2410s_recovery(
assert collector.binary_states["has_target"] == EXPECTED_RECOVERY_PRESENCE
assert ignored_changes == 2
assert setting_states == []
assert oversized_dropped.done(), "Oversized length field was not dropped"
assert footer_mismatches == [TRUNCATED_FRAME_HEX, BAD_COMMAND_FRAME_HEX]
frames = [frame for _, frame in tx_frames]
+3 -3
View File
@@ -228,8 +228,8 @@ async def test_uart_mock_ld2412(
)
# Verify the truncated frame was dropped with a warning
assert any("Invalid length" in line for line in waiter.lines), (
"Expected 'Invalid length' warning in logs"
assert any("Invalid footer" in line for line in waiter.lines), (
"Expected 'Invalid footer' warning in logs"
)
# Verify LD2412 sent setup commands (TX logging)
@@ -583,7 +583,7 @@ async def test_uart_mock_ld2412_truncated_answer(
try:
_, gate_0_state, gate_5_state = await asyncio.gather(
waiter.wait_for("Invalid length", timeout=5.0),
waiter.wait_for("Invalid footer", timeout=5.0),
gate_0_read,
gate_5_read,
)
+2 -2
View File
@@ -142,8 +142,8 @@ async def test_uart_mock_ld2450(
)
# Verify the truncated frame was dropped with a warning
assert any("Invalid header/footer" in line for line in waiter.lines), (
"Expected 'Invalid header/footer' warning in logs"
assert any("Invalid footer" in line for line in waiter.lines), (
"Expected 'Invalid footer' warning in logs"
)
# Verify LD2450 sent setup commands (TX logging)
+2 -3
View File
@@ -114,9 +114,6 @@ async def test_uart_mock_ld2460(
"Timeout waiting for the recovery frame",
sensor_states=collector.sensor_states,
)
assert any("Max frame length exceeded" in line for line in waiter.lines), (
"Expected 'Max frame length exceeded' in the log"
)
assert (
pytest.approx(3.606, abs=0.01)
in collector.sensor_states["target_1_distance"]
@@ -125,6 +122,8 @@ async def test_uart_mock_ld2460(
pytest.approx(-33.7, abs=0.1) in collector.sensor_states["target_1_angle"]
)
assert pytest.approx(26.6, abs=0.1) in collector.sensor_states["target_2_angle"]
# Phase 4 completed the truncated frame, which was rejected rather than given up early
assert any("Invalid footer" in line for line in waiter.lines)
# Phase 6: the top-mount receipt changes the angle for the same coordinates
await wait_or_fail(