Compare commits

..
57 changed files with 1716 additions and 1310 deletions

No files matched your search

+1 -1
View File
@@ -120,7 +120,7 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| hand-written `set_x_sensor()` plus `x_sensor_` member | `SUB_SENSOR(x)`, `SUB_BINARY_SENSOR`, `SUB_TEXT_SENSOR`, `SUB_SWITCH`, ... |
| `if CONF_X in config: s = await sensor.new_sensor(config[CONF_X])` plus setter | `sensors = sensor.sub_sensors(config)` then `await sensors(CONF_X, hub.set_x_sensor)` |
| hand-written `{"a": MyEnum.MY_ENUM_A, ...}` dict | `MyEnum.options("a", "b", prefix="MY_ENUM_")` |
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>`, `LengthFrameReader<N, FrameFormat<...>...>` |
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>` |
| 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)` |
+1 -2
View File
@@ -246,8 +246,7 @@ 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...>`, frames that give their own length
with `LengthFrameReader<N, FrameFormat<FrameLengthU16LE<POS, ADD>, HEADER...>...>`; I2C has `update_register`,
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`; 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,6 +2,7 @@
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iterator>
#include "esphome/core/application.h"
@@ -13,6 +14,8 @@ 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.
@@ -118,29 +121,55 @@ void AirtonSerialClimate::setup() {
void AirtonSerialClimate::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto accept = [this](const uint8_t *frame, size_t len) { return this->accept_frame_(frame, len); };
bool received = false;
this->read_available([this, &received, &accept](uint8_t byte) {
this->read_available([this, &received](uint8_t byte) {
received = true;
this->rx_reader_.feed(byte, accept);
this->handle_byte_(byte);
});
if (received) {
this->last_rx_ms_ = now;
} else if (this->rx_reader_.length() > 0 && now - this->last_rx_ms_ >= FRAME_GAP_MS) {
} 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.
this->rx_reader_.flush(accept);
while (this->rx_pos_ > 0)
this->drop_first_byte_();
}
}
bool AirtonSerialClimate::accept_frame_(const uint8_t *frame, size_t len) {
if (len < MIN_FRAME_LEN)
return false;
if (crc16(frame, len - 2) != encode_uint16(frame[len - 2], frame[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_);
}
this->handle_frame_(frame, len);
return true;
}
void AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t 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,8 +24,6 @@ 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 MAX_FRAME_LEN = 64;
/// Climate on the Airton serial bus. The ESP takes the place of the original Wi-Fi module (address 0x21):
@@ -63,13 +61,16 @@ 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);
bool accept_frame_(const 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);
void handle_a3_(const uint8_t *data);
void handle_ac_(const uint8_t *data);
void publish_settings_();
LengthFrameReader<MAX_FRAME_LEN, FrameFormat<FrameLengthU8<LENGTH_POS>, SYNC_BYTE, SYNC_BYTE>> rx_reader_;
std::array<uint8_t, MAX_FRAME_LEN> rx_buffer_;
uint8_t rx_pos_{0};
uint8_t flags_{FLAG_DISPLAY};
bool state_received_{false};
uint8_t swing_{0}; // Raw swing byte
+60 -29
View File
@@ -99,53 +99,80 @@ void APC1Component::loop() {
}
}
auto handle = [this](const uint8_t *frame, size_t len) { return this->parse_frame_(frame, len); };
if (this->reader_.length() > 0 && now - this->last_transmission_ > APC1_RX_IDLE_TIMEOUT_MS) {
ESP_LOGV(TAG, "Timed out waiting for data, looking for frames in the partial one");
this->reader_.flush(handle);
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, &handle](uint8_t byte) {
this->read_available([this, now](uint8_t byte) {
this->last_transmission_ = now;
this->reader_.feed(byte, handle);
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;
}
});
}
bool APC1Component::parse_frame_(const uint8_t *frame, uint8_t total_len) {
// The payload carries at least the checksum
if (total_len < APC1_FRAME_HEADER_SIZE + 2) {
ESP_LOGW(TAG, "Invalid frame length: %d", total_len - APC1_FRAME_HEADER_SIZE);
return false;
}
uint16_t expected_checksum = encode_uint16(frame[total_len - 2], frame[total_len - 1]);
uint16_t calculated_checksum = sum16_bytes(frame, total_len - 2);
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);
if (expected_checksum != calculated_checksum) {
ESP_LOGW(TAG, "APC1 checksum mismatch: calculated 0x%04X != expected 0x%04X", calculated_checksum,
expected_checksum);
return false;
return;
}
if (total_len == APC1_FRAME_SIZE_MEASUREMENT) {
this->parse_measurement_frame_(frame);
this->parse_measurement_frame_();
} else if (total_len == APC1_FRAME_SIZE_DEVICE_INFO) {
this->parse_device_info_frame_(frame);
this->parse_device_info_frame_();
} else if (total_len == APC1_FRAME_SIZE_COMMAND_RESPONSE) {
ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", frame[4], frame[5]);
ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", this->rx_buffer_[4], this->rx_buffer_[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_(const uint8_t *frame) {
void APC1Component::parse_measurement_frame_() {
const uint32_t now = App.get_loop_component_start_time();
this->last_valid_frame_ = now;
uint8_t error_code = frame[APC1_MEASUREMENT_OFFSET_ERROR_CODE];
uint8_t error_code = this->rx_buffer_[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++) {
@@ -162,7 +189,7 @@ void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
PUBLISH_STATE(this->error_code_sensor_, error_code);
}
uint8_t aqi = frame[APC1_MEASUREMENT_OFFSET_AQI];
uint8_t aqi = this->rx_buffer_[APC1_MEASUREMENT_OFFSET_AQI];
if (aqi == 0) {
if (!this->gas_warming_up_) {
this->gas_warming_up_ = true;
@@ -176,9 +203,12 @@ void APC1Component::parse_measurement_frame_(const uint8_t *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 = [frame](uint8_t offset) { return encode_uint16(frame[offset], frame[offset + 1]); };
const auto u32 = [frame](uint8_t offset) {
return encode_uint32(frame[offset], frame[offset + 1], frame[offset + 2], frame[offset + 3]);
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);
@@ -221,11 +251,12 @@ void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
PUBLISH_STATE(this->rs3_sensor_, u32(54));
}
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]);
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]);
ESP_LOGI(TAG, "APC1: Module: %.6s, Serial: %08" PRIX32 "%08" PRIX32 ", Firmware: 0x%04X (%u)",
reinterpret_cast<const char *>(frame + APC1_DEVICE_INFO_OFFSET_MODULE),
reinterpret_cast<const char *>(this->rx_buffer_.data() + 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);
}
+5 -8
View File
@@ -1,7 +1,6 @@
#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"
@@ -80,19 +79,17 @@ 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_();
/// Returns false for a frame that is too short or 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);
void parse_frame_(uint16_t total_len);
void parse_measurement_frame_();
void parse_device_info_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};
LengthFrameReader<APC1_FRAME_SIZE_MEASUREMENT,
FrameFormat<FrameLengthU16BE<2, APC1_FRAME_HEADER_SIZE>, APC1_HEADER_1, APC1_HEADER_2>>
reader_;
std::array<uint8_t, APC1_FRAME_SIZE_MEASUREMENT> rx_buffer_{};
uint8_t rx_index_{0};
uint8_t last_error_code_{0xFF};
bool active_mode_{true};
bool idle_{false};
+134 -110
View File
@@ -1,5 +1,6 @@
#include "daly_bms.h"
#include <algorithm>
#include <vector>
#include "esphome/core/application.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
@@ -8,7 +9,7 @@ namespace esphome::daly_bms {
ESPHOME_LOG_TAG(TAG, "daly_bms");
static constexpr uint32_t DALY_RX_IDLE_TIMEOUT_MS = 200;
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,12 +49,13 @@ void DalyBmsComponent::update() {
void DalyBmsComponent::loop() {
const uint32_t now = App.get_loop_component_start_time();
const size_t avail = this->available();
auto handle = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
if (this->reader_.length() > 0 && (now - this->last_transmission_ >= DALY_RX_IDLE_TIMEOUT_MS)) {
ESP_LOGW(TAG, "Last transmission too long ago, dropping the partial frame");
this->reader_.flush(handle);
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->reader_.length() == 0 && avail == 0 &&
if (this->response_complete_() && !this->receiving_ && avail == 0 &&
(now - this->last_transmission_ >= DALY_RESPONSE_GAP_MS) && !this->trigger_next_) {
// response complete and nothing more on the line -> trigger next request without waiting for the timeout
this->last_transmission_ = now;
@@ -66,7 +68,23 @@ void DalyBmsComponent::loop() {
}
if (avail > 0)
this->last_transmission_ = now;
this->read_available([this, &handle](uint8_t c) { this->reader_.feed(c, handle); }, avail);
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;
@@ -125,122 +143,128 @@ void DalyBmsComponent::request_data_(uint8_t data_id) {
this->flush();
}
bool DalyBmsComponent::handle_frame_(const uint8_t *frame, size_t len) {
// Only BMS responses (address 0x01) carry data; an echoed request is skipped like noise
if (len != DALY_FRAME_SIZE || frame[1] != 0x01)
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 a valid frame answering the last request counts; an echoed request or a late answer does not
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]) {
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]) {
#ifdef USE_SENSOR
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_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_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_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_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;
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;
#endif
case DALY_REQUEST_MOS:
case DALY_REQUEST_MOS:
#ifdef USE_TEXT_SENSOR
if (this->status_text_sensor_ != nullptr) {
switch (frame[4]) {
case 0:
this->status_text_sensor_->publish_state("Stationary");
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
break;
case 1:
this->status_text_sensor_->publish_state("Charging");
#ifdef USE_SENSOR
case DALY_REQUEST_STATUS:
PUBLISH_STATE(this->cells_number_sensor_, it[4]);
break;
case 2:
this->status_text_sensor_->publish_state("Discharging");
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);
}
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]);
}
#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;
std::advance(it, DALY_FRAME_SIZE);
} else {
std::advance(it, 1);
}
}
return true;
}
} // namespace esphome::daly_bms
+6 -7
View File
@@ -2,7 +2,6 @@
#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
@@ -14,9 +13,9 @@
#endif
#include "esphome/components/uart/uart.h"
namespace esphome::daly_bms {
#include <vector>
static constexpr uint8_t DALY_FRAME_SIZE = 13;
namespace esphome::daly_bms {
class DalyBmsComponent final : public PollingComponent, public uart::UARTDevice {
public:
@@ -77,13 +76,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;
/// Returns false for a frame that is not a BMS response or fails the checksum
bool handle_frame_(const uint8_t *frame, size_t len);
void decode_data_(std::vector<uint8_t> data);
uint8_t addr_;
// A5, address, data ID, length 8, 8 data bytes, sum8; every request and response has 8 data bytes
LengthFrameReader<DALY_FRAME_SIZE, FrameFormat<FrameLengthU8<3, 5>, 0xA5>> reader_;
std::vector<uint8_t> data_;
bool receiving_{false};
uint8_t data_count_{0};
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.
+75 -56
View File
@@ -119,9 +119,13 @@ 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];
@@ -227,15 +231,13 @@ void LD2410Component::restart_and_read_all_info() {
}
void LD2410Component::loop() {
this->read_available<MAX_LINE_LENGTH>([this](uint8_t c) {
this->reader_.feed(c, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
});
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
}
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_progmem(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -249,17 +251,19 @@ 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_progmem(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(50); // NOLINT
}
}
void LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
void LD2410Component::handle_periodic_data_() {
// 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 (len < 12 || frame[7] != HEADER || frame[len - 6] != FOOTER || frame[len - 5] != CHECK) {
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;
}
/*
@@ -267,8 +271,8 @@ void LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
0x01: Engineering mode
0x02: Normal mode
*/
bool engineering_mode = frame[DATA_TYPES] == 0x01;
if (len < (engineering_mode ? ENGINEERING_FRAME_MIN : PERIODIC_FRAME_MIN)) {
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
}
#ifdef USE_SWITCH
@@ -281,7 +285,7 @@ void LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
0x02 = Still targets
0x03 = Moving+Still targets
*/
const uint8_t target_state = frame[TARGET_STATES];
const uint8_t target_state = this->buffer_data_[TARGET_STATES];
#ifdef USE_LD2410_BG_CORRECTION
// Pass or fail comes only from these frames
if (this->bg_correction_running_) {
@@ -308,13 +312,13 @@ void LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
*/
#ifdef USE_SENSOR
SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, frame[MOVING_ENERGY]);
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]);
SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, frame[STILL_ENERGY]);
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]);
SAFE_PUBLISH_SENSOR(this->detection_distance_sensor_,
encode_uint16(frame[DETECT_DISTANCE_HIGH], frame[DETECT_DISTANCE_LOW]));
encode_uint16(this->buffer_data_[DETECT_DISTANCE_HIGH], this->buffer_data_[DETECT_DISTANCE_LOW]));
if (engineering_mode) {
/*
@@ -323,18 +327,18 @@ void LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
Moving energy: 20~28th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], frame[MOVING_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[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], frame[STILL_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
}
/*
Light sensor: 38th bytes
*/
SAFE_PUBLISH_SENSOR(this->light_sensor_, frame[LIGHT_SENSOR]);
SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
} else {
for (auto &gate_move_sensor : this->gate_move_sensors_) {
SAFE_PUBLISH_SENSOR_UNKNOWN(gate_move_sensor);
@@ -346,7 +350,8 @@ void LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
}
#endif
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->out_pin_presence_status_binary_sensor_, engineering_mode ? frame[OUT_PIN_SENSOR] == 0x01 : false);
PUBLISH_STATE(this->out_pin_presence_status_binary_sensor_,
engineering_mode ? this->buffer_data_[OUT_PIN_SENSOR] == 0x01 : false);
#endif
}
@@ -358,24 +363,24 @@ void set_number_value(number::Number *n, float value) {
}
#endif
void 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) {
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) {
ESP_LOGE(TAG, "Invalid status");
return;
}
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
if (this->buffer_data_[8] || this->buffer_data_[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[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 (frame[COMMAND] == CMD_BG_CORRECTION_START) {
if (this->buffer_data_[COMMAND] == CMD_BG_CORRECTION_START) {
this->finish_background_correction_(BgCorrectionResult::BG_CORRECTION_RESULT_REFUSED);
}
#endif
return;
}
switch (frame[COMMAND]) {
switch (this->buffer_data_[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -395,10 +400,10 @@ void LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_VERSION: {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -409,12 +414,12 @@ void LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_DISTANCE_RESOLUTION: {
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the resolution
}
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, frame[10]);
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
if (!index) {
ESP_LOGW(TAG, "Unknown distance resolution %u", frame[10]);
ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
break;
}
ESP_LOGV(TAG, "Distance resolution: %s",
@@ -426,12 +431,12 @@ void LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_LIGHT_CONTROL: {
if (len < 13 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 13 + HEADER_FOOTER_SIZE) {
break; // too short to hold the light settings
}
this->light_function_ = frame[10];
this->light_threshold_ = frame[11];
this->out_pin_level_ = frame[12];
this->light_function_ = this->buffer_data_[10];
this->light_threshold_ = this->buffer_data_[11];
this->out_pin_level_ = this->buffer_data_[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
@@ -444,11 +449,11 @@ void LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
}
case CMD_QUERY_MAC_ADDRESS: {
if (len < 20) {
if (this->buffer_pos_ < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[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);
@@ -472,7 +477,7 @@ void LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_BG_CORRECTION_QUERY: {
const uint8_t status = frame[10];
const uint8_t status = this->buffer_data_[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 ||
@@ -501,34 +506,34 @@ void LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY: { // Query parameters response
if (len < 38) {
if (this->buffer_pos_ < 38) {
break; // too short to hold the parameters
}
if (frame[10] != HEADER)
if (this->buffer_data_[10] != HEADER)
return; // 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_, frame[12]);
set_number_value(this->max_still_distance_gate_number_, frame[13]);
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]);
/*
Moving Sensitivities: 15~23th bytes
*/
for (size_t i = 0; i < TOTAL_GATES; i++) {
set_number_value(this->gate_move_threshold_numbers_[i], frame[14 + i]);
set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[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], frame[23 + i]);
set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[23 + i]);
}
/*
None Duration: 33~34th bytes
*/
set_number_value(this->timeout_number_, encode_uint16(frame[33], frame[32]));
set_number_value(this->timeout_number_, encode_uint16(this->buffer_data_[33], this->buffer_data_[32]));
#endif
break;
}
@@ -537,19 +542,33 @@ void LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
}
// 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");
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)) {
return false;
}
if (frame[0] == ld24xx::DataFrameFormat::FIRST) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->handle_periodic_data_(frame, len);
} else {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_(frame, len);
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
}
+6 -4
View File
@@ -145,9 +145,10 @@ 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_(const uint8_t *frame, uint8_t len);
void handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void readline_(int readch);
void query_parameters_();
void get_version_();
void get_mac_();
@@ -163,7 +164,8 @@ class LD2410Component final : public Component, public uart::UARTDevice {
uint8_t light_function_ = 0;
uint8_t light_threshold_ = 0;
uint8_t out_pin_level_ = 0;
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat> reader_;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
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};
bool bluetooth_on_{false};
+117 -23
View File
@@ -9,9 +9,13 @@ namespace esphome::ld2410s {
ESPHOME_LOG_TAG(TAG, "ld2410s");
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
static constexpr uint8_t SHORT_DATA_FRAME_FOOTER = 0x62;
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;
@@ -94,9 +98,7 @@ void LD2410SComponent::dump_config() {
}
void LD2410SComponent::loop() {
if (!this->read_available<16>([this](uint8_t c) {
this->reader_.feed(c, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
})) {
if (!this->read_available<16>([this](uint8_t b) { this->receive_byte_(b); })) {
ESP_LOGV(TAG, "UART read failed");
}
const uint32_t now = App.get_loop_component_start_time();
@@ -248,36 +250,128 @@ void LD2410SComponent::send_command_(uint16_t command) {
#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)) {
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, frame, len, ' '));
ESP_LOGV(TAG, "Footer does not match header: %s",
format_hex_pretty_to(hex_buf, this->rx_buffer_, this->rx_len_, ' '));
#endif
this->count_dropped_frame_();
return false;
}
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 : ld24xx::HEADER_FOOTER_SIZE);
if (type == ld24xx::CmdFrameFormat::FIRST) {
this->handle_command_ack_(payload, payload_len);
} else if (!this->handle_data_frame_(payload, payload_len, type == ld24xx::DataFrameFormat::FIRST)) {
this->count_dropped_frame_();
} else {
this->last_frame_at_ = App.get_loop_component_start_time();
this->dropped_frames_ = 0;
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;
}
return true;
}
bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len, bool standard) {
bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len) {
// 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 (standard) {
if (this->frame_type_ == FrameType::STD_DATA) {
if (len < 4 || payload[0] != DATA_TYPE_STANDARD) {
if (len >= 1) {
ESP_LOGV(TAG, "Ignoring data frame type %02X", payload[0]);
+16 -6
View File
@@ -9,8 +9,8 @@
#endif
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor.h"
#endif
#include "esphome/components/ld24xx/ld24xx.h"
#endif
#ifdef USE_LD2410S_VERSION
#include "esphome/components/text_sensor/text_sensor.h"
#endif
@@ -26,8 +26,6 @@ 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<FrameFixedLength<5>, 0x6E>;
/// The module's common parameters, in the order the parameter read answers them
enum class Parameter : uint8_t {
@@ -80,10 +78,13 @@ 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_(const uint8_t *frame, uint8_t len);
bool handle_frame_();
/// 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, bool standard);
bool handle_data_frame_(const uint8_t *payload, uint16_t len);
void handle_command_ack_(const uint8_t *payload, uint16_t len);
#ifdef USE_LD2410S_PARAMETERS
bool handle_parameters_(const uint8_t *values, uint16_t len);
@@ -96,6 +97,11 @@ 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);
@@ -116,12 +122,16 @@ class LD2410SComponent final : public Component, public uart::UARTDevice {
#ifdef USE_LD2410S_PARAMETERS
uint8_t parameters_[PARAMETER_COUNT]{}; // all fit a byte: gates, seconds, tenths of a hertz, speed
#endif
LengthFrameReader<RX_BUFFER_SIZE, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat, ShortDataFrameFormat> reader_;
uint8_t rx_buffer_[RX_BUFFER_SIZE];
uint8_t rx_len_{0};
uint8_t expected_len_{0};
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
+77 -59
View File
@@ -113,9 +113,13 @@ 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() {
@@ -230,15 +234,13 @@ void LD2412Component::restart_and_read_all_info() {
}
void LD2412Component::loop() {
this->read_available<MAX_LINE_LENGTH>([this](uint8_t c) {
this->reader_.feed(c, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
});
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
}
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_progmem(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
this->write_array(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -253,7 +255,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_progmem(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
this->write_array(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(30); // NOLINT
@@ -261,10 +263,11 @@ void LD2412Component::send_command_(uint8_t command, const uint8_t *command_valu
delay(20); // NOLINT
}
void LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
void LD2412Component::handle_periodic_data_() {
// 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 (len < 12 || frame[7] != HEADER || frame[len - 6] != FOOTER) {
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;
}
/*
@@ -272,8 +275,8 @@ void LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
0x01: Engineering mode
0x02: Normal mode
*/
bool engineering_mode = frame[DATA_TYPES] == 0x01;
if (len < PERIODIC_FRAME_MIN) {
bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
if (this->buffer_pos_ < PERIODIC_FRAME_MIN) {
return; // too short to hold the values
}
#ifdef USE_SWITCH
@@ -288,7 +291,7 @@ void LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
0x02 = Still targets
0x03 = Moving+Still targets
*/
char target_state = frame[TARGET_STATES];
char target_state = this->buffer_data_[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);
@@ -302,23 +305,24 @@ void LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
*/
#ifdef USE_SENSOR
SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, frame[MOVING_ENERGY]);
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]);
SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, frame[STILL_ENERGY]);
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]);
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(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]);
new_detect_distance =
encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]);
} else if (target_state != 0x00) {
new_detect_distance = encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]);
new_detect_distance = encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]);
}
this->detection_distance_sensor_.publish_state_if_not_dup(new_detect_distance);
}
if (engineering_mode) {
if (len < ENGINEERING_FRAME_MIN) {
ESP_LOGW(TAG, "Engineering mode packet too short: %u", len);
if (this->buffer_pos_ < ENGINEERING_FRAME_MIN) {
ESP_LOGW(TAG, "Engineering mode packet too short: %u", this->buffer_pos_);
} else {
/*
Moving distance range: 18th byte
@@ -326,18 +330,18 @@ void LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
Moving energy: 20~28th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], frame[MOVING_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[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], frame[STILL_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
}
/*
Light sensor value
*/
SAFE_PUBLISH_SENSOR(this->light_sensor_, frame[LIGHT_SENSOR]);
SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
}
} else {
for (auto &gate_move_sensor : this->gate_move_sensors_) {
@@ -374,18 +378,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_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", frame[COMMAND]);
if (frame[COMMAND_STATUS] != 0x01) {
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) {
ESP_LOGW(TAG, "Invalid status");
return;
}
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
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;
}
switch (frame[COMMAND]) {
switch (this->buffer_data_[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -405,10 +409,10 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_VERSION: {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -418,12 +422,12 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
}
case CMD_QUERY_DISTANCE_RESOLUTION: {
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the resolution
}
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, frame[10]);
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
if (!index) {
ESP_LOGW(TAG, "Unknown distance resolution %u", frame[10]);
ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
break;
}
ESP_LOGV(TAG, "Distance resolution: %s",
@@ -435,11 +439,11 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_LIGHT_CONTROL: {
if (len < 12 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + HEADER_FOOTER_SIZE) {
break; // too short to hold the light settings
}
this->light_function_ = frame[10];
this->light_threshold_ = frame[11];
this->light_function_ = this->buffer_data_[10];
this->light_threshold_ = this->buffer_data_[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_));
@@ -451,11 +455,11 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_MAC_ADDRESS: {
if (len < 20) {
if (this->buffer_pos_ < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[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);
@@ -474,11 +478,11 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the state
}
ESP_LOGV(TAG, "Handled query dynamic background correction");
bool dynamic_background_correction_active = (frame[10] != 0x00);
bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->dynamic_background_correction_status_binary_sensor_, dynamic_background_correction_active);
#endif
@@ -497,17 +501,17 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
case CMD_QUERY_MOTION_GATE_SENS:
case CMD_QUERY_STATIC_GATE_SENS: {
#ifdef USE_NUMBER
if (len != GATE_SENS_ACK_SIZE) {
if (this->buffer_pos_ != GATE_SENS_ACK_SIZE) {
// A length this driver does not know
ESP_LOGW(TAG, "Dropping gate threshold answer of %u bytes", len);
ESP_LOGW(TAG, "Dropping gate threshold answer of %u bytes", this->buffer_pos_);
return;
}
const bool motion = frame[COMMAND] == CMD_QUERY_MOTION_GATE_SENS;
const bool motion = this->buffer_data_[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] = frame[ACK_PAYLOAD + i];
group.last_read[i] = this->buffer_data_[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]);
@@ -524,17 +528,17 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_BASIC_CONF: { // Query parameters response
if (len < 15 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 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_ = frame[10];
this->max_gate_ = frame[11];
this->timeout_ = encode_uint16(frame[13], frame[12]);
this->out_pin_level_ = frame[14];
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];
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
@@ -566,19 +570,33 @@ void LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
}
// 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");
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)) {
return false;
}
if (frame[0] == ld24xx::DataFrameFormat::FIRST) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->handle_periodic_data_(frame, len);
} else {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_(frame, len);
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
}
+6 -4
View File
@@ -134,10 +134,11 @@ 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_(const uint8_t *frame, uint8_t len);
void handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void basic_conf_timeout_();
void readline_(int readch);
void query_parameters_();
void get_version_();
void get_mac_();
@@ -167,7 +168,8 @@ 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;
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat> reader_;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
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};
bool bluetooth_on_{false};
+76 -49
View File
@@ -71,11 +71,14 @@ static constexpr uint8_t CMD_SET_ZONE = 0xC2;
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
using ld24xx::HEADER_FOOTER_SIZE;
// Periodic data frame footer
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};
// 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; };
@@ -101,6 +104,19 @@ 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();
@@ -431,14 +447,14 @@ bool LD2450Component::get_timeout_status_(uint32_t check_millis) {
}
// Extract, store and publish zone details LD2450 buffer
void LD2450Component::process_zone_(const uint8_t *frame) {
void LD2450Component::process_zone_() {
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>(&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]);
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]);
#ifdef USE_NUMBER
// only one null check as all coordinates are required for a single zone
if (this->zone_numbers_[index].x1 != nullptr) {
@@ -488,7 +504,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_progmem(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -502,7 +518,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_progmem(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(50); // NOLINT
@@ -512,7 +528,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_(const uint8_t *frame) {
void LD2450Component::handle_periodic_data_() {
int16_t target_count = 0;
int16_t still_target_count = 0;
int16_t moving_target_count = 0;
@@ -534,18 +550,18 @@ void LD2450Component::handle_periodic_data_(const uint8_t *frame) {
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(frame[start], frame[start + 1]);
tx = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]);
// Y
start = TARGET_Y + index * 8;
ty = ld2450::decode_coordinate(frame[start], frame[start + 1]);
ty = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]);
#ifdef USE_SENSOR
// RESOLUTION
start = TARGET_RESOLUTION + index * 8;
res = encode_value_le<uint16_t>(&frame[start]);
res = encode_value_le<uint16_t>(&this->buffer_data_[start]);
#endif
// SPEED
start = TARGET_SPEED + index * 8;
ts = ld2450::decode_speed(frame[start], frame[start + 1]);
ts = ld2450::decode_speed(this->buffer_data_[start], this->buffer_data_[start + 1]);
if (ts) {
is_moving = true;
moving_target_count++;
@@ -700,18 +716,18 @@ void LD2450Component::handle_periodic_data_(const uint8_t *frame) {
this->data_callback_.call();
}
void 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) {
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) {
ESP_LOGE(TAG, "Invalid status");
return;
}
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
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;
}
switch (frame[COMMAND]) {
switch (this->buffer_data_[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -731,10 +747,10 @@ void LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_VERSION: {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -745,11 +761,11 @@ void LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_MAC_ADDRESS: {
if (len < 20) {
if (this->buffer_pos_ < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[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);
@@ -782,21 +798,21 @@ void LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_TARGET_MODE:
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 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_, frame[10] == 0x02);
PUBLISH_STATE(this->multi_target_switch_, this->buffer_data_[10] == 0x02);
#endif
break;
case CMD_QUERY_ZONE:
if (len < ZONE_ACK_FRAME_SIZE) {
if (this->buffer_pos_ < ZONE_ACK_FRAME_SIZE) {
break; // too short to hold the zones
}
ESP_LOGV(TAG, "Query zone conf");
this->zone_type_ = frame[10];
this->zone_type_ = this->buffer_data_[10];
this->publish_zone_type();
#ifdef USE_SELECT
if (this->zone_type_select_ != nullptr) {
@@ -804,16 +820,16 @@ void LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Change zone type to: %.*s", (int) zone.size(), zone.c_str());
}
#endif
if (frame[10] == 0x00) {
if (this->buffer_data_[10] == 0x00) {
ESP_LOGV(TAG, "Zone: Disabled");
}
if (frame[10] == 0x01) {
if (this->buffer_data_[10] == 0x01) {
ESP_LOGV(TAG, "Zone: Area detection");
}
if (frame[10] == 0x02) {
if (this->buffer_data_[10] == 0x02) {
ESP_LOGV(TAG, "Zone: Area filter");
}
this->process_zone_(frame);
this->process_zone_();
break;
case CMD_SET_ZONE:
@@ -826,29 +842,40 @@ void LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
}
void LD2450Component::readline_(uint8_t c) {
this->reader_.feed(c, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
// 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");
});
}
// 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] != DATA_FRAME_FOOTER[0] || end[-1] != DATA_FRAME_FOOTER[1] : !ld24xx::has_footer(frame, len)) {
if (this->invalid_frames_ < UINT16_MAX) {
this->invalid_frames_++;
// 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;
}
ESP_LOGW(TAG, "Invalid footer");
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)) {
return false;
}
if (periodic) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->on_valid_frame_();
this->handle_periodic_data_(frame);
} else {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_(frame, len);
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
}
+7 -8
View File
@@ -46,8 +46,6 @@ 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<FrameFixedLength<30>, 0xAA, 0xFF, 0x03, 0x00>;
// 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;
@@ -204,11 +202,11 @@ 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_(const uint8_t *frame);
void 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 readline_(uint8_t c);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void process_zone_();
void readline_(int readch);
void get_version_();
void get_mac_();
void query_target_tracking_mode_();
@@ -241,9 +239,10 @@ class LD2450Component : public Component, public uart::UARTDevice {
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 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};
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, PeriodicFrameFormat> reader_;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
uint8_t zone_type_ = 0;
bool bluetooth_on_{false};
LinkState link_state_{LinkState::LINK_STATE_WAITING};
+91 -22
View File
@@ -4,14 +4,19 @@
#include "esphome/core/helpers.h"
#include <cmath>
#include <cstring>
#include <numbers>
namespace esphome::ld2460 {
ESPHOME_LOG_TAG(TAG, "ld2460");
// Header (4), command (1), length (2), footer (4)
static constexpr uint8_t MIN_FRAME_LENGTH = 11;
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;
@@ -22,6 +27,32 @@ 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_(); }
@@ -51,15 +82,17 @@ void LD2460Component::dump_config() {
}
void LD2460Component::loop() {
this->read_available<MAX_FRAME_LENGTH>([this](uint8_t b) { this->readline_(b); });
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
}
void LD2460Component::handle_periodic_data_(const uint8_t *data, uint8_t packet_len) {
if (data[4] != CMD_REPORT_DATA) {
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) {
ESP_LOGW(TAG, "Invalid periodic data header");
return;
}
if ((packet_len - MIN_FRAME_LENGTH) % 4 != 0) {
const uint8_t packet_len = this->buffer_pos_;
if (packet_len < 11 || (packet_len - 11) % 4 != 0) {
ESP_LOGW(TAG, "Periodic packet length %u is not a whole number of targets", packet_len);
return;
}
@@ -76,7 +109,7 @@ void LD2460Component::handle_periodic_data_(const uint8_t *data, uint8_t packet_
}
#ifdef USE_SENSOR
uint8_t num_targets = std::min<uint8_t>((packet_len - MIN_FRAME_LENGTH) / 4, MAX_TARGETS);
uint8_t num_targets = std::min<uint8_t>((packet_len - 11) / 4, MAX_TARGETS);
for (uint8_t i = 0; i < MAX_TARGETS; i++) {
TargetSensors &t = this->target_sensors_[i];
if (i >= num_targets) {
@@ -125,24 +158,60 @@ void LD2460Component::handle_periodic_data_(const uint8_t *data, uint8_t packet_
}
void LD2460Component::readline_(uint8_t readch) {
this->reader_.feed(readch, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
}
// Handles the frame when its footer is in place; returns false otherwise
bool LD2460Component::handle_frame_(const uint8_t *frame, uint8_t len) {
if (len < MIN_FRAME_LENGTH || !ld24xx::has_footer(frame, len))
return false;
ESP_LOGV_HEX(TAG, frame, len, MAX_FRAME_LENGTH, "Frame: %s");
if (frame[0] == ld24xx::DataFrameFormat::FIRST) {
this->handle_periodic_data_(frame, len);
} else {
this->handle_ack_(frame, len);
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_);
}
}
return true;
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;
}
void LD2460Component::handle_ack_(const uint8_t *data, uint8_t len) {
if (len != ACK_FRAME_LENGTH) {
// 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) {
ESP_LOGW(TAG, "Dropping malformed command frame");
return;
}
+6 -8
View File
@@ -1,7 +1,6 @@
#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"
@@ -9,7 +8,7 @@
namespace esphome::ld2460 {
static constexpr uint8_t MAX_FRAME_LENGTH = 31; // A 5-target data frame
static constexpr uint8_t MAX_LINE_LENGTH = 32; // Longest frame is a 5-target data frame of 31 bytes
static constexpr uint8_t MAX_TARGETS = 5;
enum class InstallationMode : uint8_t {
@@ -41,10 +40,10 @@ class LD2460Component : public Component, public uart::UARTDevice {
protected:
void send_query_();
void handle_periodic_data_(const uint8_t *data, uint8_t packet_len);
void handle_ack_(const uint8_t *data, uint8_t len);
bool align_to_header_(const uint8_t *header);
void handle_periodic_data_();
void handle_ack_();
void readline_(uint8_t readch);
bool handle_frame_(const uint8_t *frame, uint8_t len);
#ifdef USE_SENSOR
// INT16_MIN marks a slot with no published coordinates, so the next report always publishes
@@ -57,9 +56,8 @@ class LD2460Component : public Component, public uart::UARTDevice {
#endif
LazyCallbackManager<void()> data_callback_;
// Header, command (1), length (2, little endian, counting the whole frame), payload, footer
LengthFrameReader<MAX_FRAME_LENGTH, ld24xx::DataFrame<FrameLengthU16LE<5>>, ld24xx::CmdFrame<FrameLengthU16LE<5>>>
reader_;
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.
+65 -18
View File
@@ -1,12 +1,13 @@
#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
@@ -78,26 +79,72 @@ 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; periodic data frames have
// their own header and footer
// Commands and their answers share this header, a little-endian byte count and this footer
static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
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};
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};
// Command and periodic data frame formats with the length rule LENGTH
template<class LENGTH> using CmdFrame = FrameFormat<LENGTH, 0xFD, 0xFC, 0xFB, 0xFA>;
template<class LENGTH> using DataFrame = FrameFormat<LENGTH, 0xF4, 0xF3, 0xF2, 0xF1>;
// The header, a little-endian payload length, the payload, then the footer
using PayloadLength = FrameLengthU16LE<HEADER_FOOTER_SIZE, 2 * HEADER_FOOTER_SIZE + 2>;
using CmdFrameFormat = CmdFrame<PayloadLength>;
using DataFrameFormat = DataFrame<PayloadLength>;
inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;
}
// 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;
// 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;
}
}
}
} // namespace esphome::ld24xx
+11 -13
View File
@@ -68,22 +68,20 @@ climate::ClimateTraits PioneerWT::traits() {
void PioneerWT::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto handle = [this](const uint8_t *frame, size_t len) {
if (!packet_valid(frame, len)) {
if (len >= HEADER_SIZE) {
ESP_LOGD(TAG, "Dropped a frame with a wrong checksum");
}
return false;
}
this->handle_frame_(frame, len);
return true;
};
if (const size_t count = this->available()) {
this->last_rx_ = now;
this->read_available([this, &handle](uint8_t byte) { this->reader_.feed(byte, handle); }, count);
} else if (this->reader_.length() != 0 && now - this->last_rx_ >= RX_GAP_MS) {
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()) {
ESP_LOGD(TAG, "Dropped a frame with a wrong checksum");
}
} 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_.flush(handle);
this->reader_.reset();
}
if (!this->queue_.empty() && now - this->last_send_ >= RESEND_INTERVAL_MS)
this->send_pending_();
@@ -11,6 +11,31 @@ 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,
@@ -103,14 +128,14 @@ 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] = FRAME_START_1;
out[1] = FRAME_START_2;
out[0] = 0xA5;
out[1] = 0x01;
out[2] = flags;
out[3] = type;
out[4] = seq;
out[5] = ack;
out[6] = 0x00;
out[LEN_POS] = total;
out[7] = total;
out[HEADER_SIZE] = class_1;
out[HEADER_SIZE + 1] = class_2;
if (len)
@@ -1,19 +1,16 @@
#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 MAX_FRAME_SIZE = 255;
static constexpr uint8_t FLAG_NO_ACK = 0x00;
@@ -48,14 +45,28 @@ 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 frames; packet_valid() checks them.
using PacketReader =
LengthFrameReader<MAX_FRAME_SIZE, FrameFormat<FrameLengthU8<LEN_POS>, FRAME_START_1, FRAME_START_2>>;
/// 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;
}
/// True when the frame is long enough to hold its checksum and the checksum matches.
inline bool packet_valid(const uint8_t *frame, size_t len) {
return len >= HEADER_SIZE && frame_crc(frame, len) == encode_uint16(frame[8], frame[9]);
}
protected:
std::array<uint8_t, MAX_FRAME_SIZE> buf_{};
uint8_t pos_{0};
bool checksum_error_{false};
};
/// Walks the attribute list in a status body. Stops at the first ID whose size is unknown.
class AttributeReader final {
+80 -45
View File
@@ -7,9 +7,10 @@ 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
// Drop a partial frame when the bytes stop mid-way
static constexpr uint32_t RX_IDLE_TIMEOUT_MS = 500;
static const uint16_t CMD_MEASUREMENT_MODE_PASSIVE =
0x0000; // use `Command::MANUAL_MEASUREMENT` to trigger a measurement
@@ -94,18 +95,9 @@ void PMSX003Component::loop() {
}
}
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;
};
if (this->reader_.length() > 0 && now - this->last_transmission_ >= RX_IDLE_TIMEOUT_MS) {
// last transmission too long ago; look for a frame in what arrived, then start over
this->reader_.flush(handle);
if (now - this->last_transmission_ >= 500) {
// last transmission too long ago. Reset RX index.
this->data_index_ = 0;
}
const size_t avail = this->available();
@@ -113,25 +105,72 @@ void PMSX003Component::loop() {
return;
this->last_transmission_ = now;
this->read_available([this, &handle](uint8_t byte) { this->reader_.feed(byte, handle); }, avail);
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);
}
bool PMSX003Component::check_frame_(const uint8_t *frame, size_t total_size) {
// start (16bit) + length (16bit) + DATA (payload_length - 16bit) + checksum (16bit)
const uint16_t payload_length = total_size - 4;
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);
optional<bool> PMSX003Component::check_byte_() {
const uint8_t index = this->data_index_;
const uint8_t byte = this->data_[index];
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);
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(frame, total_size - 2);
const uint16_t check = encode_uint16(frame[total_size - 2], frame[total_size - 1]);
const uint16_t checksum = sum16_bytes(this->data_, total_size - 2);
const uint16_t check = this->get_16_bit_uint_(total_size - 2);
if (checksum != check) {
ESP_LOGW(TAG, "PMSX003 checksum mismatch! 0x%02X != 0x%02X", checksum, check);
return false;
}
return true;
return {};
}
bool PMSX003Component::check_payload_length_(uint16_t payload_length) {
@@ -175,15 +214,11 @@ void PMSX003Component::send_command_(Command cmd, uint16_t data) {
}
}
void PMSX003Component::parse_data_(const uint8_t *frame) {
const auto get_16_bit_uint = [frame](uint8_t start_index) {
return encode_uint16(frame[start_index], frame[start_index + 1]);
};
void PMSX003Component::parse_data_() {
// PM mass concentrations
const uint16_t pm_1_0_std_concentration = get_16_bit_uint(4);
const uint16_t pm_2_5_std_concentration = get_16_bit_uint(6);
const uint16_t pm_10_0_std_concentration = get_16_bit_uint(8);
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);
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);
@@ -199,9 +234,9 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
const uint8_t pc_offset = is_luftmy ? 10 : 16;
if (!is_luftmy) {
const uint16_t pm_1_0_concentration = get_16_bit_uint(10);
const uint16_t pm_2_5_concentration = get_16_bit_uint(12);
const uint16_t pm_10_0_concentration = get_16_bit_uint(14);
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);
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);
@@ -212,10 +247,10 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
}
// Particle counts at pc_offset: >0.3, >0.5, >1.0, >2.5µm
const uint16_t pm_particles_03um = get_16_bit_uint(pc_offset);
const uint16_t pm_particles_05um = get_16_bit_uint(pc_offset + 2);
const uint16_t pm_particles_10um = get_16_bit_uint(pc_offset + 4);
const uint16_t pm_particles_25um = get_16_bit_uint(pc_offset + 6);
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);
PUBLISH_STATE(this->pm_particles_03um_sensor_, pm_particles_03um);
PUBLISH_STATE(this->pm_particles_05um_sensor_, pm_particles_05um);
@@ -228,8 +263,8 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
// 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 = get_16_bit_uint(pc_offset + 8);
const uint16_t pm_particles_100um = get_16_bit_uint(pc_offset + 10);
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);
ESP_LOGD(TAG, "Got PM5.0 Particles: %u Count/0.1L, PM10.0 Particles: %u Count/0.1L", pm_particles_50um,
pm_particles_100um);
@@ -240,7 +275,7 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
// Formaldehyde
if (this->type_ == Type::PMS5003S || this->type_ == Type::PMS5003ST) {
const uint16_t formaldehyde = get_16_bit_uint(28);
const uint16_t formaldehyde = this->get_16_bit_uint_(28);
ESP_LOGD(TAG, "Got Formaldehyde: %u µg/m^3", formaldehyde);
@@ -251,8 +286,8 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
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>(get_16_bit_uint(temperature_offset)) / 10.0f;
const float humidity = get_16_bit_uint(temperature_offset + 2) / 10.0f;
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;
ESP_LOGD(TAG, "Got Temperature: %.1f°C, Humidity: %.1f%%", temperature, humidity);
@@ -263,8 +298,8 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
// 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 = frame[firmware_error_code_offset];
const uint8_t error_code = frame[firmware_error_code_offset + 1];
const uint8_t firmware_version = this->data_[firmware_error_code_offset];
const uint8_t error_code = this->data_[firmware_error_code_offset + 1];
ESP_LOGD(TAG, "Got Firmware Version: 0x%02X, Error Code: 0x%02X", firmware_version, error_code);
}
+7 -9
View File
@@ -1,18 +1,12 @@
#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;
enum class Type : uint8_t {
PMS1003 = 0,
PMS3003,
@@ -73,15 +67,19 @@ class PMSX003Component final : public uart::UARTDevice, public Component {
SUB_SENSOR(humidity)
protected:
bool check_frame_(const uint8_t *frame, size_t total_size);
void parse_data_(const uint8_t *frame);
optional<bool> check_byte_();
void parse_data_();
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};
LengthFrameReader<MAX_FRAME_SIZE, FrameFormat<FrameLengthU16BE<2, 4>, START_CHARACTER_1, START_CHARACTER_2>> reader_;
uint8_t data_[64];
uint8_t data_index_{0};
uint32_t fan_on_time_{0};
uint32_t last_update_{0};
uint32_t last_transmission_{0};
@@ -82,12 +82,17 @@ 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]() {
@@ -104,30 +109,9 @@ void MR24HPC1Component::update_() {
this->poll_time_base_func_check_ = true; // Query the base functionality information at regular intervals
}
// 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); }
// The reader caps the data at 32 bytes; the 1 byte minimum, footer and sum are checked here
static bool frame_valid(const uint8_t *data, size_t len) {
if (len < 10 || 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->reader_.feed(b, [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_available([this](uint8_t b) { this->r24_split_data_frame_(b); });
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_)) {
@@ -262,8 +246,109 @@ 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_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_product_information_(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) {
@@ -304,7 +389,7 @@ void MR24HPC1Component::r24_frame_parse_product_information_(const uint8_t *data
}
// Parsing the underlying open parameters
void MR24HPC1Component::r24_frame_parse_open_underlying_information_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_open_underlying_information_(uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
case 0x00:
case 0x80:
@@ -397,7 +482,7 @@ void MR24HPC1Component::r24_frame_parse_open_underlying_information_(const uint8
}
}
void MR24HPC1Component::r24_parse_data_frame_(const uint8_t *data, uint8_t len) {
void MR24HPC1Component::r24_parse_data_frame_(uint8_t *data, uint8_t len) {
switch (data[FRAME_CONTROL_WORD_INDEX]) {
case 0x01: {
if (data[FRAME_COMMAND_WORD_INDEX] == 0x02) {
@@ -427,7 +512,7 @@ void MR24HPC1Component::r24_parse_data_frame_(const uint8_t *data, uint8_t len)
}
}
void MR24HPC1Component::r24_frame_parse_work_status_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_work_status_(uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
case 0x01:
case 0x81:
@@ -484,7 +569,7 @@ void MR24HPC1Component::r24_frame_parse_work_status_(const uint8_t *data) {
}
}
void MR24HPC1Component::r24_frame_parse_human_information_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_human_information_(uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
#ifdef USE_BINARY_SENSOR
case 0x01:
@@ -24,7 +24,6 @@
#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"
@@ -33,6 +32,19 @@
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,
@@ -123,20 +135,23 @@ class MR24HPC1Component final : public Component,
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_;
// 53 59, control, command, data length (high byte first), data, sum, 54 43
LengthFrameReader<FRAME_BUF_MAX_SIZE, FrameFormat<FrameLengthU16BE<4, 9>, FRAME_HEADER1_VALUE, FRAME_HEADER2_VALUE>>
reader_;
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];
int sg_start_query_data_;
bool check_dev_inf_sign_;
bool poll_time_base_func_check_;
bool module_ready_{false};
void update_();
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 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 send_query_(const uint8_t *query, size_t string_length);
public:
@@ -4,8 +4,7 @@
namespace esphome::seeed_mr24hpc1 {
// 6 header bytes, up to 32 data bytes, sum and 2 footer bytes
static constexpr uint8_t FRAME_BUF_MAX_SIZE = 41;
static const uint8_t FRAME_BUF_MAX_SIZE = 128;
static const uint8_t PRODUCT_BUF_MAX_SIZE = 32;
static const uint8_t FRAME_CONTROL_WORD_INDEX = 2;
@@ -27,6 +27,16 @@ 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.
*
@@ -42,50 +52,75 @@ 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;
}
static bool frame_valid(const uint8_t *frame, size_t len) {
const uint16_t frame_type = encode_uint16(frame[5], frame[6]);
bool MR60BHA2Component::validate_message_() {
size_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
if (at == 0) {
return new_byte == FRAME_HEADER_BUFFER;
}
if (at <= 2) {
return true;
}
uint16_t frame_id = encode_uint16(data[1], data[2]);
if (at <= 4) {
return true;
}
uint16_t length = encode_uint16(data[3], data[4]);
if (at <= 6) {
return true;
}
uint16_t frame_type = encode_uint16(data[5], data[6]);
if (frame_type != BREATH_RATE_TYPE_BUFFER && frame_type != HEART_RATE_TYPE_BUFFER &&
frame_type != DISTANCE_TYPE_BUFFER && frame_type != PEOPLE_EXIST_TYPE_BUFFER &&
frame_type != PRINT_CLOUD_BUFFER) {
return false;
}
if (!validate_checksum(frame, 7, frame[7])) {
ESP_LOGE(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", frame[7]);
ESP_LOGV_HEX(TAG, frame, 8, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
return false;
}
if (!validate_checksum(frame + 8, 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;
}
void MR60BHA2Component::loop() {
this->read_available([this](uint8_t b) {
this->reader_.feed(b, [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
return false;
this->handle_frame_(frame, len);
return true;
});
});
}
uint8_t header_checksum = new_byte;
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 + 8;
const size_t length = len - FRAME_OVERHEAD;
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");
return false;
}
return true;
}
// 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;
#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), frame, len));
this->process_frame_(frame_id, frame_type, 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;
}
void MR60BHA2Component::process_frame_(uint16_t frame_id, uint16_t frame_type, const uint8_t *data, size_t length) {
@@ -9,17 +9,12 @@
#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 constexpr uint8_t FRAME_HEADER_BUFFER = 0x01;
// Header, id, length and type bytes, header checksum, then the data and its checksum
static constexpr uint8_t FRAME_OVERHEAD = 9;
// Point cloud frames carry 4 bytes plus 16 per target; this holds 15 targets, the others at most 8 data bytes
static constexpr uint8_t FRAME_MAX_SIZE = 255;
static const uint8_t FRAME_HEADER_BUFFER = 0x01;
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;
@@ -44,11 +39,10 @@ class MR60BHA2Component final : public Component,
void loop() override;
protected:
void handle_frame_(const uint8_t *frame, size_t len);
bool validate_message_();
void process_frame_(uint16_t frame_id, uint16_t frame_type, const uint8_t *data, size_t length);
// 01, id (2), data length (2, high byte first), type (2), header checksum, data, data checksum
LengthFrameReader<FRAME_MAX_SIZE, FrameFormat<FrameLengthU16BE<3, FRAME_OVERHEAD>, FRAME_HEADER_BUFFER>> reader_;
std::vector<uint8_t> rx_message_;
};
} // namespace esphome::seeed_mr60bha2
@@ -33,7 +33,22 @@ void MR60FDA2Component::dump_config() {
}
// Initialisation functions
void MR60FDA2Component::setup() { this->get_radar_parameters(); }
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); });
}
// 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); }
@@ -53,39 +68,6 @@ 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;
}
// The reader caps the data at DATA_BUF_MAX_SIZE bytes; the 1 byte minimum, type and checksums are checked here
static bool frame_valid(const uint8_t *frame, size_t len) {
if (len <= LEN_TO_DATA_FRAME || !is_known_type(encode_uint16(frame[5], frame[6])))
return false;
if (!validate_checksum(frame, LEN_TO_HEAD_CKSUM - 1, frame[LEN_TO_HEAD_CKSUM - 1])) {
ESP_LOGD(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", frame[LEN_TO_HEAD_CKSUM - 1]);
ESP_LOGV_HEX(TAG, frame, LEN_TO_HEAD_CKSUM, MR60FDA2_MAX_LOG_BYTES, "CURRENT_FRAME: %s");
return false;
}
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() {
this->read_available([this](uint8_t b) {
this->reader_.feed(b, [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
return false;
this->process_frame_(frame);
return true;
});
});
}
#ifdef USE_SELECT
static uint8_t find_nearest_index(float value, const float *arr, int size) {
int nearest_index = 0;
@@ -106,43 +88,152 @@ 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::process_frame_(const uint8_t *frame) {
const uint8_t *data = frame + LEN_TO_HEAD_CKSUM;
switch (encode_uint16(frame[5], frame[6])) {
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_) {
case IS_FALL_TYPE_BUFFER:
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->fall_detected_binary_sensor_, data[0]);
PUBLISH_STATE(this->fall_detected_binary_sensor_, this->current_frame_buf_[LEN_TO_HEAD_CKSUM]);
#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_, data[0]);
PUBLISH_STATE(this->people_exist_binary_sensor_, this->current_frame_buf_[LEN_TO_HEAD_CKSUM]);
#endif
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_INSTALL_HEIGHT:
if (data[0]) {
if (this->current_data_buf_[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 (data[0]) {
if (this->current_data_buf_[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 (data[0]) {
if (this->current_data_buf_[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: {
@@ -151,7 +242,8 @@ void MR60FDA2Component::process_frame_(const uint8_t *frame) {
uint32_t current_sensitivity = 0;
#ifdef USE_SELECT
if (this->install_height_select_ != nullptr) {
uint32_t current_install_height_int = encode_uint32(data[3], data[2], data[1], data[0]);
uint32_t current_install_height_int =
encode_uint32(current_data_buf_[3], current_data_buf_[2], current_data_buf_[1], current_data_buf_[0]);
install_height_float = bit_cast<float>(current_install_height_int);
uint32_t select_index = find_nearest_index(install_height_float, INSTALL_HEIGHT, 7);
@@ -159,7 +251,8 @@ void MR60FDA2Component::process_frame_(const uint8_t *frame) {
}
if (this->height_threshold_select_ != nullptr) {
uint32_t current_height_threshold_int = encode_uint32(data[7], data[6], data[5], data[4]);
uint32_t current_height_threshold_int =
encode_uint32(current_data_buf_[7], current_data_buf_[6], current_data_buf_[5], current_data_buf_[4]);
height_threshold_float = bit_cast<float>(current_height_threshold_int);
size_t select_index = find_nearest_index(height_threshold_float, HEIGHT_THRESHOLD, 7);
@@ -167,7 +260,8 @@ void MR60FDA2Component::process_frame_(const uint8_t *frame) {
}
if (this->sensitivity_select_ != nullptr) {
current_sensitivity = encode_uint32(data[11], data[10], data[9], data[8]);
current_sensitivity =
encode_uint32(current_data_buf_[11], current_data_buf_[10], current_data_buf_[9], current_data_buf_[8]);
uint32_t select_index = find_nearest_index(current_sensitivity, SENSITIVITY, 3);
this->sensitivity_select_->publish_state(select_index);
@@ -176,6 +270,7 @@ void MR60FDA2Component::process_frame_(const uint8_t *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,19 +15,18 @@
#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 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 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 FRAME_HEADER_BUFFER = 0x01;
static const uint8_t FRAME_HEADER_BUFFER = 0x01;
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;
@@ -35,6 +34,20 @@ 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
@@ -52,11 +65,16 @@ class MR60FDA2Component final : public Component,
#endif
protected:
// 01, id (2), data length (2, high byte first), type (2), header checksum, data, data checksum
LengthFrameReader<FRAME_BUF_MAX_SIZE, FrameFormat<FrameLengthU16BE<3, LEN_TO_DATA_FRAME>, FRAME_HEADER_BUFFER>>
reader_;
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_;
void process_frame_(const uint8_t *frame);
void split_frame_(uint8_t buffer);
void process_frame_();
public:
float get_setup_priority() const override { return esphome::setup_priority::LATE; }
@@ -15,6 +15,7 @@
#include <algorithm>
#include <cstring>
#include <memory>
#include <numeric>
namespace {
@@ -24,6 +25,10 @@ constexpr uint8_t SHELLY_DIMMER_ACK_TIMEOUT = 200; // 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;
@@ -53,6 +58,11 @@ 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;
@@ -293,34 +303,83 @@ 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, sum16_bytes(data + 1, 3 + len));
p = put_be16(p, shelly_dimmer_checksum(data + 1, 3 + len));
*p++ = SHELLY_DIMMER_PROTO_END_BYTE;
return p - data;
}
bool ShellyDimmer::read_frame_() {
bool received = false;
while (!received && this->available()) {
const uint8_t c = this->read();
ESP_LOGV(TAG, "Read byte: 0x%02x", c);
this->reader_.feed(c, [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;
}
this->handle_frame_(frame);
received = true;
return true;
});
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;
}
return received;
// 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;
}
return 1;
}
if (pos == 4 + payload_len + 2) {
// Must be end byte.
return c == SHELLY_DIMMER_PROTO_END_BYTE ? 0 : -1;
}
return -1;
}
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];
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];
ESP_LOGD(TAG, "Got frame: 0x%02x", cmd);
@@ -330,7 +389,7 @@ bool ShellyDimmer::handle_frame_(const uint8_t *frame) {
return false;
}
const uint8_t *payload = frame + 4;
const uint8_t *payload = &this->buffer_[4];
// Handle response.
switch (cmd) {
@@ -8,7 +8,7 @@
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
#include <array>
namespace esphome::shelly_dimmer {
@@ -19,11 +19,6 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
private:
static constexpr uint16_t SHELLY_DIMMER_BUFFER_SIZE = 256;
static constexpr uint8_t SHELLY_DIMMER_PROTO_START_BYTE = 0x01;
static constexpr uint8_t SHELLY_DIMMER_PROTO_END_BYTE = 0x04;
// Start byte, seq, cmd, payload length, payload, two checksum bytes, end byte
static constexpr size_t SHELLY_DIMMER_PROTO_LEN_POS = 3;
static constexpr size_t SHELLY_DIMMER_PROTO_OVERHEAD = 7;
public:
float get_setup_priority() const override { return setup_priority::LATE; }
@@ -59,10 +54,8 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
// Frame parser state.
uint8_t seq_{0};
LengthFrameReader<SHELLY_DIMMER_BUFFER_SIZE,
FrameFormat<FrameLengthU8<SHELLY_DIMMER_PROTO_LEN_POS, SHELLY_DIMMER_PROTO_OVERHEAD>,
SHELLY_DIMMER_PROTO_START_BYTE>>
reader_;
std::array<uint8_t, SHELLY_DIMMER_BUFFER_SIZE> buffer_;
uint8_t buffer_pos_{0};
// Firmware version.
uint8_t version_major_;
@@ -99,11 +92,16 @@ 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_();
/// Handles a complete frame.
bool handle_frame_(const uint8_t *frame);
bool handle_frame_();
/// Reset STM32 with the BOOT0 pin set to the given value.
void reset_(bool boot0);
+57 -25
View File
@@ -1,6 +1,5 @@
#include "tuya.h"
#include <cstring>
#include "esphome/core/application.h"
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
@@ -56,10 +55,7 @@ void Tuya::setup() {
}
void Tuya::loop() {
this->read_available([this](uint8_t b) {
this->last_rx_char_timestamp_ = App.get_loop_component_start_time();
this->reader_.feed(b, this->frame_handler_());
});
this->read_available([this](uint8_t b) { this->handle_char_(b); });
process_command_queue_();
}
@@ -118,33 +114,70 @@ void Tuya::dump_mcu_config_() {
#endif
}
void TuyaFrameLength::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 Tuya::validate_message_() {
uint32_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
// Byte 0: HEADER1 (always 0x55)
if (at == 0)
return new_byte == 0x55;
// Byte 1: HEADER2 (always 0xAA)
if (at == 1)
return new_byte == 0xAA;
// Byte 2: VERSION
// no validation for the following fields:
uint8_t version = data[2];
if (at == 2)
return true;
// Byte 3: COMMAND
uint8_t command = data[3];
if (at == 3)
return true;
// Byte 4: LENGTH1
// Byte 5: LENGTH2
if (at <= 5) {
// no validation for these fields
return true;
}
uint16_t length = encode_uint16(data[4], data[5]);
// wait until all data is read
if (at - 6 < length)
return true;
// Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
uint8_t rx_checksum = new_byte;
const uint8_t calc_checksum = sum_bytes(data, 6 + length);
bool Tuya::handle_frame_(const uint8_t *frame, size_t len) {
// Last byte: sum of all bytes before it, header included, modulo 256
const uint8_t rx_checksum = frame[len - 1];
const uint8_t calc_checksum = sum_bytes(frame, len - 1);
if (rx_checksum != calc_checksum) {
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
return false;
}
const uint8_t version = frame[2];
const uint8_t command = frame[3];
const uint8_t *message_data = frame + 6;
const size_t length = len - 7;
// valid message
const uint8_t *message_data = data + 6;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
#endif
// Like a partial frame, a frame being handled holds queued commands back
this->handling_frame_ = true;
this->handle_command_(command, version, message_data, length);
this->handling_frame_ = false;
return true;
// return false to reset rx buffer
return false;
}
void Tuya::handle_char_(uint8_t c) {
this->rx_message_.push_back(c);
if (!this->validate_message_()) {
this->rx_message_.clear();
} else {
this->last_rx_char_timestamp_ = millis();
}
}
void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
@@ -505,9 +538,8 @@ void Tuya::process_command_queue_() {
uint32_t now = millis();
uint32_t delay = now - this->last_command_timestamp_;
// A partial frame left too long without a byte may hide a whole frame behind a broken start
if (this->reader_.length() > 0 && now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
this->reader_.flush(this->frame_handler_());
if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
this->rx_message_.clear();
}
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
@@ -525,7 +557,7 @@ void Tuya::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->reader_.length() == 0 && !this->handling_frame_ &&
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
!this->expected_response_.has_value()) {
this->send_raw_command_(command_queue_.front());
if (!this->expected_response_.has_value())
+3 -25
View File
@@ -6,7 +6,6 @@
#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"
@@ -17,21 +16,6 @@
namespace esphome::tuya {
// Some MCUs answer a datapoint query with every datapoint in one frame, and schedule datapoints can be long
static constexpr size_t MAX_FRAME_SIZE = 512;
/// 55 AA, version, command, 2 byte length, data, sum8; warns when a frame is skipped for being longer than the buffer
struct TuyaFrameLength {
static constexpr size_t KNOWN_AT = 6;
static size_t get(const uint8_t *buf) {
const size_t len = encode_uint16(buf[4], buf[5]) + 7;
if (len > MAX_FRAME_SIZE)
warn_too_long(len);
return len;
}
static void warn_too_long(size_t len);
};
enum class TuyaDatapointType : uint8_t {
RAW = 0x00, // variable length
BOOLEAN = 0x01, // 1 byte (0/1)
@@ -147,14 +131,10 @@ class Tuya final : public Component, public uart::UARTDevice {
protected:
void register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func);
void dump_mcu_config_();
/// Returns false for a frame that fails the checksum
bool handle_frame_(const uint8_t *frame, size_t len);
// One handler type for feed() and flush(), so the reader's frame loop is compiled once
auto frame_handler_() {
return [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
}
void handle_char_(uint8_t c);
void handle_datapoints_(const uint8_t *buffer, size_t len);
optional<TuyaDatapoint> get_datapoint_(uint8_t datapoint_id);
bool validate_message_();
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
void send_raw_command_(TuyaCommand command);
@@ -194,15 +174,13 @@ class Tuya final : public Component, public uart::UARTDevice {
std::unique_ptr<char[]> product_;
std::vector<TuyaDatapointListener> listeners_;
std::vector<TuyaDatapoint> datapoints_;
std::vector<uint8_t> rx_message_;
std::vector<uint8_t> ignore_mcu_update_on_datapoints_{};
std::vector<TuyaCommand> command_queue_;
optional<TuyaCommandType> expected_response_{};
uint8_t wifi_status_ = -1;
bool product_invalid_{false};
// Holds commands back while a received frame is handled
bool handling_frame_{false};
CallbackManager<void()> initialized_callback_{};
LengthFrameReader<MAX_FRAME_SIZE, FrameFormat<TuyaFrameLength, 0x55, 0xAA>> reader_;
};
} // namespace esphome::tuya
+13 -227
View File
@@ -1,33 +1,11 @@
#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;
}
template<class FIRST, class... REST> struct First {
using type = FIRST;
};
} // 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 {
@@ -40,12 +18,11 @@ 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 != frame_reader_detail::header_byte<HEADER...>(pos)) {
if (pos < HEADER_LEN && c != header_byte(pos)) {
// A later byte of the broken header, or c, may start the real one
if (pos == 0)
return nullptr;
this->buf_[pos] = c;
return this->replay_(pos);
this->replay_(pos);
return nullptr;
}
this->buf_[pos++] = c;
if (pos < N) {
@@ -67,215 +44,24 @@ template<size_t N, uint8_t... HEADER> class FrameReader {
void resync() { this->replay_(N - 1); }
protected:
// 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) {
// 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) {
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 for FrameFormat: the frame length is known once KNOWN_AT bytes are collected, and get() returns it
/// for the whole frame, header included. A component can pass its own type with these two members.
/// One length byte at POS; ADD is added to give the whole frame length.
template<size_t POS, size_t ADD = 0> struct FrameLengthU8 {
static constexpr size_t KNOWN_AT = POS + 1;
static constexpr size_t get(const uint8_t *buf) { return buf[POS] + ADD; }
};
/// Two length bytes at POS, high byte first.
template<size_t POS, size_t ADD = 0> struct FrameLengthU16BE {
static constexpr size_t KNOWN_AT = POS + 2;
static constexpr size_t get(const uint8_t *buf) { return ((size_t(buf[POS]) << 8) | buf[POS + 1]) + ADD; }
};
/// Two length bytes at POS, low byte first.
template<size_t POS, size_t ADD = 0> struct FrameLengthU16LE {
static constexpr size_t KNOWN_AT = POS + 2;
static constexpr size_t get(const uint8_t *buf) { return (buf[POS] | (size_t(buf[POS + 1]) << 8)) + ADD; }
};
/// A frame type that always has LEN bytes.
template<size_t LEN> struct FrameFixedLength {
static constexpr size_t KNOWN_AT = 1;
static constexpr size_t get(const uint8_t * /*buf*/) { return LEN; }
};
/// One frame type for LengthFrameReader: frames that start with the header bytes HEADER... and whose length follows
/// LENGTH, one of the FrameLength types above.
template<class LENGTH, uint8_t... HEADER> struct FrameFormat {
using Length = LENGTH;
static constexpr size_t HEADER_LEN = sizeof...(HEADER);
static constexpr uint8_t FIRST = frame_reader_detail::header_byte<HEADER...>(0);
// Bytes collected when the length is checked; also the shortest frame
static constexpr size_t MIN_LEN = std::max<size_t>({LENGTH::KNOWN_AT, HEADER_LEN, 2});
static_assert(HEADER_LEN >= 1 && HEADER_LEN <= 8, "FrameFormat takes 1 to 8 header bytes");
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 frame_reader_detail::header_byte<HEADER...>(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, footers and a minimum length that covers them 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); });
template<size_t N, class... FORMATS> class LengthFrameReader {
using pos_t = std::conditional_t<(N <= 0xFF), uint8_t, uint16_t>;
static_assert(sizeof...(FORMATS) >= 1, "LengthFrameReader takes at least one FrameFormat");
static_assert(N >= 2 && N <= 0xFFFF, "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");
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.
template<class F> inline void __attribute__((always_inline)) feed(uint8_t c, F &&handle) {
if (const uint8_t *frame = this->feed(c))
this->drain_(frame, handle);
}
/// For a partial frame left too long without a byte, which a corrupt length can cause: give up on it, and pass the
/// frames it held back to handle.
template<class F> void flush(F &&handle) {
while (this->pos_ != 0)
this->drain_(this->resync(), handle);
}
/// Lower level: feed one byte; returns the completed frame, valid until the next call, or nullptr. After it, call
/// next() when the frame is handled or resync() when it is rejected, until they return nullptr.
inline const uint8_t *__attribute__((always_inline)) feed(uint8_t c) {
// 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;
return nullptr;
}
return this->feed_edge_(c);
}
/// Length of the frame feed(), resync() or next() returned; valid until the next call on the reader.
size_t frame_length() const {
if constexpr (sizeof...(FORMATS) == 1) {
return frame_reader_detail::First<FORMATS...>::type::Length::get(this->buf_);
} else {
const uint8_t first = this->buf_[0];
size_t len = 0;
(void) ((first == FORMATS::FIRST && ((len = FORMATS::Length::get(this->buf_)), true)) || ...);
return len;
}
}
/// Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
size_t length() const { return this->pos_; }
/// Forget the partial frame and any held bytes, and look for a header from the next byte.
void reset() {
this->pos_ = 0;
this->end_ = 0;
this->held_end_ = 0;
}
/// Lower level: for a rejected frame, or a partial one: drop its first byte and look for a frame in the rest.
/// Returns the next frame found, or nullptr. Does nothing when no frame is held and nothing is collected.
const uint8_t *resync() { return this->replay_(1, this->pos_ != 0 ? this->pos_ : this->held_end_); }
/// Lower level: after handling a frame, look for the next one in the bytes that followed it in a resync().
/// Returns that frame, or nullptr once they are used up.
const uint8_t *next() { return this->replay_(this->frame_length(), this->held_end_); }
protected:
template<class F> void ESPHOME_FRAME_READER_COLD drain_(const uint8_t *frame, F &handle) {
while (frame != nullptr)
frame = handle(frame, this->frame_length()) ? this->next() : this->resync();
}
// A header byte, the bytes up to the length, the last byte of a frame, or a byte between frames
const uint8_t *ESPHOME_FRAME_READER_COLD feed_edge_(uint8_t c) {
const pos_t pos = this->pos_;
if (pos == 0) {
this->held_end_ = 0;
const bool header = ((c == FORMATS::FIRST) || ...);
if (header) {
this->buf_[0] = c;
this->pos_ = 1;
}
return nullptr;
}
if constexpr (sizeof...(FORMATS) == 1) {
return this->feed_as_<FORMATS...>(pos, c);
} else {
const uint8_t first = this->buf_[0];
const uint8_t *frame = nullptr;
(void) ((first == FORMATS::FIRST && ((frame = this->feed_as_<FORMATS>(pos, c)), true)) || ...);
return frame;
}
}
template<class F> const uint8_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::MIN_LEN || 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 this->buf_;
}
this->pos_ = pos;
return nullptr;
}
// 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 next() and resync(), and returns it.
const uint8_t *ESPHOME_FRAME_READER_COLD replay_(size_t from, size_t to) {
this->pos_ = 0;
this->end_ = 0;
this->held_end_ = 0;
for (size_t i = from; i < to; i++) {
if (this->feed_edge_(this->buf_[i]) == nullptr)
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 this->buf_;
}
return nullptr;
}
uint8_t buf_[N];
pos_t pos_{0};
// Length of the frame being collected once its length is known; 0 otherwise
pos_t end_{0};
// While a frame is held: end of the frame plus the bytes after it that are not fed yet; 0 otherwise
pos_t held_end_{0};
};
} // namespace esphome
#undef ESPHOME_FRAME_READER_COLD
@@ -20,12 +20,6 @@ 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) {
@@ -99,28 +93,4 @@ static void FrameReader_UltrasonicNoisy(benchmark::State &state) {
}
BENCHMARK(FrameReader_UltrasonicNoisy);
// --- LengthFrameReader: frames of different lengths among noise ---
static void LengthFrameReader_MixedFrames(benchmark::State &state) {
LengthFrameReader<255, FrameFormat<FrameLengthU8<7>, 0xA5, 0x01>> reader;
const uint8_t *bytes = LENGTH_FRAMES;
uint32_t frames = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(LENGTH_FRAMES); j++) {
const uint8_t *frame = reader.feed(bytes[j]);
if (frame == nullptr)
continue;
benchmark::DoNotOptimize(frame);
frames++;
}
}
benchmark::DoNotOptimize(frames);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LengthFrameReader_MixedFrames);
} // namespace esphome::benchmarks
-207
View File
@@ -140,211 +140,4 @@ TEST(FrameReaderTest, SixteenBitIndex) {
EXPECT_EQ(frames[0][299], 0x42);
}
// Feeds bytes and collects every completed frame of a LengthFrameReader, taking each one with next().
template<size_t N, class... F> static Frames feed_all(LengthFrameReader<N, F...> &reader, const Bytes &input) {
Frames frames;
for (uint8_t c : input) {
for (const uint8_t *frame = reader.feed(c); frame != nullptr; frame = reader.next())
frames.emplace_back(frame, frame + reader.frame_length());
}
return frames;
}
// Feeds bytes and returns the last frame feed() completed, or nullptr.
template<size_t N, class... F> static const uint8_t *feed_last(LengthFrameReader<N, F...> &reader, const Bytes &input) {
const uint8_t *last = nullptr;
for (uint8_t c : input) {
if (const uint8_t *frame = reader.feed(c))
last = frame;
}
return last;
}
template<size_t N, class... F> static Bytes held(const LengthFrameReader<N, F...> &reader, const uint8_t *frame) {
return Bytes(frame, frame + reader.frame_length());
}
// pioneer_wt: A5 01, one byte at 7 holds the whole length
using OneByte = FrameFormat<FrameLengthU8<7>, 0xA5, 0x01>;
// tuya: 55 AA, payload length big-endian at 4, header, length and checksum add 7
using TwoByteBE = FrameFormat<FrameLengthU16BE<4, 7>, 0x55, 0xAA>;
// ld24xx command and data frames: payload length little-endian at 4, header, length and footer add 10
using LdCmd = FrameFormat<FrameLengthU16LE<4, 10>, 0xFD, 0xFC, 0xFB, 0xFA>;
using LdData = FrameFormat<FrameLengthU16LE<4, 10>, 0xF4, 0xF3, 0xF2, 0xF1>;
// ld2410s short frame: 6E, always 5 bytes
using LdShort = FrameFormat<FrameFixedLength<5>, 0x6E>;
// Small formats for the recovery tests: A5, one byte at 1 holds the whole length
using Small = FrameFormat<FrameLengthU8<1>, 0xA5>;
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
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, 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, 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<FrameLengthU8<1>, 0x09>> 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;
feed_all(reader, {0xA5, 0x05});
EXPECT_EQ(reader.length(), 2u);
reader.reset();
EXPECT_EQ(reader.length(), 0u);
EXPECT_EQ(feed_all(reader, {0x01, 0xA5, 0x03, 0x07}), (Frames{{0xA5, 0x03, 0x07}}));
}
TEST(LengthFrameReaderTest, ResyncFindsHeaderInRejectedFrame) {
LengthFrameReader<8, Small> reader;
// The A5 taken as a header was payload; the real frame starts at the second A5
const uint8_t *frame = feed_last(reader, {0xA5, 0x05, 0x00, 0xA5, 0x04});
ASSERT_NE(frame, nullptr);
EXPECT_EQ(reader.frame_length(), 5u);
EXPECT_EQ(reader.resync(), nullptr);
EXPECT_EQ(reader.length(), 2u);
EXPECT_EQ(feed_all(reader, {0x10, 0x20}), (Frames{{0xA5, 0x04, 0x10, 0x20}}));
}
TEST(LengthFrameReaderTest, ResyncReturnsEveryFrameInsideRejectedOne) {
LengthFrameReader<16, Small> reader;
// A bad checksum rejects the 9 byte frame; two complete frames sit inside it, and a partial one after them
const uint8_t *frame = feed_last(reader, {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04});
ASSERT_NE(frame, nullptr);
frame = reader.resync();
ASSERT_NE(frame, nullptr);
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x03, 0x01}));
frame = reader.next();
ASSERT_NE(frame, nullptr);
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x02}));
EXPECT_EQ(reader.next(), nullptr);
EXPECT_EQ(reader.length(), 2u);
EXPECT_EQ(feed_all(reader, {0x01, 0x02}), (Frames{{0xA5, 0x04, 0x01, 0x02}}));
}
TEST(LengthFrameReaderTest, ResyncAgainAfterRecoveredFrameIsRejected) {
LengthFrameReader<16, Small> reader;
// The 9 byte frame holds a 4 byte candidate, which holds a 3 byte one, followed by two more bytes
const uint8_t *frame = feed_last(reader, {0xA5, 0x09, 0xA5, 0x04, 0xA5, 0x03, 0x01, 0x02, 0x03});
ASSERT_NE(frame, nullptr);
frame = reader.resync();
ASSERT_NE(frame, nullptr);
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x04, 0xA5, 0x03}));
// Rejected too: the 3 byte frame inside it comes back, and the bytes after the 4 byte one are kept
frame = reader.resync();
ASSERT_NE(frame, nullptr);
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x03, 0x01}));
EXPECT_EQ(reader.next(), nullptr);
EXPECT_EQ(reader.length(), 0u);
}
TEST(LengthFrameReaderTest, ResyncPartialFrameAfterSilence) {
LengthFrameReader<16, Small> reader;
// A corrupt length of 15 holds back two complete frames until the caller gives up on the partial one
EXPECT_EQ(feed_all(reader, {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x03, 0x09}), Frames{});
EXPECT_EQ(reader.length(), 9u);
Frames found;
for (const uint8_t *frame = reader.resync(); frame != nullptr; frame = reader.next())
found.push_back(held(reader, frame));
EXPECT_EQ(found, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x03, 0x09}}));
EXPECT_EQ(reader.length(), 0u);
}
TEST(LengthFrameReaderTest, ResyncWhileIdleIsHarmless) {
LengthFrameReader<8, Small> reader;
EXPECT_EQ(reader.resync(), nullptr);
// A handled frame, then noise: nothing is held any more
EXPECT_EQ(feed_all(reader, {0xA5, 0x03, 0x01, 0x00}), (Frames{{0xA5, 0x03, 0x01}}));
EXPECT_EQ(reader.resync(), nullptr);
// A rejected length leaves nothing collected
EXPECT_EQ(feed_all(reader, {0xA5, 0x09}), Frames{});
EXPECT_EQ(reader.resync(), nullptr);
EXPECT_EQ(feed_all(reader, {0xA5, 0x03, 0x01}), (Frames{{0xA5, 0x03, 0x01}}));
}
TEST(LengthFrameReaderTest, HandlerRejectionRecoversFramesInside) {
LengthFrameReader<16, Small> reader;
Frames seen;
// The handler rejects the 9 byte frame; the two frames inside it reach the handler too
auto handle = [&seen](const uint8_t *frame, size_t len) {
seen.emplace_back(frame, frame + len);
return len != 9;
};
for (uint8_t c : {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04})
reader.feed(c, handle);
EXPECT_EQ(seen, (Frames{{0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04}, {0xA5, 0x03, 0x01}, {0xA5, 0x02}}));
EXPECT_EQ(reader.length(), 2u);
}
TEST(LengthFrameReaderTest, FlushHandsOverFramesHeldBack) {
LengthFrameReader<16, Small> reader;
Frames seen;
auto handle = [&seen](const uint8_t *frame, size_t len) {
seen.emplace_back(frame, frame + len);
return true;
};
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x03, 0x09})
reader.feed(c, handle);
EXPECT_EQ(seen, Frames{});
reader.flush(handle);
EXPECT_EQ(seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x03, 0x09}}));
EXPECT_EQ(reader.length(), 0u);
reader.flush(handle); // nothing collected: nothing to do
EXPECT_EQ(seen.size(), 2u);
}
} // namespace esphome::core::testing
@@ -176,23 +176,4 @@ TEST_F(LD2410SStartTest, GapAcrossWrapFullRange) {
this->check_starts_on_first_pass_(START_GAP_ACROSS_WRAP, 0xFFFFFFFF);
}
// A short data frame inside a bad command frame inside a bad data frame is still read, so the link holds
TEST_F(LD2410SWriteTest, FrameInsideTwoNestedBadFramesKeepsTheLink) {
uint32_t now = START_FAR_FROM_WRAP;
for (int pass = 0; pass < 20; pass++, now += STEP_MS) {
this->loop_at_(now);
if (!this->uart_.commands.empty() && this->uart_.commands.back() == 0x00FE && this->uart_.available() == 0)
break;
}
ASSERT_EQ(this->uart_.commands, INIT_COMMANDS);
ASSERT_FALSE(this->radar_.status_has_warning());
std::vector<uint8_t> bytes = {0xF4, 0xF3, 0xF2, 0xF1, 0x20, 0x00, 0xFD, 0xFC, 0xFB, 0xFA, 0x07, 0x00};
bytes.insert(bytes.end(), {0x6E, 0x02, 0x64, 0x00, 0x62});
bytes.resize(42, 0x00);
this->uart_.queue(bytes);
this->loop_at_(now + 3000);
this->loop_at_(now + 6000);
EXPECT_FALSE(this->radar_.status_has_warning());
}
} // namespace esphome::ld2410s::testing
+2 -1
View File
@@ -31,7 +31,9 @@ class MockUARTComponent : public uart::UARTComponent {
// 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_;
@@ -40,7 +42,6 @@ class TestableLD2450 : public LD2450Component {
using LD2450Component::link_state_;
using LD2450Component::mac_address_;
using LD2450Component::open_link_grace_;
using LD2450Component::reader_;
using LD2450Component::readline_;
using LD2450Component::timeout_;
using LD2450Component::version_;
+1 -1
View File
@@ -35,7 +35,7 @@ TEST_F(LD2450MacAckTest, BluetoothOffAckClearsStoredMac) {
ASSERT_EQ(this->mac_str_(), "81:2C:62:BE:C9:96");
this->ld2450_.feed(make_mac_ack(ld24xx::NO_MAC));
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_FALSE(this->ld2450_.bluetooth_on_);
EXPECT_THAT(this->ld2450_.mac_address_, ::testing::Each(0));
}
+26 -26
View File
@@ -7,7 +7,7 @@ class LD2450ReadlineTest : public ::testing::Test {
void SetUp() override {
this->ld2450_.set_uart_parent(&this->mock_uart_);
// Ensure clean state
ASSERT_EQ(this->ld2450_.reader_.length(), 0u);
ASSERT_EQ(this->ld2450_.buffer_pos_, 0);
}
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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, ValidCommandAckFrame) {
auto frame = make_ack_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, BackToBackPeriodicFrames) {
auto frame = make_periodic_frame();
for (int i = 0; i < 5; i++) {
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u) << "Frame " << i << " not processed";
EXPECT_EQ(this->ld2450_.buffer_pos_, 0) << "Frame " << i << " not processed";
}
}
@@ -41,11 +41,11 @@ TEST_F(LD2450ReadlineTest, BackToBackMixedFrames) {
auto periodic = make_periodic_frame();
auto ack = make_ack_frame();
this->ld2450_.feed(periodic);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
this->ld2450_.feed(ack);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
this->ld2450_.feed(periodic);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
// --- Garbage then valid frame tests ---
@@ -54,12 +54,12 @@ 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_.reader_.length(), 0u);
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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
// --- Footer-based resynchronization tests ---
@@ -69,22 +69,22 @@ TEST_F(LD2450ReadlineTest, FooterInGarbageResyncs) {
// 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_.reader_.length(), 0u); // Footer reset the buffer
EXPECT_EQ(this->ld2450_.buffer_pos_, 0); // Footer reset the buffer
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
// --- Overflow recovery tests ---
@@ -94,8 +94,8 @@ TEST_F(LD2450ReadlineTest, OverflowResetsBuffer) {
// 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);
// Bytes that never start a header are not buffered
EXPECT_LT(this->ld2450_.reader_.length(), 4u);
// After overflow, buffer_pos_ resets to 0 (via the < 4 early return path)
EXPECT_LT(this->ld2450_.buffer_pos_, 4);
}
TEST_F(LD2450ReadlineTest, OverflowThenValidFrame) {
@@ -105,7 +105,7 @@ TEST_F(LD2450ReadlineTest, OverflowThenValidFrame) {
auto frame = make_periodic_frame();
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, BufferLargeEnoughForDesyncedFooter) {
@@ -120,7 +120,7 @@ TEST_F(LD2450ReadlineTest, BufferLargeEnoughForDesyncedFooter) {
this->ld2450_.feed(mid_frame);
// The footer from the frame should have triggered a reset
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, SimulatedRestartThenFrames) {
@@ -134,11 +134,11 @@ TEST_F(LD2450ReadlineTest, SimulatedRestartThenFrames) {
restart_noise.insert(restart_noise.end(), frame.begin(), frame.end());
this->ld2450_.feed(restart_noise);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
// Subsequent frames should work normally
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
// --- Frame payloads that look like footers ---
@@ -154,13 +154,13 @@ TEST_F(LD2450ReadlineTest, CmdFooterBytesInPeriodicPayloadDoNotEndTheFrame) {
frame[7] = 0x01;
this->ld2450_.feed(frame);
EXPECT_EQ(frames, 1);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
// 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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, BogusLengthFieldResyncsOnTheNextHeader) {
@@ -172,7 +172,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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, LargestLengthFieldDoesNotWrapToIncomplete) {
@@ -185,7 +185,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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
TEST_F(LD2450ReadlineTest, MixedHeaderPrefixNeverOpensAFrame) {
@@ -195,16 +195,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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
// The reverse mix is rejected the same way
this->ld2450_.feed({0xAA, 0xFC, 0xFB, 0xFA});
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
// A real frame right after is still parsed
this->ld2450_.feed(make_periodic_frame());
EXPECT_EQ(frames, 1);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
}
} // namespace esphome::ld2450::testing
+3 -3
View File
@@ -39,13 +39,13 @@ class LD2450ShortAckTest : public ::testing::Test {
TEST_F(LD2450ShortAckTest, ShortVersionAckDoesNotChangeTheVersion) {
this->ld2450_.feed(make_short_version_ack());
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
for (uint8_t byte : this->ld2450_.version_) {
EXPECT_EQ(byte, 0);
}
this->ld2450_.feed(make_version_ack());
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
EXPECT_TRUE(multi_target.state);
this->ld2450_.feed(make_target_mode_ack(0x01));
+17 -14
View File
@@ -63,12 +63,13 @@ 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_.reader_.length(), split) << "zone " << static_cast<int>(zone);
EXPECT_EQ(this->ld2450_.buffer_pos_, split) << "zone " << static_cast<int>(zone);
this->ld2450_.feed(std::vector<uint8_t>(frame.begin() + split, frame.end()));
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
for (uint8_t i = 0; i < MAX_ZONES; i++) {
if (i == zone) {
expect_zone(this->ld2450_, i, 772, 258, 1500, 3000);
@@ -82,7 +83,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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
this->expect_all_zones_(0, 0, 0, 0);
}
@@ -92,7 +93,7 @@ TEST_F(LD2450ZoneAckTest, FailedZoneQueryAckDoesNotWaitForCoordinates) {
frame[6] = 0xC1;
frame[8] = 0x01;
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
this->expect_all_zones_(100, 200, 300, 400);
}
@@ -107,7 +108,7 @@ TEST_F(LD2450ZoneAckTest, ValidZoneAckWithEmbeddedFooterAndHeaderIsNotResynced)
ASSERT_TRUE(std::equal(frame.begin(), frame.begin() + 36, stream.begin()));
this->ld2450_.feed(frame);
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
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);
@@ -116,7 +117,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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
expect_zone(this->ld2450_, 0, 100, 200, 1500, 3000);
}
@@ -130,7 +131,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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
expect_zone(this->ld2450_, 0, 100, 200, 300, 400);
}
@@ -138,7 +139,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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
expect_zone(this->ld2450_, 0, 100, 200, 1500, 3000);
}
@@ -149,9 +150,10 @@ 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_.reader_.length(), 10u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 10);
EXPECT_EQ(this->ld2450_.buffer_data_[6], 0xC1);
this->ld2450_.feed(std::vector<uint8_t>(complete.begin() + 10, complete.end()));
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
expect_zone(this->ld2450_, 0, 100, 200, 1500, 3000);
}
@@ -164,20 +166,21 @@ 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_.reader_.length(), 39u); // the C1 header still claims the buffer
EXPECT_EQ(this->ld2450_.buffer_pos_, 39); // 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_.reader_.length(), 1u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 1);
EXPECT_EQ(this->ld2450_.buffer_data_[0], 0xFD);
this->ld2450_.feed(std::vector<uint8_t>(complete.begin() + 1, complete.end()));
EXPECT_EQ(this->ld2450_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
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_.reader_.length(), 0u);
EXPECT_EQ(this->ld2450_.buffer_pos_, 0);
expect_zone(this->ld2450_, 0, -13227, 200, 1500, 3000);
}
@@ -55,7 +55,7 @@ TEST_F(LD2460ReadlineTest, FooterBytesInsideGarbage) {
}
TEST_F(LD2460ReadlineTest, OverflowThenValidFrame) {
this->ld2460_.feed(std::vector<uint8_t>(MAX_FRAME_LENGTH + 8, 0x11));
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
this->ld2460_.feed(make_periodic_frame());
EXPECT_FLOAT_EQ(this->count_.state, 1);
@@ -154,22 +154,6 @@ 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};
@@ -0,0 +1,152 @@
#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,12 +40,8 @@ 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) {
reader.feed(b, [&last](const uint8_t *frame, size_t len) {
if (!packet_valid(frame, len))
return false;
if (size_t len = reader.feed(b))
last = len;
return true;
});
}
return last;
}
@@ -86,8 +82,9 @@ TEST(PioneerWTProtocol, ReaderDropsBadChecksum) {
PacketReader reader;
Frame frame = from_hex(PRESENCE_CHECK);
frame[9] ^= 0x01;
EXPECT_FALSE(packet_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);
}
@@ -342,9 +339,9 @@ TEST_F(PioneerWTTest, WarningStaysUntilAcknowledgement) {
EXPECT_FALSE(this->sut_.status_has_warning());
}
TEST_F(PioneerWTTest, ReleasesPartialFrameAfterPause) {
TEST_F(PioneerWTTest, DropsPartialFrameAfterPause) {
this->start_();
// A cut-off header that claims 255 bytes is given up after the pause, so it does not swallow the frames that follow.
// A cut-off header that claims 255 bytes would otherwise swallow the frames that follow.
this->uart_.push_rx_hex("a5010121000000ff");
this->loop_at_(1100);
this->loop_at_(1300); // idle pass after the gap
@@ -353,19 +350,6 @@ TEST_F(PioneerWTTest, ReleasesPartialFrameAfterPause) {
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_(1300); // idle pass after the gap
EXPECT_EQ(this->uart_.tx, from_hex(PRESENCE_REPLY));
}
TEST_F(PioneerWTTest, KeepsPartialFrameAfterSlowLoop) {
this->start_();
const std::string check = PRESENCE_CHECK;
@@ -72,7 +72,7 @@ uart_mock:
# 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 footer' warning; the rest cannot start a header and are dropped too.
# with an 'Invalid length' warning; the rest cannot start a header and are dropped too.
- delay: 200ms
inject_rx:
[
@@ -29,7 +29,7 @@ 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: the length is skipped and the short frame still parses -> presence off
# then a short frame, state 0 -> frame dropped, 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
@@ -73,7 +73,7 @@ uart_mock:
# 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 footer' warning; the rest cannot start a header and are dropped too.
# with an 'Invalid length' warning; the rest cannot start a header and are dropped too.
- delay: 200ms
inject_rx:
[
@@ -94,7 +94,7 @@ uart_mock:
# Phase 4 (t=600ms): 75 bytes of 0xFF
# The first 22 complete the truncated frame's 30 bytes without its footer, so it is
# dropped with an 'Invalid footer' warning; the rest cannot start a header and
# dropped with an 'Invalid header/footer' warning; the rest cannot start a header and
# are dropped too, leaving the buffer empty for the recovery frame.
- delay: 200ms
inject_rx:
@@ -50,9 +50,10 @@ uart_mock:
- delay: 100ms
inject_rx: [0xF4, 0xF3, 0xF2, 0xF1, 0x04, 0x13, 0x00, 0x01, 0x02]
# 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.
# 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
inject_rx:
[
+2 -2
View File
@@ -121,8 +121,8 @@ async def test_uart_mock_ld2410(
)
# Verify the truncated frame was dropped with a warning
assert any("Invalid footer" in line for line in waiter.lines), (
"Expected 'Invalid footer' warning in logs"
assert any("Invalid length" in line for line in waiter.lines), (
"Expected 'Invalid length' warning in logs"
)
# Verify LD2410 sent setup commands (TX logging)
+9 -1
View File
@@ -121,7 +121,7 @@ EXPECTED_DROPPED_STATES = ["7", "7"]
# bytes, which publishes the swallowed frame and resumes the next one.
EXPECTED_RECOVERY_PRESENCE = [
True, # baseline short frame
False, # short frame right after the oversized length field, still parsed
False, # short frame after the dropped oversized length field
True, # rescued: short frame swallowed by the truncated standard frame
False, # short frame whose header byte completed the truncated frame
True, # short frame
@@ -302,6 +302,7 @@ 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
@@ -320,6 +321,12 @@ 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()
@@ -368,6 +375,7 @@ async def test_uart_mock_ld2410s_recovery(
assert collector.binary_states["has_target"] == EXPECTED_RECOVERY_PRESENCE
assert ignored_changes == 2
assert setting_states == []
assert oversized_dropped.done(), "Oversized length field was not dropped"
assert footer_mismatches == [TRUNCATED_FRAME_HEX, BAD_COMMAND_FRAME_HEX]
frames = [frame for _, frame in tx_frames]
+3 -3
View File
@@ -228,8 +228,8 @@ async def test_uart_mock_ld2412(
)
# Verify the truncated frame was dropped with a warning
assert any("Invalid footer" in line for line in waiter.lines), (
"Expected 'Invalid footer' warning in logs"
assert any("Invalid length" in line for line in waiter.lines), (
"Expected 'Invalid length' 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 footer", timeout=5.0),
waiter.wait_for("Invalid length", timeout=5.0),
gate_0_read,
gate_5_read,
)
+2 -2
View File
@@ -142,8 +142,8 @@ async def test_uart_mock_ld2450(
)
# Verify the truncated frame was dropped with a warning
assert any("Invalid footer" in line for line in waiter.lines), (
"Expected 'Invalid footer' warning in logs"
assert any("Invalid header/footer" in line for line in waiter.lines), (
"Expected 'Invalid header/footer' warning in logs"
)
# Verify LD2450 sent setup commands (TX logging)
@@ -114,6 +114,9 @@ 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"]