mirror of
https://github.com/esphome/esphome.git
synced 2026-10-22 13:56:10 +00:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97fda5ebfc | ||
|
|
3fffc1becb | ||
|
|
06d3900d76 | ||
|
|
e441ee5b78 | ||
|
|
3993be10ca | ||
|
|
ca2aab69f0 | ||
|
|
ace7f5bc45 | ||
|
|
ab4b24a151 | ||
|
|
1b4d284208 | ||
|
|
5cd4ccf2ca | ||
|
|
323c8bd311 | ||
|
|
e8bef162eb | ||
|
|
d4763b6e7f | ||
|
|
cb0bf36ba9 | ||
|
|
47daadd0fa | ||
|
|
f2ac6f6f93 | ||
|
|
286b3c294e | ||
|
|
e137b11ed6 | ||
|
|
eedb824934 |
@@ -186,23 +186,19 @@ static constexpr uint8_t CMD_DURATION_VALUE = 0x02;
|
||||
// Bitmasks for target states
|
||||
static constexpr uint8_t MOVE_BITMASK = 0x01;
|
||||
static constexpr uint8_t STILL_BITMASK = 0x02;
|
||||
// Header & Footer size
|
||||
static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
|
||||
// Command Header & Footer
|
||||
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};
|
||||
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};
|
||||
// MAC address the module uses when Bluetooth is disabled
|
||||
static constexpr uint8_t NO_MAC[] = {0x08, 0x05, 0x04, 0x03, 0x02, 0x01};
|
||||
static constexpr uint8_t GATE_SENS_ACK_SIZE = ACK_PAYLOAD + TOTAL_GATES + HEADER_FOOTER_SIZE;
|
||||
// The length field counts the command word, the status word and the gates
|
||||
static constexpr uint16_t GATE_SENS_ACK_LENGTH = GATE_SENS_ACK_SIZE - COMMAND - HEADER_FOOTER_SIZE;
|
||||
|
||||
static inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
|
||||
return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;
|
||||
}
|
||||
|
||||
void LD2412Component::dump_config() {
|
||||
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
|
||||
@@ -371,6 +367,9 @@ void LD2412Component::handle_periodic_data_() {
|
||||
0x02: Normal mode
|
||||
*/
|
||||
bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
|
||||
if (this->buffer_pos_ < PERIODIC_FRAME_MIN) {
|
||||
return; // too short to hold the values
|
||||
}
|
||||
#ifdef USE_SWITCH
|
||||
if (this->engineering_mode_switch_ != nullptr) {
|
||||
this->engineering_mode_switch_->publish_state(engineering_mode);
|
||||
@@ -421,8 +420,7 @@ void LD2412Component::handle_periodic_data_() {
|
||||
this->detection_distance_sensor_.publish_state_if_not_dup(new_detect_distance);
|
||||
}
|
||||
if (engineering_mode) {
|
||||
// Engineering mode needs at least LIGHT_SENSOR + 1 bytes
|
||||
if (this->buffer_pos_ < LIGHT_SENSOR + 1) {
|
||||
if (this->buffer_pos_ < ENGINEERING_FRAME_MIN) {
|
||||
ESP_LOGW(TAG, "Engineering mode packet too short: %u", this->buffer_pos_);
|
||||
} else {
|
||||
/*
|
||||
@@ -477,24 +475,15 @@ static constexpr uint32_t GATE_QUERY_TIMEOUT_ID = 0;
|
||||
static constexpr uint32_t GATE_QUERY_TIMEOUT_MS = 2000;
|
||||
#endif
|
||||
|
||||
bool LD2412Component::handle_ack_data_() {
|
||||
void LD2412Component::handle_ack_data_() {
|
||||
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
|
||||
if (this->buffer_pos_ < 10) {
|
||||
ESP_LOGW(TAG, "Invalid length");
|
||||
return true;
|
||||
}
|
||||
if (!ld2412::validate_header_footer(CMD_FRAME_HEADER, this->buffer_data_)) {
|
||||
char hex_buf[format_hex_pretty_size(HEADER_FOOTER_SIZE)];
|
||||
ESP_LOGW(TAG, "Invalid header: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, HEADER_FOOTER_SIZE));
|
||||
return true;
|
||||
}
|
||||
if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
|
||||
ESP_LOGW(TAG, "Invalid status");
|
||||
return true;
|
||||
return;
|
||||
}
|
||||
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 true;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (this->buffer_data_[COMMAND]) {
|
||||
@@ -517,8 +506,8 @@ bool LD2412Component::handle_ack_data_() {
|
||||
break;
|
||||
|
||||
case CMD_QUERY_VERSION: {
|
||||
if (this->buffer_pos_ < 12 + sizeof(this->version_)) {
|
||||
return false;
|
||||
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
|
||||
break; // too short to hold a version
|
||||
}
|
||||
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
|
||||
char version_s[20];
|
||||
@@ -532,6 +521,9 @@ bool LD2412Component::handle_ack_data_() {
|
||||
break;
|
||||
}
|
||||
case CMD_QUERY_DISTANCE_RESOLUTION: {
|
||||
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
|
||||
break; // too short to hold the resolution
|
||||
}
|
||||
const auto *distance_resolution = find_str(DISTANCE_RESOLUTIONS_BY_UINT, this->buffer_data_[10]);
|
||||
ESP_LOGV(TAG, "Distance resolution: %s", distance_resolution);
|
||||
#ifdef USE_SELECT
|
||||
@@ -543,6 +535,9 @@ bool LD2412Component::handle_ack_data_() {
|
||||
}
|
||||
|
||||
case CMD_QUERY_LIGHT_CONTROL: {
|
||||
if (this->buffer_pos_ < 12 + HEADER_FOOTER_SIZE) {
|
||||
break; // too short to hold the light settings
|
||||
}
|
||||
this->light_function_ = this->buffer_data_[10];
|
||||
this->light_threshold_ = this->buffer_data_[11];
|
||||
const auto *light_function_str = find_str(LIGHT_FUNCTIONS_BY_UINT, this->light_function_);
|
||||
@@ -562,7 +557,7 @@ bool LD2412Component::handle_ack_data_() {
|
||||
|
||||
case CMD_QUERY_MAC_ADDRESS: {
|
||||
if (this->buffer_pos_ < 20) {
|
||||
return false;
|
||||
break; // too short to hold a MAC address
|
||||
}
|
||||
|
||||
this->bluetooth_on_ = std::memcmp(&this->buffer_data_[10], NO_MAC, sizeof(NO_MAC)) != 0;
|
||||
@@ -591,6 +586,9 @@ bool LD2412Component::handle_ack_data_() {
|
||||
break;
|
||||
|
||||
case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
|
||||
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 = (this->buffer_data_[10] != 0x00);
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
@@ -613,14 +611,10 @@ bool LD2412Component::handle_ack_data_() {
|
||||
case CMD_QUERY_MOTION_GATE_SENS:
|
||||
case CMD_QUERY_STATIC_GATE_SENS: {
|
||||
#ifdef USE_NUMBER
|
||||
const uint16_t declared = encode_uint16(this->buffer_data_[FRAME_LENGTH + 1], this->buffer_data_[FRAME_LENGTH]);
|
||||
if (declared != GATE_SENS_ACK_LENGTH || this->buffer_pos_ > GATE_SENS_ACK_SIZE) {
|
||||
// A truncated answer merged with the next frame, or a length this driver does not know
|
||||
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", this->buffer_pos_);
|
||||
return true;
|
||||
}
|
||||
if (this->buffer_pos_ < GATE_SENS_ACK_SIZE) {
|
||||
return false; // the footer pattern appeared inside the payload, keep reading
|
||||
return;
|
||||
}
|
||||
const bool motion = this->buffer_data_[COMMAND] == CMD_QUERY_MOTION_GATE_SENS;
|
||||
GateThresholds &group = this->gate_thresholds_(motion);
|
||||
@@ -646,8 +640,8 @@ bool LD2412Component::handle_ack_data_() {
|
||||
case CMD_QUERY_BASIC_CONF: // Query parameters response
|
||||
{
|
||||
#ifdef USE_NUMBER
|
||||
if (this->buffer_pos_ < 15) {
|
||||
return false;
|
||||
if (this->buffer_pos_ < 15 + HEADER_FOOTER_SIZE) {
|
||||
break; // too short to hold the configuration
|
||||
}
|
||||
/*
|
||||
Moving distance range: 9th byte
|
||||
@@ -677,42 +671,36 @@ bool LD2412Component::handle_ack_data_() {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void LD2412Component::readline_(int readch) {
|
||||
if (readch < 0) {
|
||||
return; // No data available
|
||||
}
|
||||
if (this->buffer_pos_ < HEADER_FOOTER_SIZE && readch != DATA_FRAME_HEADER[this->buffer_pos_] &&
|
||||
readch != CMD_FRAME_HEADER[this->buffer_pos_]) {
|
||||
this->buffer_pos_ = 0;
|
||||
return;
|
||||
}
|
||||
if (this->buffer_pos_ < MAX_LINE_LENGTH - 1) {
|
||||
this->buffer_data_[this->buffer_pos_++] = readch;
|
||||
this->buffer_data_[this->buffer_pos_] = 0;
|
||||
} else {
|
||||
// We should never get here, but just in case...
|
||||
ESP_LOGW(TAG, "Max command length exceeded; ignoring");
|
||||
this->buffer_pos_ = 0;
|
||||
}
|
||||
if (this->buffer_pos_ < 4) {
|
||||
return; // Not enough data to process yet
|
||||
}
|
||||
if (ld2412::validate_header_footer(DATA_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
|
||||
// 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_();
|
||||
this->buffer_pos_ = 0; // Reset position index for next message
|
||||
} else if (ld2412::validate_header_footer(CMD_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
|
||||
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
|
||||
if (this->handle_ack_data_()) {
|
||||
this->buffer_pos_ = 0; // Reset position index for next message
|
||||
} else {
|
||||
ESP_LOGV(TAG, "Ack Data incomplete");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!ld2412::validate_header_footer(CMD_FRAME_FOOTER, tail)) {
|
||||
return false;
|
||||
}
|
||||
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
|
||||
this->handle_ack_data_();
|
||||
return true;
|
||||
}
|
||||
|
||||
void LD2412Component::set_config_mode_(bool enable) {
|
||||
|
||||
@@ -111,7 +111,8 @@ class LD2412Component final : public Component, public uart::UARTDevice {
|
||||
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_();
|
||||
bool handle_ack_data_();
|
||||
void handle_ack_data_();
|
||||
bool handle_frame_(uint8_t frame_len);
|
||||
void readline_(int readch);
|
||||
void query_parameters_();
|
||||
void get_version_();
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
@@ -53,6 +55,74 @@ inline void format_version_str(const uint8_t *version, std::span<char, 20> buffe
|
||||
version[2]);
|
||||
}
|
||||
|
||||
// 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] = {0xFD, 0xFC, 0xFB, 0xFA};
|
||||
static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0x04, 0x03, 0x02, 0x01};
|
||||
|
||||
inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
|
||||
return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
template<typename T> using SensorWithDedup = sensor::SensorWithDedup<T>;
|
||||
#endif
|
||||
|
||||
@@ -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
|
||||
@@ -30,7 +30,7 @@ uart_mock:
|
||||
# Target state: 0x03 (moving + still)
|
||||
# detection_distance = 100 (LD2412 computes from moving target when MOVE_BITMASK set)
|
||||
#
|
||||
# Frame layout (24 bytes):
|
||||
# Frame layout (23 bytes):
|
||||
# [0-3] F4 F3 F2 F1 = data frame header
|
||||
# [4-5] 0D 00 = length 13
|
||||
# [6] 02 = data type (normal)
|
||||
@@ -41,10 +41,9 @@ uart_mock:
|
||||
# [12-13] 78 00 = still distance 120 (0x0078)
|
||||
# [14] 19 = still energy 25
|
||||
# [15-16] 64 00 = detect distance bytes (ignored by LD2412 code)
|
||||
# [17] 00 = padding
|
||||
# [18] 55 = data footer marker
|
||||
# [19] 00 = CRC/check
|
||||
# [20-23] F8 F7 F6 F5 = data frame footer
|
||||
# [17] 55 = data footer marker
|
||||
# [18] 00 = CRC/check
|
||||
# [19-22] F8 F7 F6 F5 = data frame footer
|
||||
- delay: 100ms
|
||||
inject_rx:
|
||||
[
|
||||
@@ -57,7 +56,6 @@ uart_mock:
|
||||
0x78, 0x00,
|
||||
0x19,
|
||||
0x64, 0x00,
|
||||
0x00,
|
||||
0x55, 0x00,
|
||||
0xF8, 0xF7, 0xF6, 0xF5,
|
||||
]
|
||||
@@ -69,17 +67,13 @@ uart_mock:
|
||||
inject_rx: [0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x11, 0x22]
|
||||
|
||||
# Phase 3 (t=400ms): Truncated frame (header + partial data, no footer)
|
||||
# Starts with valid data frame header so parser accepts it.
|
||||
# After this, buffer_pos_ = 8.
|
||||
# Starts with a valid data frame header, so the parser waits for the 23 bytes its length announces.
|
||||
- delay: 100ms
|
||||
inject_rx: [0xF4, 0xF3, 0xF2, 0xF1, 0x0D, 0x00, 0x02, 0xAA]
|
||||
|
||||
# Phase 4 (t=600ms): Overflow - inject 60 bytes of 0xFF (MAX_LINE_LENGTH=54)
|
||||
# Buffer has 8 bytes from phase 3 (garbage in phase 2 was rejected).
|
||||
# Overflow math: buffer_pos_ starts at 8, overflow triggers when
|
||||
# buffer_pos_ reaches 53 (MAX_LINE_LENGTH - 1). Need 45 more bytes to
|
||||
# fill positions 8-52, then byte 46 triggers overflow. After overflow,
|
||||
# buffer_pos_ = 0 and remaining 0xFF bytes are rejected (don't match header).
|
||||
# Phase 4 (t=600ms): 60 bytes of 0xFF
|
||||
# The first 15 complete the truncated frame's 23 bytes without its footer, so it is dropped
|
||||
# with an 'Invalid length' warning; the rest cannot start a header and are dropped too.
|
||||
- delay: 200ms
|
||||
inject_rx:
|
||||
[
|
||||
@@ -91,8 +85,8 @@ uart_mock:
|
||||
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
|
||||
]
|
||||
|
||||
# Phase 5 (t=700ms): Valid frame after overflow - recovery test
|
||||
# Buffer was reset by overflow. This valid frame should parse correctly.
|
||||
# Phase 5 (t=700ms): Valid frame after the garbage - recovery test
|
||||
# The buffer is empty again, so this valid frame should parse correctly.
|
||||
# Moving target: 50cm, energy 100
|
||||
# Still target: 75cm, energy 80
|
||||
# detection_distance = 50 (moving target distance, since MOVE_BITMASK set)
|
||||
@@ -108,7 +102,72 @@ uart_mock:
|
||||
0x4B, 0x00,
|
||||
0x50,
|
||||
0x32, 0x00,
|
||||
0x00,
|
||||
0x55, 0x00,
|
||||
0xF8, 0xF7, 0xF6, 0xF5,
|
||||
]
|
||||
|
||||
# Phase 6 (t=3200ms): Values that spell the command footer 04 03 02 01
|
||||
# Moving distance 772 (0x0304), moving energy 2, still distance 1: bytes 9 to 12 are the
|
||||
# command frame footer, which must not end the frame early.
|
||||
# Still energy 5, detection_distance = 772 (moving target distance, since MOVE_BITMASK set).
|
||||
# The sensors hold and throttle values for a second, so the gap lets the phase 5 states
|
||||
# reach the test before these replace them.
|
||||
- delay: 2500ms
|
||||
inject_rx:
|
||||
[
|
||||
0xF4, 0xF3, 0xF2, 0xF1,
|
||||
0x0D, 0x00,
|
||||
0x02, 0xAA,
|
||||
0x03,
|
||||
0x04, 0x03,
|
||||
0x02,
|
||||
0x01, 0x00,
|
||||
0x05,
|
||||
0x04, 0x03,
|
||||
0x55, 0x00,
|
||||
0xF8, 0xF7, 0xF6, 0xF5,
|
||||
]
|
||||
|
||||
# Phase 7 (t=5700ms): Truncated frame merged with a complete one
|
||||
# The eight header bytes announce a 23 byte frame, so its window takes in the first 15 bytes of
|
||||
# the valid frame that follows. The merged frame has no footer where the count says, so it is
|
||||
# dropped and the bytes after its header are replayed, which recovers the valid frame.
|
||||
# Moving distance 400, moving energy 7, still distance 200, still energy 9, detection_distance = 400
|
||||
- delay: 2500ms
|
||||
inject_rx:
|
||||
[
|
||||
0xF4, 0xF3, 0xF2, 0xF1, 0x0D, 0x00, 0x02, 0xAA,
|
||||
0xF4, 0xF3, 0xF2, 0xF1,
|
||||
0x0D, 0x00,
|
||||
0x02, 0xAA,
|
||||
0x03,
|
||||
0x90, 0x01,
|
||||
0x07,
|
||||
0xC8, 0x00,
|
||||
0x09,
|
||||
0x90, 0x01,
|
||||
0x55, 0x00,
|
||||
0xF8, 0xF7, 0xF6, 0xF5,
|
||||
]
|
||||
|
||||
# Phase 8 (t=8200ms): Impossible counts, then a complete frame
|
||||
# A command header counting 0xFFF6 bytes (65536 in total, which must not wrap to 0) and one counting
|
||||
# 0xFFFF are each dropped as soon as the count arrives, and the valid frame after them is parsed.
|
||||
# Moving distance 600, moving energy 11, still distance 300, still energy 13, detection distance 600
|
||||
- delay: 2500ms
|
||||
inject_rx:
|
||||
[
|
||||
0xFD, 0xFC, 0xFB, 0xFA, 0xF6, 0xFF,
|
||||
0xFD, 0xFC, 0xFB, 0xFA, 0xFF, 0xFF,
|
||||
0xF4, 0xF3, 0xF2, 0xF1,
|
||||
0x0D, 0x00,
|
||||
0x02, 0xAA,
|
||||
0x03,
|
||||
0x58, 0x02,
|
||||
0x0B,
|
||||
0x2C, 0x01,
|
||||
0x0D,
|
||||
0x58, 0x02,
|
||||
0x55, 0x00,
|
||||
0xF8, 0xF7, 0xF6, 0xF5,
|
||||
]
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
esphome:
|
||||
name: uart-mock-ld2412-short-answers
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
external_components:
|
||||
- source:
|
||||
type: local
|
||||
path: EXTERNAL_COMPONENT_PATH
|
||||
|
||||
# Dummy uart entry to satisfy ld2412's DEPENDENCIES = ["uart"]
|
||||
# The actual UART bus used is the uart_mock component below
|
||||
uart:
|
||||
baud_rate: 115200
|
||||
port: /dev/null
|
||||
|
||||
# Answers cut short, so the footer sits where their values would be, each followed by a whole one
|
||||
uart_mock:
|
||||
id: mock_uart
|
||||
baud_rate: 256000
|
||||
auto_start: false
|
||||
injections:
|
||||
# Version answer cut after two version bytes
|
||||
- delay: 100ms
|
||||
inject_rx:
|
||||
[
|
||||
0xFD, 0xFC, 0xFB, 0xFA, 0x08, 0x00, 0xA0, 0x01, 0x00, 0x00,
|
||||
0x00, 0x01, 0x07, 0x02,
|
||||
0x04, 0x03, 0x02, 0x01,
|
||||
]
|
||||
|
||||
# Basic configuration answer cut after the minimum gate 7
|
||||
- delay: 100ms
|
||||
inject_rx:
|
||||
[
|
||||
0xFD, 0xFC, 0xFB, 0xFA, 0x05, 0x00, 0x12, 0x01, 0x00, 0x00,
|
||||
0x07,
|
||||
0x04, 0x03, 0x02, 0x01,
|
||||
]
|
||||
|
||||
# Whole version answer: firmware type 1, version 2.07.22062416
|
||||
- delay: 100ms
|
||||
inject_rx:
|
||||
[
|
||||
0xFD, 0xFC, 0xFB, 0xFA, 0x0C, 0x00, 0xA0, 0x01, 0x00, 0x00,
|
||||
0x00, 0x01, 0x07, 0x02, 0x16, 0x24, 0x06, 0x22,
|
||||
0x04, 0x03, 0x02, 0x01,
|
||||
]
|
||||
|
||||
# Whole basic configuration answer: gates 3 to 9, timeout 10 s, output pin level low
|
||||
- delay: 100ms
|
||||
inject_rx:
|
||||
[
|
||||
0xFD, 0xFC, 0xFB, 0xFA, 0x09, 0x00, 0x12, 0x01, 0x00, 0x00,
|
||||
0x03, 0x09, 0x0A, 0x00, 0x01,
|
||||
0x04, 0x03, 0x02, 0x01,
|
||||
]
|
||||
|
||||
ld2412:
|
||||
id: ld2412_dev
|
||||
uart_id: mock_uart
|
||||
|
||||
number:
|
||||
- platform: ld2412
|
||||
ld2412_id: ld2412_dev
|
||||
min_distance_gate:
|
||||
name: "Min Distance Gate"
|
||||
max_distance_gate:
|
||||
name: "Max Distance Gate"
|
||||
timeout:
|
||||
name: "Timeout"
|
||||
|
||||
text_sensor:
|
||||
- platform: ld2412
|
||||
ld2412_id: ld2412_dev
|
||||
version:
|
||||
name: "Version"
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: "Start Scenario"
|
||||
id: start_scenario_btn
|
||||
on_press:
|
||||
- lambda: 'id(mock_uart).start_scenario();'
|
||||
@@ -37,7 +37,7 @@ uart_mock:
|
||||
0x04, 0x00, # length 4
|
||||
0xFE, 0x01, # answer to command 0x00FE
|
||||
0x00, 0x00, # status: success
|
||||
0x04, 0x03, 0x02, 0x01, # its footer; the merged 40-byte frame gets dropped
|
||||
0x04, 0x03, 0x02, 0x01, # its footer; the 28 bytes the answer announced hold no footer, so it is dropped
|
||||
]
|
||||
# A complete answer after setup proves the parser recovered
|
||||
injections:
|
||||
|
||||
@@ -5,9 +5,12 @@ test_uart_mock_ld2412 (normal mode):
|
||||
1. Happy path - valid data frame publishes correct sensor values
|
||||
2. Garbage resilience - random bytes don't crash the component
|
||||
3. Truncated frame handling - partial frame doesn't corrupt state
|
||||
4. Buffer overflow recovery - overflow resets the parser
|
||||
5. Post-overflow parsing - next valid frame after overflow is parsed correctly
|
||||
6. TX logging - verifies LD2412 sends expected setup commands
|
||||
4. Truncated frame recovery - the frame is dropped once its length is reached
|
||||
5. Post-garbage parsing - the next valid frame is parsed correctly
|
||||
6. Footer bytes in the values - a frame whose values spell the command footer is parsed whole
|
||||
7. Replay after a drop - a valid frame caught inside a dropped frame's window is still parsed
|
||||
8. Impossible counts - a length field of 0xFFF6 or 0xFFFF is dropped and the next frame is parsed
|
||||
9. TX logging - verifies LD2412 sends expected setup commands
|
||||
|
||||
test_uart_mock_ld2412_engineering (engineering mode):
|
||||
1. Engineering mode frames with per-gate energy data and light sensor
|
||||
@@ -24,6 +27,7 @@ test_uart_mock_ld2412_engineering_truncated (truncated engineering mode):
|
||||
The gate threshold tests (footer_in_payload, truncated_answer, requery_after_giveup) cover
|
||||
answers that hold the frame footer or are truncated, writes that fill the gates without a
|
||||
number from the module's values, and writes held back until the module reports them.
|
||||
test_uart_mock_ld2412_short_answers: answers cut short publish nothing, the whole ones after them do.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,6 +43,7 @@ from aioesphomeapi import (
|
||||
EntityState,
|
||||
NumberInfo,
|
||||
NumberState,
|
||||
TextSensorState,
|
||||
)
|
||||
import pytest
|
||||
|
||||
@@ -138,18 +143,18 @@ async def test_uart_mock_ld2412(
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Test LD2412 data parsing with happy path, garbage, overflow, and recovery."""
|
||||
"""Test LD2412 data parsing with happy path, garbage, a truncated frame, and recovery."""
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
# Track overflow warning in logs
|
||||
overflow_seen = loop.create_future()
|
||||
# Track the warning for the dropped truncated frame in logs
|
||||
resync_seen = loop.create_future()
|
||||
|
||||
# Track TX data logged by the mock for assertions
|
||||
tx_log_lines: list[str] = []
|
||||
|
||||
def line_callback(line: str) -> None:
|
||||
if "Max command length exceeded" in line and not overflow_seen.done():
|
||||
overflow_seen.set_result(True)
|
||||
if "Invalid length" in line and not resync_seen.done():
|
||||
resync_seen.set_result(True)
|
||||
# Capture all TX log lines from uart_mock
|
||||
if _is_tx(line):
|
||||
tx_log_lines.append(line)
|
||||
@@ -177,6 +182,22 @@ async def test_uart_mock_ld2412(
|
||||
and pytest.approx(100.0) in collector.sensor_states["moving_energy"]
|
||||
and pytest.approx(80.0) in collector.sensor_states["still_energy"]
|
||||
and pytest.approx(50.0) in collector.sensor_states["detection_distance"]
|
||||
and pytest.approx(772.0) in collector.sensor_states["moving_distance"]
|
||||
and pytest.approx(400.0) in collector.sensor_states["moving_distance"]
|
||||
# Every value asserted below, so no state can still be in flight when the waiter fires
|
||||
and pytest.approx(2.0) in collector.sensor_states["moving_energy"]
|
||||
and pytest.approx(1.0) in collector.sensor_states["still_distance"]
|
||||
and pytest.approx(5.0) in collector.sensor_states["still_energy"]
|
||||
and pytest.approx(772.0) in collector.sensor_states["detection_distance"]
|
||||
and pytest.approx(7.0) in collector.sensor_states["moving_energy"]
|
||||
and pytest.approx(200.0) in collector.sensor_states["still_distance"]
|
||||
and pytest.approx(9.0) in collector.sensor_states["still_energy"]
|
||||
and pytest.approx(400.0) in collector.sensor_states["detection_distance"]
|
||||
and pytest.approx(600.0) in collector.sensor_states["moving_distance"]
|
||||
and pytest.approx(11.0) in collector.sensor_states["moving_energy"]
|
||||
and pytest.approx(300.0) in collector.sensor_states["still_distance"]
|
||||
and pytest.approx(13.0) in collector.sensor_states["still_energy"]
|
||||
and pytest.approx(600.0) in collector.sensor_states["detection_distance"]
|
||||
)
|
||||
)
|
||||
|
||||
@@ -204,18 +225,16 @@ async def test_uart_mock_ld2412(
|
||||
assert collector.sensor_states["detection_distance"][0] == pytest.approx(100.0)
|
||||
|
||||
# Wait for the recovery frame (Phase 5) to be parsed
|
||||
# This proves the component survived garbage + truncated + overflow
|
||||
# This proves the component survived garbage + truncated frame + filler bytes
|
||||
await wait_or_fail(
|
||||
recovery_received,
|
||||
3.0,
|
||||
15.0,
|
||||
"Timeout waiting for recovery frame",
|
||||
sensor_states=collector.sensor_states,
|
||||
)
|
||||
|
||||
# Verify overflow warning was logged
|
||||
assert overflow_seen.done(), (
|
||||
"Expected 'Max command length exceeded' warning in logs"
|
||||
)
|
||||
# Verify the truncated frame was dropped with a warning
|
||||
assert resync_seen.done(), "Expected 'Invalid length' warning in logs"
|
||||
|
||||
# Verify LD2412 sent setup commands (TX logging)
|
||||
assert len(tx_log_lines) > 0, "Expected TX log lines from uart_mock"
|
||||
@@ -235,6 +254,27 @@ async def test_uart_mock_ld2412(
|
||||
assert pytest.approx(80.0) in collector.sensor_states["still_energy"]
|
||||
assert pytest.approx(50.0) in collector.sensor_states["detection_distance"]
|
||||
|
||||
# Phase 6: the values 04 03 02 01 did not end the frame early
|
||||
assert pytest.approx(772.0) in collector.sensor_states["moving_distance"]
|
||||
assert pytest.approx(2.0) in collector.sensor_states["moving_energy"]
|
||||
assert pytest.approx(1.0) in collector.sensor_states["still_distance"]
|
||||
assert pytest.approx(5.0) in collector.sensor_states["still_energy"]
|
||||
assert pytest.approx(772.0) in collector.sensor_states["detection_distance"]
|
||||
|
||||
# Phase 7: the valid frame inside the dropped frame's window was replayed and parsed
|
||||
assert pytest.approx(400.0) in collector.sensor_states["moving_distance"]
|
||||
assert pytest.approx(7.0) in collector.sensor_states["moving_energy"]
|
||||
assert pytest.approx(200.0) in collector.sensor_states["still_distance"]
|
||||
assert pytest.approx(9.0) in collector.sensor_states["still_energy"]
|
||||
assert pytest.approx(400.0) in collector.sensor_states["detection_distance"]
|
||||
|
||||
# Phase 8: both impossible counts were dropped and the frame after them was parsed
|
||||
assert pytest.approx(600.0) in collector.sensor_states["moving_distance"]
|
||||
assert pytest.approx(11.0) in collector.sensor_states["moving_energy"]
|
||||
assert pytest.approx(300.0) in collector.sensor_states["still_distance"]
|
||||
assert pytest.approx(13.0) in collector.sensor_states["still_energy"]
|
||||
assert pytest.approx(600.0) in collector.sensor_states["detection_distance"]
|
||||
|
||||
# Verify binary sensors detected targets (from Phase 1 frame)
|
||||
assert collector.binary_states["has_target"][0] is True
|
||||
assert collector.binary_states["has_moving_target"][0] is True
|
||||
@@ -524,7 +564,7 @@ async def test_uart_mock_ld2412_truncated_answer(
|
||||
def line_callback(line: str) -> None:
|
||||
if "[W][ld2412" in line:
|
||||
warnings.append(line)
|
||||
if "Dropping gate threshold answer" in line and not dropped.done():
|
||||
if "Invalid length" in line and not dropped.done():
|
||||
dropped.set_result(True)
|
||||
|
||||
# Gate bytes of the truncated answer
|
||||
@@ -681,3 +721,56 @@ async def test_uart_mock_ld2412_requery_after_giveup(
|
||||
assert gate_0_state.state == pytest.approx(25.0)
|
||||
assert gate_5_values
|
||||
assert all(value == pytest.approx(30.0) for value in gate_5_values)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uart_mock_ld2412_short_answers(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Test that answers cut short publish nothing and the whole answers after them do."""
|
||||
loop = asyncio.get_running_loop()
|
||||
# Number object_id: the value from the whole basic configuration answer
|
||||
expected = {"min_distance_gate": 3.0, "max_distance_gate": 8.0, "timeout": 10.0}
|
||||
number_states: dict[str, list[float]] = {name: [] for name in expected}
|
||||
version_states: list[str] = []
|
||||
key_to_name: dict[int, str] = {}
|
||||
all_received = loop.create_future()
|
||||
|
||||
def on_state(state: EntityState) -> None:
|
||||
if isinstance(state, TextSensorState) and not state.missing_state:
|
||||
version_states.append(state.state)
|
||||
elif (
|
||||
isinstance(state, NumberState)
|
||||
and not state.missing_state
|
||||
and (name := key_to_name.get(state.key)) is not None
|
||||
):
|
||||
number_states[name].append(state.state)
|
||||
if not all_received.done() and version_states and all(number_states.values()):
|
||||
all_received.set_result(True)
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
entities, _ = await client.list_entities_services()
|
||||
key_to_name.update(
|
||||
{require_entity(entities, name, NumberInfo).key: name for name in expected}
|
||||
)
|
||||
await _wait_initial(client, entities, on_state)
|
||||
|
||||
start_btn = require_entity(entities, "start_scenario", ButtonInfo)
|
||||
client.button_command(start_btn.key)
|
||||
|
||||
await wait_or_fail(
|
||||
all_received,
|
||||
5.0,
|
||||
"Timeout waiting for the whole answers",
|
||||
number_states=number_states,
|
||||
version_states=version_states,
|
||||
)
|
||||
# Each entity saw exactly one value, the one from the whole answer
|
||||
assert version_states == ["2.07.22062416"]
|
||||
for name, value in expected.items():
|
||||
assert number_states[name] == pytest.approx([value]), name
|
||||
|
||||
Reference in New Issue
Block a user