mirror of
https://github.com/esphome/esphome.git
synced 2026-11-19 11:35:57 +00:00
Compare commits
159
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f9925e631 | ||
|
|
cebd928843 | ||
|
|
d50b9cbe0b | ||
|
|
a8c95ace2d | ||
|
|
f24319c5c5 | ||
|
|
e235bd3bba | ||
|
|
25af9abd94 | ||
|
|
ec04273cb9 | ||
|
|
67d96843fb | ||
|
|
2a3bfba88f | ||
|
|
8b744ca59c | ||
|
|
9abfb210d7 | ||
|
|
fc80c2aaf9 | ||
|
|
590ed71434 | ||
|
|
b148f40429 | ||
|
|
19d2f90a2a | ||
|
|
6afa247a0c | ||
|
|
bee80eef56 | ||
|
|
7c3c6e43ea | ||
|
|
9829919d21 | ||
|
|
04bb736511 | ||
|
|
89030d28e5 | ||
|
|
94e670de12 | ||
|
|
a4da01e207 | ||
|
|
b6c0ceabf2 | ||
|
|
9a7b4c3121 | ||
|
|
03990bf424 | ||
|
|
30d62b54f3 | ||
|
|
d3dd1b27da | ||
|
|
7c563011eb | ||
|
|
49fe004a80 | ||
|
|
05436f0b15 | ||
|
|
04aa0fccc6 | ||
|
|
c90cf2c987 | ||
|
|
0d4d3f9d86 | ||
|
|
63fc52ed41 | ||
|
|
87be3320a3 | ||
|
|
f6b19e3139 | ||
|
|
80bb2c4f75 | ||
|
|
39fa5b1dd6 | ||
|
|
4998195f7e | ||
|
|
a51d880796 | ||
|
|
96886c9178 | ||
|
|
037c6f6395 | ||
|
|
d983659f32 | ||
|
|
d892a4598f | ||
|
|
d25e511e5e | ||
|
|
837f2706b4 | ||
|
|
c3d475876a | ||
|
|
d01835e824 | ||
|
|
7cc83ab11e | ||
|
|
0b0bb23517 | ||
|
|
00f4c3165d | ||
|
|
1cbe0dd624 | ||
|
|
4f8ca50ffe | ||
|
|
6c328fe6c4 | ||
|
|
8ceed2a7e8 | ||
|
|
e009b526aa | ||
|
|
29f751a8aa | ||
|
|
3fe21d0ba0 | ||
|
|
8bed96bf79 | ||
|
|
c617c99c60 | ||
|
|
e76d7b807c | ||
|
|
ca0de4e3b4 | ||
|
|
c1b0e3b7b6 | ||
|
|
38a3aee1b7 | ||
|
|
38a90d244d | ||
|
|
5a46ae13d8 | ||
|
|
9cb098b6ac | ||
|
|
2e01654d39 | ||
|
|
b338e0a2e3 | ||
|
|
e6151b8de1 | ||
|
|
4cdb7c4c63 | ||
|
|
38653974db | ||
|
|
fd330d8e23 | ||
|
|
93074d3d92 | ||
|
|
90146e7b72 | ||
|
|
c7001c33a6 | ||
|
|
3d067b9484 | ||
|
|
4d28203063 | ||
|
|
ef6232571a | ||
|
|
f72ba983e9 | ||
|
|
47f57f1723 | ||
|
|
9318cd782a | ||
|
|
a15b02a647 | ||
|
|
b1ffe8690f | ||
|
|
739e2f106f | ||
|
|
dcda93d7ca | ||
|
|
a15d2da270 | ||
|
|
dde2bc4004 | ||
|
|
d38437dedb | ||
|
|
0436eda0f8 | ||
|
|
3969df3ed7 | ||
|
|
414bc9c806 | ||
|
|
bf79439362 | ||
|
|
dba1402480 | ||
|
|
54a588d154 | ||
|
|
56a0d3e6b3 | ||
|
|
e7b91adb6d | ||
|
|
a459f80efe | ||
|
|
03d4ba97a2 | ||
|
|
10e166dc7e | ||
|
|
4206665ad9 | ||
|
|
3508113c61 | ||
|
|
a460fb50b4 | ||
|
|
5b98c9c134 | ||
|
|
7f30d135c7 | ||
|
|
06ac99fe7b | ||
|
|
d97af3b539 | ||
|
|
3ced52a018 | ||
|
|
f1ba9db67f | ||
|
|
ecb6c5fb10 | ||
|
|
44eb08c002 | ||
|
|
29dbefee56 | ||
|
|
62de684473 | ||
|
|
17e7e6acfd | ||
|
|
3b41980b69 | ||
|
|
ca66513783 | ||
|
|
cf871bc7b9 | ||
|
|
6fbf57b747 | ||
|
|
24601231db | ||
|
|
518e8e9a60 | ||
|
|
749f632112 | ||
|
|
cd25f87619 | ||
|
|
7fa2806227 | ||
|
|
ac6a48d650 | ||
|
|
61b99d91bf | ||
|
|
dd69a68531 | ||
|
|
39bb0aa1bf | ||
|
|
8c03fc331c | ||
|
|
1acbcdd015 | ||
|
|
429aa69a4a | ||
|
|
f78b8167e4 | ||
|
|
1241599bbb | ||
|
|
117b9634b4 | ||
|
|
506f1c4821 | ||
|
|
d82342b81f | ||
|
|
171c08442f | ||
|
|
1beecc63c4 | ||
|
|
d41625bd74 | ||
|
|
b6843e022f | ||
|
|
69a7f7a408 | ||
|
|
5e24d3f6d5 | ||
|
|
5e2f90af11 | ||
|
|
9fb6cb4867 | ||
|
|
e0a5fad2de | ||
|
|
6d472f4954 | ||
|
|
5bf30663b3 | ||
|
|
2827c1a07e | ||
|
|
d76c655553 | ||
|
|
01765c6ba0 | ||
|
|
8bb20f3ebf | ||
|
|
9bdd466e51 | ||
|
|
fad0b39f98 | ||
|
|
c803b7163a | ||
|
|
03880d5ea6 | ||
|
|
c27895a12b | ||
|
|
4a04c61ab5 | ||
|
|
2cd9ddf246 |
No files matched your search
@@ -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)` |
|
||||
|
||||
@@ -246,7 +246,9 @@ 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 frees frames a bad length holds; 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
|
||||
|
||||
@@ -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) {
|
||||
@@ -369,11 +319,14 @@ void AirtonSerialClimate::send_a5_() {
|
||||
void AirtonSerialClimate::send_ab_() {
|
||||
uint8_t frame[sizeof(AB_FRAME)];
|
||||
progmem_memcpy(frame, AB_FRAME, sizeof(AB_FRAME));
|
||||
this->reader_.drop_kept();
|
||||
this->write_array(frame, sizeof(frame));
|
||||
}
|
||||
|
||||
void AirtonSerialClimate::write_frame_(uint8_t *frame, size_t len) {
|
||||
put_be16(frame + len - 2, crc16(frame, len - 2));
|
||||
// Kept bytes of an earlier frame must not merge into the reply
|
||||
this->reader_.drop_kept();
|
||||
this->write_array(frame, len);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -295,6 +246,8 @@ void APC1Component::set_measurement_mode() {
|
||||
}
|
||||
|
||||
void APC1Component::send_command_(APC1Command cmd, uint16_t data) {
|
||||
// Kept bytes of an earlier reply must not merge into this command's
|
||||
this->reader_.drop_kept();
|
||||
std::array<uint8_t, APC1_COMMAND_FRAME_SIZE> buf{
|
||||
APC1_HEADER_1,
|
||||
APC1_HEADER_2,
|
||||
|
||||
@@ -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,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_.receiving() &&
|
||||
(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_++;
|
||||
// Kept bytes of an earlier reply must not merge into this request's
|
||||
this->reader_.drop_kept();
|
||||
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
|
||||
@@ -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.
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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,11 @@ void LD2410SComponent::dump_config() {
|
||||
}
|
||||
|
||||
void LD2410SComponent::loop() {
|
||||
if (!this->read_available<16>([this](uint8_t b) { this->receive_byte_(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); };
|
||||
if (!this->read_frames<16>(this->reader_, handler, now, this->last_rx_)) {
|
||||
ESP_LOGV(TAG, "UART read failed");
|
||||
}
|
||||
const uint32_t now = App.get_loop_component_start_time();
|
||||
if (this->sequence_ == nullptr) {
|
||||
if (!this->init_done_) {
|
||||
this->start_sequence_(INIT_SEQUENCE, INIT_SEQUENCE_LENGTH, now);
|
||||
@@ -211,7 +208,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 +237,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 +292,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 +315,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 +347,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,36 @@ 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_LOGW(TAG, "Invalid footer");
|
||||
ESP_LOGV_HEX(TAG, frame, len, MAX_FRAME_LENGTH, "Rejected: %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 +164,7 @@ void LD2460Component::handle_ack_() {
|
||||
t.last_x = INT16_MIN;
|
||||
}
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace esphome::ld2460
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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,22 +66,17 @@ 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();
|
||||
}
|
||||
if (!this->queue_.empty() && now - this->last_send_ >= RESEND_INTERVAL_MS)
|
||||
this->handle_frame_(frame, len);
|
||||
return true;
|
||||
};
|
||||
this->read_frames(this->reader_, handle, now, this->last_rx_);
|
||||
// A frame still coming in may be the reply; wait for it before resending
|
||||
if (!this->queue_.empty() && now - this->last_send_ >= RESEND_INTERVAL_MS && !this->reader_.receiving())
|
||||
this->send_pending_();
|
||||
// The target temperature only arrives in a full status, so it tells whether one has been received.
|
||||
const uint32_t status_interval = std::isnan(this->target_temperature) ? STATUS_RETRY_MS : STATUS_REFRESH_MS;
|
||||
@@ -334,6 +327,8 @@ void PioneerWT::write_frame_(uint8_t flags, uint8_t type, uint8_t seq, uint8_t a
|
||||
uint8_t frame[HEADER_SIZE + 2 + MAX_BODY_SIZE];
|
||||
const size_t total = build_frame(frame, flags, type, seq, ack, class_1, class_2, body, len);
|
||||
ESP_LOGVV_HEX(TAG, frame, total, sizeof(frame), "TX %s");
|
||||
// Kept bytes of an earlier frame must not merge into the reply
|
||||
this->reader_.drop_kept();
|
||||
this->write_array(frame, total);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 =
|
||||
@@ -83,8 +80,9 @@ void PMSX003Component::loop() {
|
||||
// wait for the sensor to be stable
|
||||
if (now - this->fan_on_time_ < STABILISING_MS)
|
||||
return;
|
||||
// consume any command responses that are in the serial buffer
|
||||
// consume any command responses that are in the serial buffer, and any partial frame from before the sleep
|
||||
this->discard_available();
|
||||
this->reader_.reset();
|
||||
// Trigger a new read
|
||||
this->send_command_(Command::MANUAL_MEASUREMENT, 0);
|
||||
this->state_ = State::WAITING;
|
||||
@@ -95,82 +93,38 @@ 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];
|
||||
void warn_too_long(size_t len) {
|
||||
ESP_LOGW(TAG, "Payload length %u doesn't match. Are you using the correct PMSX003 type?",
|
||||
static_cast<unsigned>(len - PayloadLength::KNOWN_AT));
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -196,6 +150,8 @@ bool PMSX003Component::check_payload_length_(uint16_t payload_length) {
|
||||
}
|
||||
|
||||
void PMSX003Component::send_command_(Command cmd, uint16_t data) {
|
||||
// Kept bytes of an earlier reply must not merge into this command's
|
||||
this->reader_.drop_kept();
|
||||
uint8_t send_data[7] = {
|
||||
START_CHARACTER_1, // Start Byte 1
|
||||
START_CHARACTER_2, // Start Byte 2
|
||||
@@ -214,11 +170,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 +190,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 +203,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 +219,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 +231,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 +242,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 +254,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);
|
||||
}
|
||||
|
||||
@@ -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}>;
|
||||
/// The wrong-type warning, for a frame longer than any supported type sends
|
||||
void warn_too_long(size_t len);
|
||||
using PmsFrame = FrameFormat<FrameHeader<START_CHARACTER_1, START_CHARACTER_2>,
|
||||
WarnIfLonger<PayloadLength, MAX_FRAME_SIZE, warn_too_long>>;
|
||||
|
||||
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,62 @@ 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]);
|
||||
void warn_too_long(size_t len) {
|
||||
ESP_LOGW(TAG, "Skipped a %u byte frame, longer than the %u byte buffer", static_cast<unsigned>(len),
|
||||
static_cast<unsigned>(FRAME_MAX_SIZE));
|
||||
}
|
||||
|
||||
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,24 @@
|
||||
#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);
|
||||
};
|
||||
void warn_too_long(size_t len);
|
||||
// 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 +51,13 @@ 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>,
|
||||
WarnIfLonger<TinyFrameLength, FRAME_MAX_SIZE, warn_too_long>>>
|
||||
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; }
|
||||
|
||||
@@ -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
|
||||
// After this long without a byte, a partial frame is searched, 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;
|
||||
@@ -273,13 +265,16 @@ bool ShellyDimmer::send_command_(uint8_t cmd, const uint8_t *const payload, uint
|
||||
// Write the frame and wait for acknowledgement.
|
||||
int retries = SHELLY_DIMMER_MAX_RETRIES;
|
||||
while (retries--) {
|
||||
// Kept bytes of an earlier reply must not merge into this one
|
||||
this->reader_.drop_kept();
|
||||
this->write_array(frame, frame_len);
|
||||
this->flush();
|
||||
|
||||
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 +298,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 +332,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);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "tuya_uart.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
@@ -27,7 +28,7 @@ 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 constexpr uint32_t RECEIVE_TIMEOUT = 300;
|
||||
static const int MAX_RETRIES = 5;
|
||||
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
|
||||
|
||||
@@ -54,7 +55,12 @@ void TuyaUART::setup() {
|
||||
}
|
||||
|
||||
void TuyaUART::loop() {
|
||||
this->read_available([this](uint8_t b) { this->handle_char_(b); });
|
||||
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_();
|
||||
}
|
||||
|
||||
@@ -92,70 +98,30 @@ void TuyaUART::dump_mcu_config_() {
|
||||
#endif
|
||||
}
|
||||
|
||||
bool TuyaUART::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);
|
||||
void warn_too_long(size_t len) {
|
||||
ESP_LOGW(TAG, "Skipped a %u byte frame, longer than the %u byte buffer", static_cast<unsigned>(len),
|
||||
static_cast<unsigned>(MAX_FRAME_SIZE));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// valid message
|
||||
const uint8_t *message_data = data + 6;
|
||||
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 false to reset rx buffer
|
||||
return false;
|
||||
}
|
||||
|
||||
void TuyaUART::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();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void TuyaUART::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
|
||||
@@ -488,11 +454,8 @@ void TuyaUART::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) {
|
||||
// A reply still coming in, or held behind a corrupt length, is waited for
|
||||
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT && !this->reader_.receiving()) {
|
||||
this->expected_response_.reset();
|
||||
if (init_state_ != TuyaInitState::INIT_DONE) {
|
||||
if (++this->init_retries_ >= MAX_RETRIES) {
|
||||
@@ -507,8 +470,11 @@ void TuyaUART::process_command_queue_() {
|
||||
}
|
||||
|
||||
// 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() &&
|
||||
// A partial frame kept by an idle flush does not hold commands back; a command clears it, so it cannot merge into
|
||||
// the reply
|
||||
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && !this->reader_.receiving() && !this->handling_frame_ &&
|
||||
!this->expected_response_.has_value()) {
|
||||
this->reader_.drop_kept();
|
||||
this->send_raw_command_(command_queue_.front());
|
||||
if (!this->expected_response_.has_value())
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
#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"
|
||||
@@ -14,6 +16,14 @@
|
||||
|
||||
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}>;
|
||||
void warn_too_long(size_t len);
|
||||
using TuyaFrame = FrameFormat<FrameHeader<0x55, 0xAA>, WarnIfLonger<TuyaLength, MAX_FRAME_SIZE, warn_too_long>>;
|
||||
|
||||
enum class TuyaCommandType : uint8_t {
|
||||
HEARTBEAT = 0x00,
|
||||
PRODUCT_QUERY = 0x01,
|
||||
@@ -70,9 +80,9 @@ class TuyaUART final : public Tuya, public uart::UARTDevice {
|
||||
|
||||
protected:
|
||||
void dump_mcu_config_();
|
||||
void handle_char_(uint8_t c);
|
||||
/// 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);
|
||||
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);
|
||||
@@ -107,11 +117,13 @@ class TuyaUART final : public Tuya, public uart::UARTDevice {
|
||||
uint32_t last_command_timestamp_ = 0;
|
||||
uint32_t last_rx_char_timestamp_ = 0;
|
||||
std::unique_ptr<char[]> product_;
|
||||
std::vector<uint8_t> rx_message_;
|
||||
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
|
||||
@@ -90,6 +90,19 @@ class UARTDevice {
|
||||
count);
|
||||
}
|
||||
|
||||
/// Feed the waiting bytes to a LengthFrameReader; on a pass with none, gap_ms after last_rx, flush a stalled frame.
|
||||
/// Returns false when a UART read failed.
|
||||
template<size_t N = 64, typename R, typename F>
|
||||
bool 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;
|
||||
return this->read_available<N>([&reader, &handle](uint8_t c) { reader.feed(c, handle); }, count);
|
||||
}
|
||||
if (reader.length() != 0 && now - last_rx >= gap_ms)
|
||||
reader.flush(handle);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Read and drop every byte waiting in the receive buffer.
|
||||
void discard_available();
|
||||
|
||||
|
||||
+320
-13
@@ -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,311 @@ 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; }
|
||||
};
|
||||
|
||||
/// Wraps a length rule: a frame longer than MAX calls WARN(length) and is rejected; a replay can warn again.
|
||||
template<class LENGTH, size_t MAX, void (*WARN)(size_t)> struct WarnIfLonger {
|
||||
static constexpr size_t KNOWN_AT = LENGTH::KNOWN_AT;
|
||||
static size_t get(const uint8_t *buf) {
|
||||
const size_t len = LENGTH::get(buf);
|
||||
if (len <= MAX)
|
||||
return len;
|
||||
WARN(len);
|
||||
return 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>;
|
||||
template<class LENGTH, size_t MAX, void (*WARN)(size_t)>
|
||||
constexpr size_t FIXED_LENGTH<WarnIfLonger<LENGTH, MAX, WARN>> = FIXED_LENGTH<LENGTH>;
|
||||
// The MAX of a WarnIfLonger rule, 0 for every other rule
|
||||
template<class LENGTH> constexpr size_t WARN_MAX = 0;
|
||||
template<class LENGTH, size_t MAX, void (*WARN)(size_t)>
|
||||
constexpr size_t WARN_MAX<WarnIfLonger<LENGTH, MAX, WARN>> = MAX;
|
||||
template<class LENGTH, size_t AT, bool (*CHECK)(const uint8_t *)>
|
||||
constexpr size_t WARN_MAX<CheckedLength<LENGTH, AT, CHECK>> = WARN_MAX<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");
|
||||
// flush_() copies a partial frame on the stack
|
||||
static_assert(N >= 2 && N <= 1024, "LengthFrameReader size out of range");
|
||||
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");
|
||||
static_assert(((frame_reader_detail::WARN_MAX<typename FORMATS::Length> <= N) && ...),
|
||||
"A WarnIfLonger MAX above N lets longer frames be skipped without a warning");
|
||||
|
||||
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 idle too long: hands over the frames a corrupt length holds back inside it, else keeps it for
|
||||
/// a slow UART. UARTDevice::read_frames() calls this.
|
||||
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_; }
|
||||
|
||||
/// Whether a frame is coming in: a partial frame that an idle flush has not searched and kept.
|
||||
bool receiving() const { return this->pos_ != 0 && this->held_end_ != this->pos_; }
|
||||
|
||||
/// Forget a partial frame an idle flush kept, before a request starts a new exchange; safe inside a frame handler.
|
||||
void drop_kept() {
|
||||
if (this->pos_ != 0 && this->held_end_ == this->pos_)
|
||||
this->reset();
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
// A byte that starts or ends a frame clears the searched mark, so it cannot match a later partial frame
|
||||
this->held_end_ = 0;
|
||||
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; or, after flush() kept a partial frame, the pos_ it
|
||||
// searched
|
||||
pos_t held_end_{0};
|
||||
uint8_t buf_[N];
|
||||
};
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#undef ESPHOME_FRAME_READER_COLD
|
||||
@@ -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
|
||||
@@ -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_();
|
||||
}
|
||||
|
||||
|
||||
@@ -140,4 +140,372 @@ 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; });
|
||||
}
|
||||
|
||||
// Takes every frame and keeps a copy
|
||||
struct Collect {
|
||||
Frames seen;
|
||||
bool operator()(const uint8_t *frame, size_t len) {
|
||||
this->seen.emplace_back(frame, frame + len);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// 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;
|
||||
Collect handle;
|
||||
// A corrupt length of 15 holds back two complete frames until flush()
|
||||
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x03, 0x09})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(handle.seen, Frames{});
|
||||
EXPECT_EQ(reader.length(), 9u);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x03, 0x09}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
reader.flush(handle); // nothing collected: nothing to do
|
||||
EXPECT_EQ(handle.seen.size(), 2u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FlushKeepsASlowFrameUntilTheRestArrives) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0x06, 0xA5, 0x03})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, Frames{});
|
||||
EXPECT_EQ(reader.length(), 4u);
|
||||
for (uint8_t c : {0x01, 0x02})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x06, 0xA5, 0x03, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FlushKeepsASlowFrameBehindTheFramesItHandsOver) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
// 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(handle.seen, (Frames{{0xA5, 0x04, 0x01, 0x02}}));
|
||||
EXPECT_EQ(reader.length(), 3u);
|
||||
for (uint8_t c : {0x22, 0x33})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x05, 0x11, 0x22, 0x33}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ReceivingUntilAnIdleFlushKeepsTheFrame) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
EXPECT_FALSE(reader.receiving());
|
||||
for (uint8_t c : {0xA5, 0x06, 0x01})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_TRUE(reader.receiving());
|
||||
reader.flush(handle);
|
||||
EXPECT_FALSE(reader.receiving());
|
||||
reader.feed(0x02, handle);
|
||||
EXPECT_TRUE(reader.receiving());
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, NewBytesAtTheSearchedLengthAreSearchedAgain) {
|
||||
// A5 with a whole-frame length at 5, and a fixed two-byte 6E frame
|
||||
LengthFrameReader<16, FrameFormat<FrameHeader<0xA5>, FrameLengthU8<LengthField{.offset = 5}>>,
|
||||
FrameFormat<FrameHeader<0x6E>, FrameFixedLength<2>>>
|
||||
reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0xA5, 0x00, 0x00, 0x6E})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
reader.feed(0x01, handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0x6E, 0x01}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResyncAfterASearchedFrameIsSearchedAgain) {
|
||||
// A5 with a whole-frame length at 3, and a fixed two-byte AA frame
|
||||
LengthFrameReader<6, FrameFormat<FrameHeader<0xA5>, FrameLengthU8<LengthField{.offset = 3}>>,
|
||||
FrameFormat<FrameHeader<0xAA>, FrameFixedLength<2>>>
|
||||
reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0xA5, 0xAA})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
reader.feed(0x07, handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xAA, 0x07}}));
|
||||
}
|
||||
|
||||
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, DropKeptLeavesAFrameStillComingIn) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0x06, 0x01})
|
||||
reader.feed(c, handle);
|
||||
reader.drop_kept();
|
||||
EXPECT_EQ(reader.length(), 3u);
|
||||
reader.flush(handle);
|
||||
reader.drop_kept();
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, DropKeptInsideAHandlerKeepsTheHeldFrames) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Frames seen;
|
||||
auto handle = [&reader, &seen](const uint8_t *frame, size_t len) {
|
||||
seen.emplace_back(frame, frame + len);
|
||||
reader.drop_kept();
|
||||
return frame[1] != 0x09;
|
||||
};
|
||||
for (uint8_t c : {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x03, 0x02, 0x00})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(seen,
|
||||
(Frames{{0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x03, 0x02, 0x00}, {0xA5, 0x03, 0x01}, {0xA5, 0x03, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, IdleAfterHandledFrameFindsNothingInIt) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
// 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(handle.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>>;
|
||||
|
||||
static size_t &warned_len() {
|
||||
static size_t len = 0;
|
||||
return len;
|
||||
}
|
||||
static void note_too_long(size_t len) { warned_len() = len; }
|
||||
|
||||
TEST(LengthFrameReaderTest, WarnIfLongerRejectsAndReports) {
|
||||
LengthFrameReader<
|
||||
8, FrameFormat<FrameHeader<0xA5>, WarnIfLonger<FrameLengthU8<LengthField{.offset = 1}>, 8, note_too_long>>>
|
||||
reader;
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x09, 0xA5, 0x03, 0x42}), (Frames{{0xA5, 0x03, 0x42}}));
|
||||
EXPECT_EQ(warned_len(), 9u);
|
||||
}
|
||||
|
||||
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
|
||||
@@ -129,7 +129,7 @@ TEST_F(DalyBmsRequestCycleTest, BufferedBytesHoldTheNextRequest) {
|
||||
EXPECT_EQ(last_request(this->uart_), 0x91);
|
||||
}
|
||||
|
||||
// A partly received frame holds the next request, even after the quiet gap, until the receive reset drops it.
|
||||
// A kept partial frame holds the early trigger; the response timeout sends the next request, which clears it.
|
||||
TEST_F(DalyBmsRequestCycleTest, PartialFrameHoldsTheNextRequest) {
|
||||
receive(this->uart_, response_frame(0x90));
|
||||
loop_at(this->bms_, 1010);
|
||||
@@ -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.
|
||||
|
||||
@@ -77,13 +77,18 @@ class LD2410SWriteTest : public ::testing::Test {
|
||||
LoopBlockingGuard guard{nullptr, nullptr, now};
|
||||
this->radar_.loop();
|
||||
}
|
||||
// Runs init until the configuration-mode-off acknowledgement is taken, then queues one change
|
||||
void finish_init_(uint32_t now) {
|
||||
// Runs init until the configuration-mode-off acknowledgement is taken; returns the time it stopped at
|
||||
uint32_t run_init_(uint32_t now) {
|
||||
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;
|
||||
}
|
||||
return now;
|
||||
}
|
||||
// Runs init, then queues one change
|
||||
void finish_init_(uint32_t now) {
|
||||
now = this->run_init_(now);
|
||||
ASSERT_EQ(this->uart_.commands, INIT_COMMANDS);
|
||||
ASSERT_EQ(this->uart_.available(), 0u);
|
||||
ASSERT_TRUE(this->radar_.set_parameter(Parameter::PARAMETER_NO_DELAY, 30));
|
||||
@@ -176,4 +181,18 @@ 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) {
|
||||
const uint32_t now = this->run_init_(START_FAR_FROM_WRAP);
|
||||
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
|
||||
@@ -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();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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); // idle pass: searched and kept
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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,66 @@ TEST(UARTReadAvailableTest, DiscardStopsOnReadFailure) {
|
||||
EXPECT_EQ(uart.read_sizes.size(), 3u);
|
||||
}
|
||||
|
||||
// Keeps a copy of each frame; takes every frame except those whose length byte is reject_len
|
||||
struct Collect {
|
||||
std::vector<std::vector<uint8_t>> frames;
|
||||
uint8_t reject_len{0};
|
||||
bool operator()(const uint8_t *f, size_t len) {
|
||||
this->frames.emplace_back(f, f + len);
|
||||
return f[1] != this->reject_len;
|
||||
}
|
||||
};
|
||||
|
||||
// AA, length byte, then that many bytes
|
||||
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;
|
||||
Collect handle;
|
||||
uint32_t last_rx = 0;
|
||||
EXPECT_TRUE(dev.read_frames(reader, handle, 500, last_rx));
|
||||
EXPECT_EQ(last_rx, 500u);
|
||||
EXPECT_EQ(handle.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;
|
||||
Collect handle{.reject_len = 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(handle.frames.empty());
|
||||
dev.read_frames(reader, handle, 1100, last_rx, 100);
|
||||
EXPECT_EQ(handle.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;
|
||||
Collect handle;
|
||||
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(handle.frames, (std::vector<std::vector<uint8_t>>{{0xAA, 0x02, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(UARTReadFramesTest, ReportsAFailedRead) {
|
||||
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x01, 0x07});
|
||||
uart.fail_after_reads = 0;
|
||||
UARTDevice dev(&uart);
|
||||
GapReader reader;
|
||||
Collect handle;
|
||||
uint32_t last_rx = 0;
|
||||
EXPECT_FALSE(dev.read_frames(reader, handle, 500, last_rx));
|
||||
}
|
||||
|
||||
} // 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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"]
|
||||
# Later bytes completed phase 4's truncated frame, which was then rejected
|
||||
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(
|
||||
|
||||
Reference in new issue
Block a user