11static constexpr uint8_t ANGLE_OFFSET = 0x80;
13static constexpr uint8_t DIRECTION_APPROACHING = 0x01;
16 ESP_LOGW(TAG,
"Skipped a data frame of %u bytes; more than %u targets are not supported",
static_cast<unsigned>(
len),
21 ESP_LOGCONFIG(TAG,
"LD2451:");
23 LOG_SENSOR_WITH_DEDUP(
" ",
"TargetCount", this->target_count_sensor_);
25 LOG_SENSOR_WITH_DEDUP(
" ",
"TargetAngle", t.angle);
26 LOG_SENSOR_WITH_DEDUP(
" ",
"TargetDistance", t.distance);
27 LOG_SENSOR_WITH_DEDUP(
" ",
"TargetSpeed", t.speed);
28 LOG_SENSOR_WITH_DEDUP(
" ",
"TargetSnr", t.snr);
33void LD2451Component::loop() {
35 auto handler = [
this](
const uint8_t *frame,
size_t len) {
return this->
handle_frame_(frame,
len); };
42 ESP_LOGW(TAG,
"Invalid footer");
43 ESP_LOGV_HEX(TAG, frame,
len, MAX_FRAME_LENGTH,
"Rejected: %s");
46 ESP_LOGV_HEX(TAG, frame,
len, MAX_FRAME_LENGTH,
"Frame: %s");
50 return this->
handle_data_(&frame[PAYLOAD_OFFSET],
len - PAYLOAD_OFFSET - ld24xx::HEADER_FOOTER_SIZE);
56 const uint8_t num_targets =
len == 0 ? 0 : payload[0];
57 if (
len != 0 &&
len != 2 + num_targets * TARGET_SIZE) {
58 ESP_LOGW(TAG,
"Payload of %u bytes does not match a target count of %u",
static_cast<unsigned>(
len), num_targets);
63 for (uint8_t i = 0; i < MAX_TARGETS; i++) {
65 if (i >= num_targets) {
66 SAFE_PUBLISH_SENSOR_UNKNOWN(t.angle);
67 SAFE_PUBLISH_SENSOR_UNKNOWN(t.distance);
68 SAFE_PUBLISH_SENSOR_UNKNOWN(t.speed);
69 SAFE_PUBLISH_SENSOR_UNKNOWN(t.snr);
72 const uint8_t *p = &payload[2 + i * TARGET_SIZE];
73 const auto angle =
static_cast<int8_t
>(p[0] - ANGLE_OFFSET);
74 const int16_t
speed = p[2] == DIRECTION_APPROACHING ? -p[3] : p[3];
75 ESP_LOGV(TAG,
"Target %u: angle %d, distance %u m, speed %d km/h, SNR %u", i + 1, angle, p[1],
speed, p[4]);
76 SAFE_PUBLISH_SENSOR(t.angle, angle);
77 SAFE_PUBLISH_SENSOR(t.distance, p[1]);
78 SAFE_PUBLISH_SENSOR(t.speed,
speed);
79 SAFE_PUBLISH_SENSOR(t.snr, p[4]);
81 SAFE_PUBLISH_SENSOR(this->target_count_sensor_, num_targets);
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void dump_config()
bool handle_data_(const uint8_t *payload, size_t len)
LengthFrameReader< MAX_FRAME_LENGTH, DataFrame, ld24xx::CmdFrameFormat > reader_
bool handle_frame_(const uint8_t *frame, size_t len)
std::array< TargetSensors, MAX_TARGETS > target_sensors_
bool read_frames(R &reader, F &&handle, uint32_t now, uint32_t &last_rx, uint32_t gap_ms=250)
Feed the waiting bytes to a LengthFrameReader; on a pass with none, gap_ms after last_rx,...
void warn_too_many_targets(size_t len)
Warns about a data frame with more targets than MAX_TARGETS, which is skipped.
ESPHOME_LOG_TAG(TAG, "ld2451")
bool has_footer(const uint8_t *frame, size_t len)
Application App
Global storage of Application pointer - only one Application can exist.