ESPHome 2026.8.0b4
Loading...
Searching...
No Matches
ld6002b.cpp
Go to the documentation of this file.
1#include "ld6002b.h"
2#include "esphome/core/log.h"
3#include <algorithm>
4#include <cinttypes>
5#include <cmath>
6#include <cstdio>
7#include <cstring>
8
9namespace esphome::ld6002b {
10
11static const char *const TAG = "ld6002b";
12
13static constexpr uint8_t TF_SOF = 0x01;
14static constexpr uint32_t SETUP_DELAY_MS = 100;
15
16// Command/message types
17static constexpr uint16_t TYPE_CONTROL = 0x0201;
18static constexpr uint16_t TYPE_SET_AREA = 0x0202;
19static constexpr uint16_t TYPE_SET_HOLD_DELAY = 0x0203;
20static constexpr uint16_t TYPE_SET_Z_RANGE = 0x0204;
21static constexpr uint16_t TYPE_SET_LOW_POWER_SLEEP = 0x0205;
22
23static constexpr uint16_t TYPE_REPORT_TARGET = 0x0A04;
24static constexpr uint16_t TYPE_REPORT_POINT_CLOUD = 0x0A08;
25static constexpr uint16_t TYPE_REPORT_AREA_PRESENCE = 0x0A0A;
26static constexpr uint16_t TYPE_REPORT_INTERFERENCE_AREAS = 0x0A0B;
27static constexpr uint16_t TYPE_REPORT_DETECTION_AREAS = 0x0A0C;
28static constexpr uint16_t TYPE_REPORT_DELAY = 0x0A0D;
29static constexpr uint16_t TYPE_REPORT_SENSITIVITY = 0x0A0E;
30static constexpr uint16_t TYPE_REPORT_TRIGGER = 0x0A0F;
31static constexpr uint16_t TYPE_REPORT_Z_RANGE = 0x0A10;
32static constexpr uint16_t TYPE_REPORT_INSTALLATION = 0x0A11;
33static constexpr uint16_t TYPE_REPORT_LOW_POWER = 0x0A12;
34static constexpr uint16_t TYPE_REPORT_LOW_POWER_SLEEP = 0x0A13;
35static constexpr uint16_t TYPE_REPORT_WORK_MODE = 0x0A14;
36static constexpr uint16_t TYPE_QUERY_VERSION = 0xFFFF;
37
38// Control command values for TYPE_CONTROL
39static constexpr uint32_t CMD_AUTO_INTERFERENCE = 0x01;
40static constexpr uint32_t CMD_GET_AREAS = 0x02;
41static constexpr uint32_t CMD_CLEAR_INTERFERENCE = 0x03;
42static constexpr uint32_t CMD_RESET_DETECTION_AREA = 0x04;
43static constexpr uint32_t CMD_GET_DELAY = 0x05;
44static constexpr uint32_t CMD_POINT_CLOUD_ON = 0x06;
45static constexpr uint32_t CMD_POINT_CLOUD_OFF = 0x07;
46static constexpr uint32_t CMD_TARGET_DISPLAY_ON = 0x08;
47static constexpr uint32_t CMD_TARGET_DISPLAY_OFF = 0x09;
48static constexpr uint32_t CMD_SENSITIVITY_LOW = 0x0A;
49static constexpr uint32_t CMD_SENSITIVITY_MEDIUM = 0x0B;
50static constexpr uint32_t CMD_SENSITIVITY_HIGH = 0x0C;
51static constexpr uint32_t CMD_GET_SENSITIVITY = 0x0D;
52static constexpr uint32_t CMD_TRIGGER_SLOW = 0x0E;
53static constexpr uint32_t CMD_TRIGGER_MEDIUM = 0x0F;
54static constexpr uint32_t CMD_TRIGGER_FAST = 0x10;
55static constexpr uint32_t CMD_GET_TRIGGER = 0x11;
56static constexpr uint32_t CMD_GET_Z_RANGE = 0x12;
57static constexpr uint32_t CMD_INSTALL_TOP = 0x13;
58static constexpr uint32_t CMD_INSTALL_SIDE = 0x14;
59static constexpr uint32_t CMD_GET_INSTALLATION = 0x15;
60static constexpr uint32_t CMD_LOW_POWER_ON = 0x16;
61static constexpr uint32_t CMD_LOW_POWER_OFF = 0x17;
62static constexpr uint32_t CMD_GET_LOW_POWER = 0x18;
63static constexpr uint32_t CMD_GET_LOW_POWER_SLEEP = 0x19;
64static constexpr uint32_t CMD_RESET_UNATTENDED = 0x1A;
65
66static constexpr uint16_t TARGET_DATA_LEN = 20; // x,y,z,dop_idx,cluster_id
67static constexpr uint16_t AREA_DATA_LEN = 24; // 6 floats
68static constexpr uint16_t AREA_CONFIG_LEN = 28; // int32 + 6 floats
69static constexpr uint16_t AREA_PRESENCE_ENTRY_LEN = 4; // uint32 per detection area
70
71static constexpr uint8_t AREA_ID_DEFAULT = 4; // detection_area_0 for initial display
72
73static constexpr uint8_t VERSION_QUERY_DATA[] = {0x01, 0x01, 0x00, 0x00};
74
75#ifdef ESPHOME_LOG_HAS_VERBOSE
76static const char *control_command_name(uint32_t command) {
77 switch (command) {
78 case CMD_AUTO_INTERFERENCE:
79 return "auto_interference";
80 case CMD_GET_AREAS:
81 return "get_areas";
82 case CMD_CLEAR_INTERFERENCE:
83 return "clear_interference";
84 case CMD_RESET_DETECTION_AREA:
85 return "reset_detection_area";
86 case CMD_GET_DELAY:
87 return "get_delay";
88 case CMD_POINT_CLOUD_ON:
89 return "point_cloud_on";
90 case CMD_POINT_CLOUD_OFF:
91 return "point_cloud_off";
92 case CMD_TARGET_DISPLAY_ON:
93 return "target_display_on";
94 case CMD_TARGET_DISPLAY_OFF:
95 return "target_display_off";
96 case CMD_SENSITIVITY_LOW:
97 return "sensitivity_low";
98 case CMD_SENSITIVITY_MEDIUM:
99 return "sensitivity_medium";
100 case CMD_SENSITIVITY_HIGH:
101 return "sensitivity_high";
102 case CMD_GET_SENSITIVITY:
103 return "get_sensitivity";
104 case CMD_TRIGGER_SLOW:
105 return "trigger_slow";
106 case CMD_TRIGGER_MEDIUM:
107 return "trigger_medium";
108 case CMD_TRIGGER_FAST:
109 return "trigger_fast";
110 case CMD_GET_TRIGGER:
111 return "get_trigger";
112 case CMD_GET_Z_RANGE:
113 return "get_z_range";
114 case CMD_INSTALL_TOP:
115 return "install_top";
116 case CMD_INSTALL_SIDE:
117 return "install_side";
118 case CMD_GET_INSTALLATION:
119 return "get_installation";
120 case CMD_LOW_POWER_ON:
121 return "low_power_on";
122 case CMD_LOW_POWER_OFF:
123 return "low_power_off";
124 case CMD_GET_LOW_POWER:
125 return "get_low_power";
126 case CMD_GET_LOW_POWER_SLEEP:
127 return "get_low_power_sleep";
128 case CMD_RESET_UNATTENDED:
129 return "reset_unattended";
130 default:
131 return "unknown";
132 }
133}
134
135static const char *frame_type_name(uint16_t type) {
136 switch (type) {
137 case TYPE_CONTROL:
138 return "control";
139 case TYPE_SET_AREA:
140 return "set_area";
141 case TYPE_SET_HOLD_DELAY:
142 return "set_hold_delay";
143 case TYPE_SET_Z_RANGE:
144 return "set_z_range";
145 case TYPE_SET_LOW_POWER_SLEEP:
146 return "set_low_power_sleep";
147 case TYPE_REPORT_TARGET:
148 return "report_target";
149 case TYPE_REPORT_POINT_CLOUD:
150 return "report_point_cloud";
151 case TYPE_REPORT_AREA_PRESENCE:
152 return "report_area_presence";
153 case TYPE_REPORT_INTERFERENCE_AREAS:
154 return "report_interference_areas";
155 case TYPE_REPORT_DETECTION_AREAS:
156 return "report_detection_areas";
157 case TYPE_REPORT_DELAY:
158 return "report_delay";
159 case TYPE_REPORT_SENSITIVITY:
160 return "report_sensitivity";
161 case TYPE_REPORT_TRIGGER:
162 return "report_trigger";
163 case TYPE_REPORT_Z_RANGE:
164 return "report_z_range";
165 case TYPE_REPORT_INSTALLATION:
166 return "report_installation";
167 case TYPE_REPORT_LOW_POWER:
168 return "report_low_power";
169 case TYPE_REPORT_LOW_POWER_SLEEP:
170 return "report_low_power_sleep";
171 case TYPE_REPORT_WORK_MODE:
172 return "report_work_mode";
173 case TYPE_QUERY_VERSION:
174 return "query_version";
175 default:
176 return "unknown";
177 }
178}
179
180static bool is_expected_control_report(uint32_t command, uint16_t type) {
181 switch (command) {
182 case CMD_GET_AREAS:
183 return type == TYPE_REPORT_INTERFERENCE_AREAS || type == TYPE_REPORT_DETECTION_AREAS;
184 case CMD_GET_DELAY:
185 return type == TYPE_REPORT_DELAY;
186 case CMD_GET_SENSITIVITY:
187 return type == TYPE_REPORT_SENSITIVITY;
188 case CMD_GET_TRIGGER:
189 return type == TYPE_REPORT_TRIGGER;
190 case CMD_GET_Z_RANGE:
191 return type == TYPE_REPORT_Z_RANGE;
192 case CMD_GET_INSTALLATION:
193 return type == TYPE_REPORT_INSTALLATION;
194 case CMD_GET_LOW_POWER:
195 case CMD_LOW_POWER_ON:
196 case CMD_LOW_POWER_OFF:
197 return type == TYPE_REPORT_LOW_POWER;
198 case CMD_GET_LOW_POWER_SLEEP:
199 return type == TYPE_REPORT_LOW_POWER_SLEEP;
200 default:
201 return false;
202 }
203}
204#endif
205
206uint16_t LD6002BComponent::read_u16_be(const uint8_t *data) { return (static_cast<uint16_t>(data[0]) << 8) | data[1]; }
207
209 return static_cast<uint32_t>(data[0]) | (static_cast<uint32_t>(data[1]) << 8) |
210 (static_cast<uint32_t>(data[2]) << 16) | (static_cast<uint32_t>(data[3]) << 24);
211}
212
213int32_t LD6002BComponent::read_int32_le(const uint8_t *data) {
214 uint32_t raw = read_u32_le(data);
215 int32_t value;
216 std::memcpy(&value, &raw, sizeof(value));
217 return value;
218}
219
220float LD6002BComponent::read_f32_le(const uint8_t *data) {
221 uint32_t raw = read_u32_le(data);
222 float value;
223 std::memcpy(&value, &raw, sizeof(value));
224 return value;
225}
226
227void LD6002BComponent::write_u32_le(uint8_t *data, uint32_t value) {
228 data[0] = value & 0xFF;
229 data[1] = (value >> 8) & 0xFF;
230 data[2] = (value >> 16) & 0xFF;
231 data[3] = (value >> 24) & 0xFF;
232}
233
234void LD6002BComponent::write_int32_le(uint8_t *data, int32_t value) {
235 write_u32_le(data, static_cast<uint32_t>(value));
236}
237
238void LD6002BComponent::write_f32_le(uint8_t *data, float value) {
240 std::memcpy(&raw, &value, sizeof(raw));
241 write_u32_le(data, raw);
242}
243
245 // Only the point cloud stream needs the larger frame; nothing resizes the buffer after setup.
246 bool point_cloud_configured = false;
247#ifdef USE_SENSOR
248 point_cloud_configured = point_cloud_configured || this->point_count_sensor_ != nullptr;
249#endif
250#ifdef USE_SWITCH
251 point_cloud_configured = point_cloud_configured || this->point_cloud_switch_ != nullptr;
252#endif
253 this->max_data_len_ = point_cloud_configured ? DEFAULT_MAX_DATA_LEN_POINT_CLOUD : DEFAULT_MAX_DATA_LEN;
254 // One allocation for the component lifetime; the parser reuses it for the header and every payload.
255 RAMAllocator<uint8_t> allocator;
256 this->data_buf_ = allocator.allocate(this->max_data_len_);
257 if (this->data_buf_ == nullptr) {
258 this->mark_failed(LOG_STR("Failed to allocate frame buffer"));
259 return;
260 }
261 if (this->wakeup_pin_ != nullptr) {
262 this->wakeup_pin_->setup();
263 this->wakeup_pin_->digital_write(true);
264 }
265
266 this->set_timeout(SETUP_DELAY_MS, [this]() {
267 bool want_target_stream = false;
268#ifdef USE_SENSOR
269 want_target_stream = want_target_stream || this->target_count_sensor_ != nullptr;
270 if (!want_target_stream) {
271 for (const auto &target : this->targets_) {
272 if (target.x != nullptr || target.y != nullptr || target.z != nullptr || target.dop_idx != nullptr ||
273 target.cluster_id != nullptr) {
274 want_target_stream = true;
275 break;
276 }
277 }
278 }
279#endif
280#ifdef USE_BINARY_SENSOR
281 want_target_stream = want_target_stream || this->presence_binary_sensor_ != nullptr;
282 if (!want_target_stream) {
283 for (auto *sensor : this->target_presence_) {
284 if (sensor != nullptr) {
285 want_target_stream = true;
286 break;
287 }
288 }
289 }
290#endif
291#ifdef USE_TEXT_SENSOR
292 // The work mode fallback reads presence off this stream, so it counts as a
293 // consumer of it here. This only feeds the automatic branch below: with a
294 // target_display switch configured that switch still decides, and the
295 // fallback weighs no presence at all while the stream is off.
296 want_target_stream = want_target_stream || this->work_mode_text_sensor_ != nullptr;
297#endif
298 bool target_display_controlled = false;
299#ifdef USE_SWITCH
300 if (this->target_display_switch_ != nullptr) {
301 target_display_controlled = true;
302 // Nothing reports this switch back, so its restored state is the only state
303 // there is. Restoring through the switch keeps its inversion in the path:
304 // the restored value is logical, and turn_on()/turn_off() are what turn it
305 // into the raw command, the published state and the stream flag.
306 const bool state = this->target_display_switch_->get_initial_state_with_restore_mode().value_or(true);
307 if (state) {
309 } else {
311 }
312 }
313#endif
314 if (!target_display_controlled) {
315 // No switch: the stream follows its consumers. With none, nothing is sent
316 // and the module's own default stands -- but the reports are gated out
317 // regardless, because there is nothing configured for them to feed.
318 this->target_display_enabled_ = want_target_stream;
319 if (want_target_stream) {
320 this->send_control_command_(CMD_TARGET_DISPLAY_ON);
321 }
322 }
323
324 bool point_cloud_controlled = false;
325#ifdef USE_SWITCH
326 if (this->point_cloud_switch_ != nullptr) {
327 point_cloud_controlled = true;
328 // The switch owns the stream, so it is also what applies the restored state:
329 // driving it rather than the module keeps the entity's inversion in the path.
330 const bool state = this->point_cloud_switch_->get_initial_state_with_restore_mode().value_or(false);
331 if (state) {
333 } else {
335 }
336 }
337#endif
338 if (!point_cloud_controlled) {
339 // No switch: the stream follows the sensor that reads it, which is also what
340 // the frame buffer above was sized for.
341 bool want_point_cloud = false;
342#ifdef USE_SENSOR
343 want_point_cloud = this->point_count_sensor_ != nullptr;
344#endif
345 this->send_control_command_(want_point_cloud ? CMD_POINT_CLOUD_ON : CMD_POINT_CLOUD_OFF);
346 this->point_cloud_enabled_ = want_point_cloud;
347 }
348
349#ifdef USE_SELECT
350 if (this->sensitivity_select_ != nullptr) {
351 this->send_control_command_(CMD_GET_SENSITIVITY);
352 }
353 if (this->trigger_speed_select_ != nullptr) {
354 this->send_control_command_(CMD_GET_TRIGGER);
355 }
356 if (this->installation_select_ != nullptr) {
357 this->send_control_command_(CMD_GET_INSTALLATION);
358 }
359#endif
360#ifdef USE_NUMBER
361 if (this->z_min_number_ != nullptr || this->z_max_number_ != nullptr) {
362 this->send_control_command_(CMD_GET_Z_RANGE);
363 }
364 if (this->low_power_sleep_number_ != nullptr) {
365 this->send_control_command_(CMD_GET_LOW_POWER_SLEEP);
366 }
367 if (this->hold_delay_number_ != nullptr) {
368 this->send_control_command_(CMD_GET_DELAY);
369 }
370#endif
371#ifdef USE_SWITCH
372 bool want_low_power = this->low_power_switch_ != nullptr;
373 if (want_low_power) {
374 // The module reports this one back, so the query below confirms what it took.
375 // Driving the switch applies its inversion; it also marks the restored value
376 // as reported, so the work mode fallback runs on that until the query lands.
377 const bool state = this->low_power_switch_->get_initial_state_with_restore_mode().value_or(false);
378 if (state) {
379 this->low_power_switch_->turn_on();
380 } else {
382 }
383 }
384#else
385 bool want_low_power = false;
386#endif
387#ifdef USE_TEXT_SENSOR
388 want_low_power = want_low_power || this->work_mode_text_sensor_ != nullptr;
389#endif
390 if (want_low_power) {
391 this->send_control_command_(CMD_GET_LOW_POWER);
392 }
393
394 bool want_area_report = false;
395#ifdef USE_SENSOR
396 for (const auto &area : this->interference_areas_) {
397 if (area.x_min != nullptr || area.x_max != nullptr || area.y_min != nullptr || area.y_max != nullptr ||
398 area.z_min != nullptr || area.z_max != nullptr) {
399 want_area_report = true;
400 break;
401 }
402 }
403 if (!want_area_report) {
404 for (const auto &area : this->detection_areas_) {
405 if (area.x_min != nullptr || area.x_max != nullptr || area.y_min != nullptr || area.y_max != nullptr ||
406 area.z_min != nullptr || area.z_max != nullptr) {
407 want_area_report = true;
408 break;
409 }
410 }
411 }
412#endif
413#ifdef USE_NUMBER
414 if (this->area_x_min_number_ != nullptr || this->area_x_max_number_ != nullptr ||
415 this->area_y_min_number_ != nullptr || this->area_y_max_number_ != nullptr ||
416 this->area_z_min_number_ != nullptr || this->area_z_max_number_ != nullptr) {
417 want_area_report = true;
418 }
419#endif
420 if (want_area_report) {
421 this->send_control_command_(CMD_GET_AREAS);
422 }
423
424 this->init_area_id_pref_();
425 this->init_version_pref_();
426
427#ifdef USE_TEXT_SENSOR
428 if (this->ota_version_text_sensor_ != nullptr) {
429 this->queue_command_(TYPE_QUERY_VERSION, VERSION_QUERY_DATA, sizeof(VERSION_QUERY_DATA));
430 }
431#endif
432 });
433}
434
436 ESP_LOGCONFIG(TAG,
437 "HLK-LD6002B:\n"
438 " Auto wake: %s\n"
439 " Max data length: %u",
440 this->auto_wake_ ? "true" : "false", static_cast<unsigned>(this->max_data_len_));
441 if (this->wakeup_pin_ != nullptr) {
442 LOG_PIN(" Wake-up Pin: ", this->wakeup_pin_);
443 ESP_LOGCONFIG(TAG, " Wake Pulse: %" PRIu32 "ms", this->wakeup_pulse_ms_);
444 }
445#ifdef USE_SENSOR
446 LOG_SENSOR(" ", "Target Count", this->target_count_sensor_);
447 LOG_SENSOR(" ", "Point Count", this->point_count_sensor_);
448 for (auto &target : this->targets_) {
449 LOG_SENSOR(" ", "Target X", target.x);
450 LOG_SENSOR(" ", "Target Y", target.y);
451 LOG_SENSOR(" ", "Target Z", target.z);
452 LOG_SENSOR(" ", "Target Doppler Index", target.dop_idx);
453 LOG_SENSOR(" ", "Target Cluster ID", target.cluster_id);
454 }
455 for (auto &area : this->interference_areas_) {
456 LOG_SENSOR(" ", "Interference Area X Min", area.x_min);
457 LOG_SENSOR(" ", "Interference Area X Max", area.x_max);
458 LOG_SENSOR(" ", "Interference Area Y Min", area.y_min);
459 LOG_SENSOR(" ", "Interference Area Y Max", area.y_max);
460 LOG_SENSOR(" ", "Interference Area Z Min", area.z_min);
461 LOG_SENSOR(" ", "Interference Area Z Max", area.z_max);
462 }
463 for (auto &area : this->detection_areas_) {
464 LOG_SENSOR(" ", "Detection Area X Min", area.x_min);
465 LOG_SENSOR(" ", "Detection Area X Max", area.x_max);
466 LOG_SENSOR(" ", "Detection Area Y Min", area.y_min);
467 LOG_SENSOR(" ", "Detection Area Y Max", area.y_max);
468 LOG_SENSOR(" ", "Detection Area Z Min", area.z_min);
469 LOG_SENSOR(" ", "Detection Area Z Max", area.z_max);
470 }
471#endif
472#ifdef USE_BINARY_SENSOR
473 LOG_BINARY_SENSOR(" ", "Presence", this->presence_binary_sensor_);
474 for (uint8_t i = 0; i < MAX_TARGETS; i++) {
475 LOG_BINARY_SENSOR(" ", "Target Presence", this->target_presence_[i]);
476 }
477 for (uint8_t i = 0; i < AREA_COUNT; i++) {
478 LOG_BINARY_SENSOR(" ", "Detection Area Presence", this->area_presence_[i]);
479 }
480#endif
481#ifdef USE_TEXT_SENSOR
482 LOG_TEXT_SENSOR(" ", "Work Mode", this->work_mode_text_sensor_);
483 LOG_TEXT_SENSOR(" ", "OTA Version", this->ota_version_text_sensor_);
484#endif
485#ifdef USE_NUMBER
486 LOG_NUMBER(" ", "Hold Delay", this->hold_delay_number_);
487 LOG_NUMBER(" ", "Z Min", this->z_min_number_);
488 LOG_NUMBER(" ", "Z Max", this->z_max_number_);
489 LOG_NUMBER(" ", "Low Power Sleep", this->low_power_sleep_number_);
490 LOG_NUMBER(" ", "Area X Min", this->area_x_min_number_);
491 LOG_NUMBER(" ", "Area X Max", this->area_x_max_number_);
492 LOG_NUMBER(" ", "Area Y Min", this->area_y_min_number_);
493 LOG_NUMBER(" ", "Area Y Max", this->area_y_max_number_);
494 LOG_NUMBER(" ", "Area Z Min", this->area_z_min_number_);
495 LOG_NUMBER(" ", "Area Z Max", this->area_z_max_number_);
496#endif
497#ifdef USE_SWITCH
498 LOG_SWITCH(" ", "Low Power", this->low_power_switch_);
499 LOG_SWITCH(" ", "Point Cloud", this->point_cloud_switch_);
500 LOG_SWITCH(" ", "Target Display", this->target_display_switch_);
501#endif
502#ifdef USE_SELECT
503 LOG_SELECT(" ", "Sensitivity", this->sensitivity_select_);
504 LOG_SELECT(" ", "Trigger Speed", this->trigger_speed_select_);
505 LOG_SELECT(" ", "Installation Mode", this->installation_select_);
506 LOG_SELECT(" ", "Area ID", this->area_id_select_);
507#endif
508}
509
511 while (this->available()) {
512 uint8_t byte = this->read();
513 this->parse_byte_(byte);
514 }
516}
517
520 this->header_pos_ = 0;
521 this->header_xor_ = 0;
522 this->data_len_ = 0;
523 this->data_pos_ = 0;
524 this->data_xor_ = 0;
525 this->discard_remaining_ = 0;
526 this->frame_oversize_ = false;
527}
528
530 switch (this->parse_state_) {
532 // discard_remaining_ is unsigned: an unguarded decrement at zero would swallow 4 GB of stream.
533 if (this->discard_remaining_ > 0) {
534 this->discard_remaining_--;
535 }
536 if (this->discard_remaining_ == 0) {
537 this->reset_parser_();
538 }
539 return;
540 case ParseState::SOF:
541 if (byte != TF_SOF)
542 return;
543 this->header_pos_ = 0;
544 this->header_xor_ = 0;
545 this->header_xor_ ^= byte;
547 return;
549 if (this->header_pos_ < 6) {
550 this->data_buf_[this->header_pos_] = byte;
551 this->header_xor_ ^= byte;
552 this->header_pos_++;
553 if (this->header_pos_ == 6) {
554 this->frame_id_ = read_u16_be(this->data_buf_);
555 this->data_len_ = read_u16_be(this->data_buf_ + 2);
556 this->frame_type_ = read_u16_be(this->data_buf_ + 4);
557 // The length is only trustworthy once the header checksum has been verified, so just
558 // remember that the frame is oversized and let the HCK state act on it.
559 this->frame_oversize_ = this->data_len_ > this->max_data_len_;
561 }
562 }
563 return;
564 case ParseState::HCK: {
565 uint8_t expected = static_cast<uint8_t>(~this->header_xor_);
566 if (byte != expected) {
567 ESP_LOGV(TAG, "Header checksum mismatch");
568 this->reset_parser_();
569 return;
570 }
571 if (this->frame_oversize_) {
572 ESP_LOGW(TAG, "Frame too large: %u", this->data_len_);
573 // The header is verified, so the length can be trusted: skip the payload and its checksum.
574 this->discard_remaining_ = static_cast<uint32_t>(this->data_len_) + 1;
576 return;
577 }
578 if (this->data_len_ == 0) {
579 this->handle_frame_(this->frame_type_, nullptr, 0);
580 this->reset_parser_();
581 } else {
582 this->data_pos_ = 0;
583 this->data_xor_ = 0;
585 }
586 return;
587 }
588 case ParseState::DATA:
589 this->data_buf_[this->data_pos_++] = byte;
590 this->data_xor_ ^= byte;
591 if (this->data_pos_ >= this->data_len_) {
593 }
594 return;
595 case ParseState::DCK: {
596 uint8_t expected = static_cast<uint8_t>(~this->data_xor_);
597 if (byte == expected) {
598 this->handle_frame_(this->frame_type_, this->data_buf_, this->data_len_);
599 } else {
600 ESP_LOGV(TAG, "Data checksum mismatch");
601 }
602 this->reset_parser_();
603 return;
604 }
605 }
606}
607
608void LD6002BComponent::handle_frame_(uint16_t type, const uint8_t *data, uint16_t len) {
609 this->last_traffic_ms_ = millis();
610 if (this->stale_ack_count_ > 0 && millis() - this->stale_ack_ms_ > STALE_ACK_MAX_AGE_MS) {
611 this->stale_ack_count_ = 0;
612 }
613 // ACKs carry no id and arrive in send order: debt from earlier attempts is paid before the active command.
614 if (len == 0 && this->stale_ack_count_ > 0 && this->stale_ack_type_ == type) {
615 this->stale_ack_count_--;
616 ESP_LOGV(TAG, "Ignoring ACK for command 0x%04X from an earlier attempt (module frame 0x%04X)", type,
617 this->frame_id_);
618 return;
619 }
620 if (len == 0 && this->command_active_ && this->command_sent_ && type == this->active_command_.type) {
621 ESP_LOGV(TAG, "ACK for command 0x%04X (module frame 0x%04X)", type, this->frame_id_);
622 const bool refresh_areas = (type == TYPE_SET_AREA) && this->area_write_in_flight_;
623 // This settles one expected reply; the rest stay owed and become the debt for the next command.
624 this->send_generation_++;
625 this->stale_ack_type_ = type;
626 this->stale_ack_count_ = this->acks_expected_ > 0 ? static_cast<uint8_t>(this->acks_expected_ - 1) : 0;
627 this->stale_ack_ms_ = millis();
628 this->command_active_ = false;
629 this->command_sent_ = false;
630 this->last_send_ms_ = 0;
632 if (refresh_areas) {
633 this->area_write_in_flight_ = false;
634 this->set_timeout(AREA_REFRESH_TIMEOUT, 50, [this]() { this->send_control_command_(CMD_GET_AREAS); });
635 }
636 return;
637 }
638
639#ifdef ESPHOME_LOG_HAS_VERBOSE
640 const uint32_t active_control_command =
641 (this->command_active_ && this->active_command_.type == TYPE_CONTROL && this->active_command_.len >= 4)
642 ? read_u32_le(this->active_command_.data.data())
643 : 0;
644 if (active_control_command != 0 && is_expected_control_report(active_control_command, type)) {
645 ESP_LOGV(TAG, "Received %s (0x%04X) while waiting for %s (0x%02" PRIX32 ") ACK", frame_type_name(type), type,
646 control_command_name(active_control_command), active_control_command);
647 }
648#endif
649
650 switch (type) {
651 case TYPE_REPORT_TARGET:
652 this->handle_target_report_(data, len);
653 break;
654 case TYPE_REPORT_POINT_CLOUD:
655 this->handle_point_cloud_(data, len);
656 break;
657 case TYPE_REPORT_AREA_PRESENCE:
658 this->handle_area_presence_(data, len);
659 break;
660 case TYPE_REPORT_INTERFERENCE_AREAS:
661 this->handle_area_report_(true, data, len);
662 break;
663 case TYPE_REPORT_DETECTION_AREAS:
664 this->handle_area_report_(false, data, len);
665 break;
666 case TYPE_REPORT_DELAY:
667 this->handle_delay_report_(data, len);
668 break;
669 case TYPE_REPORT_SENSITIVITY:
670 this->handle_sensitivity_report_(data, len);
671 break;
672 case TYPE_REPORT_TRIGGER:
674 break;
675 case TYPE_REPORT_Z_RANGE:
676 this->handle_z_range_report_(data, len);
677 break;
678 case TYPE_REPORT_INSTALLATION:
679 this->handle_installation_report_(data, len);
680 break;
681 case TYPE_REPORT_LOW_POWER:
682 this->handle_low_power_report_(data, len);
683 break;
684 case TYPE_REPORT_LOW_POWER_SLEEP:
686 break;
687 case TYPE_REPORT_WORK_MODE:
688 this->handle_work_mode_report_(data, len);
689 break;
690 case TYPE_QUERY_VERSION:
691 this->handle_version_report_(data, len);
692 break;
693 default:
694 break;
695 }
696}
697
698void LD6002BComponent::handle_target_report_(const uint8_t *data, uint16_t len) {
699 // The module stops streaming when it acts on the command, not when the command
700 // is queued, so trailing frames after an off must not repopulate what
701 // set_switch_state just cleared.
702 if (!this->target_display_enabled_) {
703 return;
704 }
705 if (len < 4)
706 return;
707
708 uint32_t target_num = read_u32_le(data);
709 uint16_t available = (len - 4) / TARGET_DATA_LEN;
710 // Un-narrowed: a report of e.g. 256 targets must not truncate to 0 and read as "absent".
711 const uint32_t reported = std::min<uint32_t>(target_num, available);
712 uint8_t count = static_cast<uint8_t>(std::min<uint32_t>(reported, MAX_TARGETS));
713
714 // The module re-sorts its array by cluster id, so slots key on the id to track the person.
715 std::array<int32_t, MAX_TARGETS> wire_cluster{};
716 std::array<bool, MAX_TARGETS> wire_placed{};
717 std::array<bool, MAX_TARGETS> slot_seen{};
718 std::array<uint8_t, MAX_TARGETS> slot_wire{};
719 for (uint8_t i = 0; i < count; i++) {
720 uint16_t cluster_offset = 4 + (i * TARGET_DATA_LEN) + 16;
721 wire_cluster[i] = static_cast<int32_t>(read_u32_le(data + cluster_offset));
722 }
723 for (uint8_t i = 0; i < count; i++) {
724 for (uint8_t s = 0; s < MAX_TARGETS; s++) {
725 if (this->slot_occupied_[s] && !slot_seen[s] && this->slot_cluster_[s] == wire_cluster[i]) {
726 slot_seen[s] = true;
727 wire_placed[i] = true;
728 slot_wire[s] = i;
729 break;
730 }
731 }
732 }
733 for (uint8_t s = 0; s < MAX_TARGETS; s++) {
734 if (!slot_seen[s]) {
735 this->slot_occupied_[s] = false;
736 }
737 }
738 for (uint8_t i = 0; i < count; i++) {
739 if (wire_placed[i]) {
740 continue;
741 }
742 for (uint8_t s = 0; s < MAX_TARGETS; s++) {
743 if (!this->slot_occupied_[s]) {
744 this->slot_occupied_[s] = true;
745 this->slot_cluster_[s] = wire_cluster[i];
746 slot_wire[s] = i;
747 break;
748 }
749 }
750 }
751
752#ifdef USE_SENSOR
753 if (this->target_count_sensor_ != nullptr) {
754 if (reported != this->last_target_count_) {
755 this->target_count_sensor_->publish_state(reported);
756 this->last_target_count_ = reported;
757 }
758 }
759#endif
760
761 this->target_presence_any_ = (reported > 0);
762#ifdef USE_BINARY_SENSOR
763 bool presence = this->target_presence_any_ || this->area_presence_any_;
764 if (this->presence_binary_sensor_ != nullptr) {
765 this->presence_binary_sensor_->publish_state(presence);
766 }
767#endif
769
770 for (uint8_t i = 0; i < MAX_TARGETS; i++) {
771 bool has_target = this->slot_occupied_[i];
772 if (has_target) {
773#ifdef USE_SENSOR
774 uint16_t offset = 4 + (slot_wire[i] * TARGET_DATA_LEN);
775 float x = read_f32_le(data + offset + 0);
776 float y = read_f32_le(data + offset + 4);
777 float z = read_f32_le(data + offset + 8);
778 int32_t dop_idx = read_int32_le(data + offset + 12);
779 int32_t cluster_id = this->slot_cluster_[i];
780 TargetSensors &target = this->targets_[i];
781 if (target.x != nullptr) {
782 target.x->publish_state(x);
783 }
784 if (target.y != nullptr) {
785 target.y->publish_state(y);
786 }
787 if (target.z != nullptr) {
788 target.z->publish_state(z);
789 }
790 if (target.dop_idx != nullptr) {
791 target.dop_idx->publish_state(static_cast<float>(dop_idx));
792 }
793 if (target.cluster_id != nullptr) {
794 if (!this->last_cluster_id_valid_[i] || cluster_id != this->last_cluster_id_[i]) {
795 target.cluster_id->publish_state(static_cast<float>(cluster_id));
796 this->last_cluster_id_[i] = cluster_id;
797 this->last_cluster_id_valid_[i] = true;
798 }
799 }
800#endif
801 } else {
802#ifdef USE_SENSOR
803 this->clear_target_slot_(i);
804#endif
805 }
806#ifdef USE_BINARY_SENSOR
807 if (this->target_presence_[i] != nullptr) {
808 // publish_state() already skips unchanged states, no manual de-dup needed.
809 this->target_presence_[i]->publish_state(has_target);
810 }
811#endif
812#ifdef USE_SENSOR
813 this->last_target_presence_[i] = has_target;
814#endif
815 }
816}
817
818void LD6002BComponent::handle_point_cloud_(const uint8_t *data, uint16_t len) {
819 // Same window as the target stream: a frame already in flight must not put the
820 // count back after the switch cleared it.
821 if (!this->point_cloud_enabled_) {
822 return;
823 }
824 if (len < 4)
825 return;
826
827#ifdef USE_SENSOR
828 uint32_t point_num = read_u32_le(data);
829 if (this->point_count_sensor_ != nullptr) {
830 if (point_num != this->last_point_count_) {
831 this->point_count_sensor_->publish_state(point_num);
832 this->last_point_count_ = point_num;
833 }
834 }
835#endif
836}
837
838// 0x0A0A carries one uint32 per detection area -- the protocol names the four
839// fields detection_state_area0..3 -- so this covers area ids 4..7 only. The
840// interference areas have no presence report: a target inside one is what they
841// exist to suppress.
842void LD6002BComponent::handle_area_presence_(const uint8_t *data, uint16_t len) {
843 const uint16_t needed = AREA_COUNT * AREA_PRESENCE_ENTRY_LEN;
844 if (len < needed)
845 return;
846
847 this->area_presence_any_ = false;
848 for (uint8_t i = 0; i < AREA_COUNT; i++) {
849 uint32_t state = read_u32_le(data + (i * AREA_PRESENCE_ENTRY_LEN));
850 bool present = state != 0;
851 this->area_presence_any_ = this->area_presence_any_ || present;
852#ifdef USE_BINARY_SENSOR
853 if (this->area_presence_[i] != nullptr) {
854 this->area_presence_[i]->publish_state(present);
855 }
856#endif
857 }
858
859#ifdef USE_BINARY_SENSOR
860 bool presence = this->target_presence_any_ || this->area_presence_any_;
861 if (this->presence_binary_sensor_ != nullptr) {
862 this->presence_binary_sensor_->publish_state(presence);
863 }
864#endif
866}
867
868void LD6002BComponent::handle_area_report_(bool interference, const uint8_t *data, uint16_t len) {
869 uint16_t needed = AREA_COUNT * AREA_DATA_LEN;
870 if (len < needed)
871 return;
872
873 for (uint8_t i = 0; i < AREA_COUNT; i++) {
874 uint16_t offset = i * AREA_DATA_LEN;
875 float x_min = read_f32_le(data + offset + 0);
876 float x_max = read_f32_le(data + offset + 4);
877 float y_min = read_f32_le(data + offset + 8);
878 float y_max = read_f32_le(data + offset + 12);
879 float z_min = read_f32_le(data + offset + 16);
880 float z_max = read_f32_le(data + offset + 20);
881
882#ifdef USE_SENSOR
883 AreaSensors &area = interference ? this->interference_areas_[i] : this->detection_areas_[i];
884 if (area.x_min != nullptr)
885 area.x_min->publish_state(x_min);
886 if (area.x_max != nullptr)
887 area.x_max->publish_state(x_max);
888 if (area.y_min != nullptr)
889 area.y_min->publish_state(y_min);
890 if (area.y_max != nullptr)
891 area.y_max->publish_state(y_max);
892 if (area.z_min != nullptr)
893 area.z_min->publish_state(z_min);
894 if (area.z_max != nullptr)
895 area.z_max->publish_state(z_max);
896#endif
897
898 AreaConfig &store = interference ? this->interference_area_values_[i] : this->detection_area_values_[i];
899 store.x_min = x_min;
900 store.x_max = x_max;
901 store.y_min = y_min;
902 store.y_max = y_max;
903 store.z_min = z_min;
904 store.z_max = z_max;
905
906 uint8_t selected_id = this->area_id_set_ ? this->area_id_ : AREA_ID_DEFAULT;
907 bool selected_interference = selected_id < AREA_COUNT;
908 uint8_t selected_index = selected_interference ? selected_id : static_cast<uint8_t>(selected_id - AREA_COUNT);
909 if (selected_interference == interference && selected_index == i) {
910 this->update_area_numbers_(store);
911 }
912 }
913 this->try_apply_pending_area_(interference);
914}
915
916void LD6002BComponent::handle_delay_report_(const uint8_t *data, uint16_t len) {
917 if (len < 4)
918 return;
919#ifdef USE_NUMBER
920 uint32_t delay = read_u32_le(data);
922#endif
923}
924
925void LD6002BComponent::handle_sensitivity_report_(const uint8_t *data, uint16_t len) {
926 if (len < 1)
927 return;
928#ifdef USE_SELECT
929 if (this->sensitivity_select_ == nullptr)
930 return;
931 uint8_t value = data[0];
932 if (value <= 2) {
934 }
935#endif
936}
937
938void LD6002BComponent::handle_trigger_speed_report_(const uint8_t *data, uint16_t len) {
939 if (len < 1)
940 return;
941#ifdef USE_SELECT
942 if (this->trigger_speed_select_ == nullptr)
943 return;
944 uint8_t value = data[0];
945 if (value <= 2) {
947 }
948#endif
949}
950
951void LD6002BComponent::handle_z_range_report_(const uint8_t *data, uint16_t len) {
952 if (len < 8)
953 return;
954 float z_min = read_f32_le(data);
955 float z_max = read_f32_le(data + 4);
956 this->z_min_ = z_min;
957 this->z_max_ = z_max;
958#ifdef USE_NUMBER
959 this->publish_number_clamped_(this->z_min_number_, z_min);
960 this->publish_number_clamped_(this->z_max_number_, z_max);
961#endif
962}
963
964void LD6002BComponent::handle_installation_report_(const uint8_t *data, uint16_t len) {
965 if (len < 1)
966 return;
967#ifdef USE_SELECT
968 if (this->installation_select_ == nullptr)
969 return;
970 uint8_t value = data[0];
971 if (value <= 1) {
973 }
974#endif
975}
976
977void LD6002BComponent::handle_low_power_report_(const uint8_t *data, uint16_t len) {
978 if (len < 1)
979 return;
980 bool enabled = data[0] != 0;
981 this->low_power_enabled_ = enabled;
982 this->low_power_reported_ = true;
983#ifdef USE_SWITCH
984 if (this->low_power_switch_ != nullptr) {
985 this->low_power_switch_->publish_state(enabled);
986 }
987#endif
989}
990
991void LD6002BComponent::handle_low_power_sleep_report_(const uint8_t *data, uint16_t len) {
992 if (len < 4)
993 return;
994#ifdef USE_NUMBER
995 uint32_t sleep_ms = read_u32_le(data);
997#endif
998}
999
1000void LD6002BComponent::handle_work_mode_report_(const uint8_t *data, uint16_t len) {
1001 if (len < 1)
1002 return;
1003 // Zero is the unattended half of this transition. Read outside the text sensor's
1004 // ifdef because the area sensors do not need one configured to have gone stale.
1005 const bool low_power = (data[0] == 0);
1006#ifdef USE_TEXT_SENSOR
1007 if (this->work_mode_text_sensor_ != nullptr) {
1008 this->work_mode_reported_ = true;
1009 this->publish_work_mode_(low_power);
1010 }
1011#endif
1012 // Protocol V1.2 section 2.1.17: this message is sent only on the transition
1013 // between the unattended low-power mode and normal operation, so a zero is the
1014 // module stating that nobody is in any area. Not while a target is still being
1015 // tracked, though: the reset_unattended command is undocumented on whether it
1016 // forces this report, and where two statements from the module disagree the live
1017 // one wins.
1018 if (low_power && !this->target_presence_any_) {
1019 this->clear_area_presence_();
1020 }
1021}
1022
1024#ifdef USE_TEXT_SENSOR
1025 if (this->work_mode_text_sensor_ == nullptr || this->work_mode_reported_) {
1026 return;
1027 }
1028 if (!this->low_power_reported_) {
1029 return;
1030 }
1031 // Target presence is only meaningful while the stream that maintains it runs.
1032 // Area presence keeps its own report, so it still counts with the target stream
1033 // off and low power alone decides only when neither half has anything to say.
1034 const bool presence = (this->target_display_enabled_ && this->target_presence_any_) || this->area_presence_any_;
1035 this->publish_work_mode_(this->low_power_enabled_ && !presence);
1036#endif
1037}
1038
1040#ifdef USE_TEXT_SENSOR
1041 if (this->work_mode_text_sensor_ == nullptr) {
1042 return;
1043 }
1044 if (this->last_work_mode_valid_ && this->last_work_mode_low_power_ == low_power) {
1045 return;
1046 }
1047 this->work_mode_text_sensor_->publish_state(low_power ? "low_power" : "normal");
1048 this->last_work_mode_valid_ = true;
1049 this->last_work_mode_low_power_ = low_power;
1050#endif
1051}
1052
1053#ifdef USE_NUMBER
1055 if (number == nullptr)
1056 return;
1057 if (std::isnan(value)) {
1058 // NAN is this component's "the module has not told us yet". Publishing it on an
1059 // entity that has never had a state would report a nan where unknown is the
1060 // truth; on one that already shows a value it is the only way to say that value
1061 // no longer describes the selected area.
1062 if (number->has_state()) {
1063 number->publish_state(value);
1064 }
1065 return;
1066 }
1067 const float min_value = number->traits.get_min_value();
1068 const float max_value = number->traits.get_max_value();
1069 // Outside the declared range the user cannot write the value back, so publish
1070 // what they can reach and say what the module actually sent.
1071 if (value < min_value || value > max_value) {
1072 ESP_LOGW(TAG, "'%s': module reported %.1f, clamped to %.1f..%.1f", number->get_name().c_str(), value, min_value,
1073 max_value);
1074 value = std::clamp(value, min_value, max_value);
1075 }
1076 number->publish_state(value);
1077}
1078#endif
1079
1080void LD6002BComponent::handle_version_report_(const uint8_t *data, uint16_t len) {
1081 if (len < 4)
1082 return;
1083#ifdef USE_TEXT_SENSOR
1084 if (this->ota_version_text_sensor_ == nullptr)
1085 return;
1086 uint8_t project = data[0];
1087 uint8_t major = data[1];
1088 uint8_t minor = data[2];
1089 uint8_t patch = data[3];
1090 char buf[32];
1091 if (project == 0) {
1092 std::snprintf(buf, sizeof(buf), "%u.%u.%u", major, minor, patch);
1093 } else {
1094 std::snprintf(buf, sizeof(buf), "p%u %u.%u.%u", project, major, minor, patch);
1095 }
1097 this->save_version_pref_(buf);
1098#endif
1099}
1100
1101bool LD6002BComponent::queue_command_(uint16_t type, const uint8_t *data, uint8_t len) {
1102 if (len > CMD_MAX_DATA_LEN) {
1103 ESP_LOGW(TAG, "Command data too large: %u", len);
1104 return false;
1105 }
1106 if (this->cmd_count_ >= CMD_QUEUE_SIZE) {
1107 ESP_LOGW(TAG, "Command queue full, dropping command 0x%04X", type);
1108 return false;
1109 }
1110
1111 PendingCommand &cmd = this->cmd_queue_[this->cmd_tail_];
1112 cmd.type = type;
1113 cmd.len = len;
1114 if (len > 0 && data != nullptr) {
1115 std::memcpy(cmd.data.data(), data, len);
1116 }
1117
1118 this->cmd_tail_ = (this->cmd_tail_ + 1) % CMD_QUEUE_SIZE;
1119 this->cmd_count_++;
1120 this->process_command_queue_();
1121 return true;
1122}
1123
1125 uint32_t now = millis();
1126 if (this->command_active_) {
1127 // A sleeping module consumes the opening attempt as its wake-up instead of answering it.
1128 const uint32_t ack_timeout = this->attempts_sent_ <= 1 ? CMD_FIRST_ACK_TIMEOUT_MS : CMD_ACK_TIMEOUT_MS;
1129 if (this->command_sent_ && now - this->last_send_ms_ >= ack_timeout) {
1130 const uint32_t active_control_command =
1131 (this->active_command_.type == TYPE_CONTROL && this->active_command_.len >= 4)
1132 ? read_u32_le(this->active_command_.data.data())
1133 : 0;
1134 if (this->retries_left_ > 0) {
1135#ifdef ESPHOME_LOG_HAS_VERBOSE
1136 if (active_control_command != 0) {
1137 ESP_LOGV(TAG, "Retrying %s (0x%02" PRIX32 "), %u attempt(s) remaining",
1138 control_command_name(active_control_command), active_control_command, this->retries_left_);
1139 } else {
1140 // Writes without a control subcommand (hold delay, z-range) had no retry trace at all.
1141 ESP_LOGV(TAG, "Retrying command 0x%04X, %u attempt(s) remaining", this->active_command_.type,
1142 this->retries_left_);
1143 }
1144#endif
1145 this->command_sent_ = false;
1146 this->last_send_ms_ = 0;
1147 this->send_command_(this->active_command_.type, this->active_command_.data.data(), this->active_command_.len);
1148 this->retries_left_--;
1149 } else {
1150 if (active_control_command != 0) {
1151 ESP_LOGW(TAG, "Command 0x%04X subcommand 0x%02" PRIX32 " timed out", this->active_command_.type,
1152 active_control_command);
1153 } else {
1154 ESP_LOGW(TAG, "Command 0x%04X timed out", this->active_command_.type);
1155 }
1156 if (this->active_command_.type == TYPE_SET_AREA) {
1157 this->area_write_in_flight_ = false;
1158 }
1159 // The deferred apply is waiting on the report this command would have
1160 // brought back, and nothing else re-arms it. Dropping it here is the
1161 // difference between one apply lost to a timeout and one that rides in on
1162 // an unrelated area report later, writing bounds the user has moved on from.
1163 if (active_control_command == CMD_GET_AREAS && this->deferred_apply_pending_) {
1164 this->deferred_apply_pending_ = false;
1166 ESP_LOGW(TAG, "Area read timed out, dropping deferred area apply");
1167 }
1168 // A reply may still be in flight for the attempt we just gave up on, so carry one over as
1169 // debt rather than clearing the ledger, or that late ACK would retire the successor. Only
1170 // one: reaching this point means nothing was answered at all, so the older attempts are
1171 // speculative, and carrying them would swallow the successor's own replies.
1172 const uint16_t owed = (this->stale_ack_type_ == this->active_command_.type ? this->stale_ack_count_ : 0) +
1173 (this->acks_expected_ > 0 ? 1 : 0);
1174 this->stale_ack_type_ = this->active_command_.type;
1175 this->stale_ack_count_ = static_cast<uint8_t>(std::min<uint16_t>(owed, 255));
1176 this->stale_ack_ms_ = now;
1177 this->send_generation_++;
1178 this->command_active_ = false;
1179 this->command_sent_ = false;
1180 this->last_send_ms_ = 0;
1181 }
1182 }
1183 return;
1184 }
1185
1186 if (this->cmd_count_ == 0)
1187 return;
1188
1189 this->active_command_ = this->cmd_queue_[this->cmd_head_];
1190 this->cmd_head_ = (this->cmd_head_ + 1) % CMD_QUEUE_SIZE;
1191 this->cmd_count_--;
1192
1193 this->send_generation_++;
1195 this->command_active_ = true;
1196 this->command_sent_ = false;
1197 this->last_send_ms_ = 0;
1198 this->attempts_sent_ = 0;
1199 this->acks_expected_ = 0;
1200 if (this->stale_ack_type_ != this->active_command_.type) {
1201 this->stale_ack_count_ = 0;
1202 }
1203 this->send_command_(this->active_command_.type, this->active_command_.data.data(), this->active_command_.len);
1204}
1205
1206void LD6002BComponent::send_command_(uint16_t type, const uint8_t *data, uint8_t len) {
1207 this->send_command_internal_(type, data, len, true);
1208}
1209
1210void LD6002BComponent::send_command_internal_(uint16_t type, const uint8_t *data, uint8_t len, bool track) {
1211 if (len > CMD_MAX_DATA_LEN) {
1212 ESP_LOGW(TAG, "Command data too large: %u", len);
1213 if (track) {
1214 // Release the slot: an unwritten command is never acked and never times out.
1215 this->command_active_ = false;
1216 this->command_sent_ = false;
1217 this->last_send_ms_ = 0;
1218 }
1219 return;
1220 }
1221
1222 // Anonymous timeouts never replace each other; with a pulse already pending the module is waking anyway.
1223 if (this->auto_wake_ && this->wakeup_pin_ != nullptr && !this->wake_pulse_pending_) {
1224 // Snapshot the payload: the deferred write must not depend on state a completing command changes.
1225 if (len > 0 && data != nullptr) {
1226 std::memcpy(this->wake_scratch_.data(), data, len);
1227 }
1228 // A button pulse must not raise the pin in the middle of this one.
1230 this->wake_pulse_pending_ = true;
1231 this->wakeup_pin_->digital_write(false);
1232 const uint8_t generation = this->send_generation_;
1233 this->set_timeout(this->wakeup_pulse_ms_, [this, type, len, track, generation]() {
1234 this->wakeup_pin_->digital_write(true);
1235 this->wake_pulse_pending_ = false;
1236 // Anonymous timeouts are never cancelled, so a tracked pulse whose command has since been
1237 // retired must not transmit: the frame would land after its successor and be booked to it.
1238 if (track && generation != this->send_generation_) {
1239 return;
1240 }
1241 this->write_frame_(type, (len > 0) ? this->wake_scratch_.data() : nullptr, len, track);
1242 });
1243 return;
1244 }
1245
1246 this->write_frame_(type, data, len, track);
1247}
1248
1249void LD6002BComponent::write_frame_(uint16_t type, const uint8_t *data, uint8_t len, bool track) {
1250 uint16_t frame_id = this->next_frame_id_++ & 0x7FFF;
1251 frame_id |= 0x8000;
1252
1253 uint8_t header_xor = 0;
1254 auto write_header = [&](uint8_t b) {
1255 this->write_byte(b);
1256 header_xor ^= b;
1257 };
1258
1259 write_header(TF_SOF);
1260 write_header((frame_id >> 8) & 0xFF);
1261 write_header(frame_id & 0xFF);
1262 write_header((len >> 8) & 0xFF);
1263 write_header(len & 0xFF);
1264 write_header((type >> 8) & 0xFF);
1265 write_header(type & 0xFF);
1266
1267 this->write_byte(static_cast<uint8_t>(~header_xor));
1268
1269 if (len > 0 && data != nullptr) {
1270 uint8_t data_xor = 0;
1271 for (uint8_t i = 0; i < len; i++) {
1272 this->write_byte(data[i]);
1273 data_xor ^= data[i];
1274 }
1275 this->write_byte(static_cast<uint8_t>(~data_xor));
1276 }
1277 const uint32_t now = millis();
1278 if (track) {
1279 // A frame sent to a module that has had time to fall asleep is its wake-up, and goes unanswered.
1280 if (this->last_traffic_ms_ != 0 && now - this->last_traffic_ms_ < MODULE_AWAKE_MS) {
1281 this->acks_expected_++;
1282 }
1283 this->last_send_ms_ = now;
1284 this->command_sent_ = true;
1285 this->attempts_sent_++;
1286 }
1287 this->last_traffic_ms_ = now;
1288}
1289
1291 uint8_t data[4];
1292 write_u32_le(data, command);
1293 return this->queue_command_(TYPE_CONTROL, data, sizeof(data));
1294}
1295
1297 // One frame carries both bounds, so half a range cannot be written.
1298 if (std::isnan(this->z_min_) || std::isnan(this->z_max_)) {
1299 ESP_LOGW(TAG, "Z range not written, other bound unknown");
1300 return;
1301 }
1302 // Both bounds are known and crossed; the frame has no way to say that.
1303 if (this->z_min_ > this->z_max_) {
1304 ESP_LOGW(TAG, "Z range not written, min above max");
1305 return;
1306 }
1307 uint8_t data[8];
1308 write_f32_le(data, this->z_min_);
1309 write_f32_le(data + 4, this->z_max_);
1310 this->queue_command_(TYPE_SET_Z_RANGE, data, sizeof(data));
1311}
1312
1314 if (!this->area_id_set_) {
1315 ESP_LOGW(TAG, "Area ID not selected; ignoring apply");
1316 return;
1317 }
1318 if (this->area_id_ >= AREA_ID_COUNT) {
1319 ESP_LOGW(TAG, "Invalid area id: %u", this->area_id_);
1320 return;
1321 }
1322
1323 const bool interference = this->area_id_ < AREA_COUNT;
1324 const uint8_t index = interference ? this->area_id_ : static_cast<uint8_t>(this->area_id_ - AREA_COUNT);
1325 AreaConfig desired = interference ? this->interference_area_values_[index] : this->detection_area_values_[index];
1326 if (!std::isnan(this->area_x_min_))
1327 desired.x_min = this->area_x_min_;
1328 if (!std::isnan(this->area_x_max_))
1329 desired.x_max = this->area_x_max_;
1330 if (!std::isnan(this->area_y_min_))
1331 desired.y_min = this->area_y_min_;
1332 if (!std::isnan(this->area_y_max_))
1333 desired.y_max = this->area_y_max_;
1334 if (!std::isnan(this->area_z_min_))
1335 desired.z_min = this->area_z_min_;
1336 if (!std::isnan(this->area_z_max_))
1337 desired.z_max = this->area_z_max_;
1338
1339 if (std::isnan(desired.x_min) || std::isnan(desired.x_max) || std::isnan(desired.y_min) ||
1340 std::isnan(desired.y_max) || std::isnan(desired.z_min) || std::isnan(desired.z_max)) {
1341 // Ask first: a read that never reached the queue would leave a deferral waiting
1342 // on a report nobody requested, with the user's values already retired for it.
1343 if (!this->send_control_command_(CMD_GET_AREAS)) {
1344 ESP_LOGW(TAG, "Area read not queued; area config left unapplied");
1345 return;
1346 }
1347 this->deferred_apply_pending_ = true;
1348 this->pending_area_id_ = this->area_id_;
1349 // The ledger, not the mirror: the mirror also carries whatever the module last
1350 // reported for the axes the user never touched, and staging those would hand them
1351 // back later wearing the user's badge -- a module value the next report is then
1352 // kept away from. Staging only what was actually typed is also what makes the
1353 // replay's overlay right: the untouched axes come from the fresh report. An
1354 // empty ledger is a meaning rather than a gap, then: an apply with nothing
1355 // staged rewrites the area exactly as the report just described it, which is
1356 // what a direct apply with nothing staged already does.
1357 this->pending_area_updates_ = this->area_edits_;
1358 // Staged above, so they are the deferred apply's values now rather than an
1359 // unsent edit. Anything typed from here belongs to whatever the user does
1360 // next, which may well be a different area.
1361 this->area_edits_ = AreaConfig{};
1362 ESP_LOGI(TAG, "Area config incomplete; requesting current areas before applying");
1363 return;
1364 }
1365 // Only a write the module will actually see retires them.
1366 if (this->queue_area_config_(this->area_id_, desired)) {
1367 this->area_edits_ = AreaConfig{};
1368 }
1369}
1370
1372 // A command's own pulse raises the pin and writes after it, so ride along instead of
1373 // claiming the flag: claiming it would send that command down the immediate-write path
1374 // with the pin still low.
1375 if (this->wakeup_pin_ == nullptr || this->wake_pulse_pending_)
1376 return;
1377 this->wakeup_pin_->digital_write(false);
1378 this->set_timeout(WAKE_BUTTON_TIMEOUT, this->wakeup_pulse_ms_, [this]() { this->wakeup_pin_->digital_write(true); });
1379}
1380
1382 switch (type) {
1384 uint32_t delay = static_cast<uint32_t>(value);
1385 uint8_t data[4];
1386 write_u32_le(data, delay);
1387 this->queue_command_(TYPE_SET_HOLD_DELAY, data, sizeof(data));
1388 break;
1389 }
1390 case NumberType::Z_MIN:
1391 this->z_min_ = value;
1392 this->send_z_range_();
1393 break;
1394 case NumberType::Z_MAX:
1395 this->z_max_ = value;
1396 this->send_z_range_();
1397 break;
1399 uint32_t sleep_ms = static_cast<uint32_t>(value);
1400 uint8_t data[4];
1401 write_u32_le(data, sleep_ms);
1402 this->queue_command_(TYPE_SET_LOW_POWER_SLEEP, data, sizeof(data));
1403 break;
1404 }
1406 this->area_x_min_ = value;
1407 this->area_edits_.x_min = value;
1408 break;
1410 this->area_x_max_ = value;
1411 this->area_edits_.x_max = value;
1412 break;
1414 this->area_y_min_ = value;
1415 this->area_edits_.y_min = value;
1416 break;
1418 this->area_y_max_ = value;
1419 this->area_edits_.y_max = value;
1420 break;
1422 this->area_z_min_ = value;
1423 this->area_edits_.z_min = value;
1424 break;
1426 this->area_z_max_ = value;
1427 this->area_edits_.z_max = value;
1428 break;
1429 }
1430}
1431
1433 switch (type) {
1435 if (index == 0) {
1436 this->send_control_command_(CMD_SENSITIVITY_LOW);
1437 } else if (index == 1) {
1438 this->send_control_command_(CMD_SENSITIVITY_MEDIUM);
1439 } else if (index == 2) {
1440 this->send_control_command_(CMD_SENSITIVITY_HIGH);
1441 }
1442 break;
1444 if (index == 0) {
1445 this->send_control_command_(CMD_TRIGGER_SLOW);
1446 } else if (index == 1) {
1447 this->send_control_command_(CMD_TRIGGER_MEDIUM);
1448 } else if (index == 2) {
1449 this->send_control_command_(CMD_TRIGGER_FAST);
1450 }
1451 break;
1453 if (index == 0) {
1454 this->send_control_command_(CMD_INSTALL_TOP);
1455 } else if (index == 1) {
1456 this->send_control_command_(CMD_INSTALL_SIDE);
1457 }
1458 break;
1460 this->area_id_ = static_cast<uint8_t>(index);
1461 this->area_id_set_ = true;
1463 this->save_area_id_pref_(this->area_id_);
1464 break;
1465 }
1466}
1467
1469 // A report refreshes every axis the user is not in the middle of changing. An
1470 // unapplied edit is the one value here the module cannot know about, so taking
1471 // the report over it would discard what the user typed with nothing to show for it.
1472 const AreaConfig &edits = this->area_edits_;
1473 if (std::isnan(edits.x_min))
1474 this->area_x_min_ = area.x_min;
1475 if (std::isnan(edits.x_max))
1476 this->area_x_max_ = area.x_max;
1477 if (std::isnan(edits.y_min))
1478 this->area_y_min_ = area.y_min;
1479 if (std::isnan(edits.y_max))
1480 this->area_y_max_ = area.y_max;
1481 if (std::isnan(edits.z_min))
1482 this->area_z_min_ = area.z_min;
1483 if (std::isnan(edits.z_max))
1484 this->area_z_max_ = area.z_max;
1485 this->publish_area_numbers_();
1486}
1487
1488// The mirror, not the report: an axis a report was kept away from has to keep its
1489// displayed value too, or the entity and the value the next apply sends disagree.
1500
1502 if (area_id >= AREA_ID_COUNT)
1503 return;
1504 const bool interference = area_id < AREA_COUNT;
1505 const uint8_t index = interference ? area_id : static_cast<uint8_t>(area_id - AREA_COUNT);
1506 const AreaConfig &area = interference ? this->interference_area_values_[index] : this->detection_area_values_[index];
1507 // The edits belonged to the area being navigated away from.
1508 this->area_edits_ = AreaConfig{};
1509 this->update_area_numbers_(area);
1510}
1511
1512bool LD6002BComponent::queue_area_config_(uint8_t area_id, const AreaConfig &desired) {
1513 // One frame carries all three pairs and cannot express a crossed one; the module
1514 // would keep a box nothing can ever be inside. Both callers arrive with the six
1515 // bounds resolved, so this is the last place that can say no -- and the return
1516 // value is how saying no reaches the caller, which must not then retire the edits
1517 // the user still has to fix.
1518 if (desired.x_min > desired.x_max || desired.y_min > desired.y_max || desired.z_min > desired.z_max) {
1519 ESP_LOGW(TAG, "Area %u not written, min above max", area_id);
1520 return false;
1521 }
1522 uint8_t data[AREA_CONFIG_LEN];
1523 write_int32_le(data, static_cast<int32_t>(area_id));
1524 write_f32_le(data + 4, desired.x_min);
1525 write_f32_le(data + 8, desired.x_max);
1526 write_f32_le(data + 12, desired.y_min);
1527 write_f32_le(data + 16, desired.y_max);
1528 write_f32_le(data + 20, desired.z_min);
1529 write_f32_le(data + 24, desired.z_max);
1530
1531 if (!this->queue_command_(TYPE_SET_AREA, data, sizeof(data))) {
1532 // Nothing is on its way, so the cache must not claim these bounds, the ack
1533 // refresh must not be armed for an ack that cannot come, and the values stay
1534 // the user's unsent edit.
1535 return false;
1536 }
1537 this->area_write_in_flight_ = true;
1538
1539 const bool interference = area_id < AREA_COUNT;
1540 const uint8_t index = interference ? area_id : static_cast<uint8_t>(area_id - AREA_COUNT);
1541 AreaConfig &store = interference ? this->interference_area_values_[index] : this->detection_area_values_[index];
1542 store = desired;
1543 // The six numbers show one area at a time, and a deferred apply can land here for
1544 // an area the user has navigated away from. Same question handle_area_report_
1545 // asks before it touches them.
1546 const uint8_t selected_id = this->area_id_set_ ? this->area_id_ : AREA_ID_DEFAULT;
1547 if (area_id == selected_id) {
1548 this->update_area_numbers_(store);
1549 }
1550 return true;
1551}
1552
1553void LD6002BComponent::try_apply_pending_area_(bool reported_interference) {
1554 if (!this->deferred_apply_pending_) {
1555 return;
1556 }
1557 if (this->pending_area_id_ >= AREA_ID_COUNT) {
1558 this->deferred_apply_pending_ = false;
1559 return;
1560 }
1561 const bool interference = this->pending_area_id_ < AREA_COUNT;
1562 const uint8_t index =
1563 interference ? this->pending_area_id_ : static_cast<uint8_t>(this->pending_area_id_ - AREA_COUNT);
1564 AreaConfig desired = interference ? this->interference_area_values_[index] : this->detection_area_values_[index];
1565
1566 if (!std::isnan(this->pending_area_updates_.x_min))
1567 desired.x_min = this->pending_area_updates_.x_min;
1568 if (!std::isnan(this->pending_area_updates_.x_max))
1569 desired.x_max = this->pending_area_updates_.x_max;
1570 if (!std::isnan(this->pending_area_updates_.y_min))
1571 desired.y_min = this->pending_area_updates_.y_min;
1572 if (!std::isnan(this->pending_area_updates_.y_max))
1573 desired.y_max = this->pending_area_updates_.y_max;
1574 if (!std::isnan(this->pending_area_updates_.z_min))
1575 desired.z_min = this->pending_area_updates_.z_min;
1576 if (!std::isnan(this->pending_area_updates_.z_max))
1577 desired.z_max = this->pending_area_updates_.z_max;
1578
1579 if (std::isnan(desired.x_min) || std::isnan(desired.x_max) || std::isnan(desired.y_min) ||
1580 std::isnan(desired.y_max) || std::isnan(desired.z_min) || std::isnan(desired.z_max)) {
1581 // Only the report covering this area's half can still fill it in, and there is
1582 // exactly one of those per read. Once it has landed with a bound still unknown,
1583 // nothing further is coming and waiting means waiting forever.
1584 if (reported_interference == interference) {
1585 this->deferred_apply_pending_ = false;
1587 ESP_LOGW(TAG, "Dropping deferred area apply, area report incomplete");
1588 }
1589 return;
1590 }
1591
1592 const uint8_t area_id = this->pending_area_id_;
1593 this->deferred_apply_pending_ = false;
1594 if (!this->queue_area_config_(area_id, desired)) {
1595 // Nothing was queued, so this is a drop like the other two: hand the staged
1596 // values back rather than leaving them with no ledger to protect them.
1598 }
1599}
1600
1602#ifdef USE_SELECT
1603 if (this->area_id_select_ == nullptr) {
1604 return;
1605 }
1606 this->area_id_pref_ = this->area_id_select_->make_entity_preference<uint8_t>();
1607 this->area_id_pref_initialized_ = true;
1608
1609 uint8_t value = 0;
1610 if (!this->area_id_pref_.load(&value) || value >= AREA_ID_COUNT) {
1611 // No stored selection. The numbers are about to display this area either way,
1612 // so select it for real: a displayed area that apply_area then refuses to write
1613 // is the one combination the user cannot make sense of.
1614 value = AREA_ID_DEFAULT;
1615 }
1616 this->area_id_select_->publish_state(value);
1617 this->area_id_ = value;
1618 this->area_id_set_ = true;
1619 this->update_area_numbers_for_id_(value);
1620#endif
1621}
1622
1624#ifdef USE_SELECT
1625 if (!this->area_id_pref_initialized_) {
1626 return;
1627 }
1628 this->area_id_pref_.save(&value);
1629#endif
1630}
1631
1633#ifdef USE_TEXT_SENSOR
1634 if (this->ota_version_text_sensor_ == nullptr) {
1635 return;
1636 }
1638 this->version_pref_initialized_ = true;
1639
1640 VersionPref pref{};
1641 if (this->version_pref_.load(&pref) && pref.value[0] != '\0') {
1642 pref.value[sizeof(pref.value) - 1] = '\0';
1643 this->ota_version_text_sensor_->publish_state(pref.value);
1644 }
1645#endif
1646}
1647
1649#ifdef USE_TEXT_SENSOR
1650 if (!this->version_pref_initialized_) {
1651 return;
1652 }
1653 VersionPref pref{};
1654 std::strncpy(pref.value, value, sizeof(pref.value) - 1);
1655 pref.value[sizeof(pref.value) - 1] = '\0';
1656 this->version_pref_.save(&pref);
1657#endif
1658}
1659
1660#ifdef USE_SENSOR
1662 if (!this->last_target_presence_[index]) {
1663 return;
1664 }
1665 TargetSensors &target = this->targets_[index];
1666 if (target.x != nullptr) {
1667 target.x->publish_state(NAN);
1668 }
1669 if (target.y != nullptr) {
1670 target.y->publish_state(NAN);
1671 }
1672 if (target.z != nullptr) {
1673 target.z->publish_state(NAN);
1674 }
1675 if (target.dop_idx != nullptr) {
1676 target.dop_idx->publish_state(NAN);
1677 }
1678 if (target.cluster_id != nullptr) {
1679 target.cluster_id->publish_state(NAN);
1680 }
1681 // The slot is free: the next person's id is new even when it repeats this one.
1682 this->last_cluster_id_valid_[index] = false;
1683}
1684#endif
1685
1687 // The staged values become an unsent edit again, but only for the user who is
1688 // still looking at the area they were staged for; anyone else's ledger belongs to
1689 // the area they are on now.
1690 const uint8_t selected_id = this->area_id_set_ ? this->area_id_ : AREA_ID_DEFAULT;
1691 if (this->pending_area_id_ != selected_id) {
1692 return;
1693 }
1694 // Axis by axis rather than a whole-struct assignment: the user can have edited
1695 // another bound while the deferral was in flight, and that edit is newer than
1696 // anything the deferral staged. Assigning over the ledger would drop it back to
1697 // NaN and let the next report take the value away. A live edit wins; only an axis
1698 // with nothing in the ledger takes its staged value back.
1699 //
1700 // The mirror moves with the ledger, because on the report path handle_area_report_
1701 // ran update_area_numbers_ before the replay, with the ledger still empty -- so the
1702 // mirror already holds the module's bounds and both the entities and the next apply
1703 // would build on them. On the timeout path no report arrived, the mirror still
1704 // holds the staged values, and this is an identity.
1705 const AreaConfig &staged = this->pending_area_updates_;
1706 if (std::isnan(this->area_edits_.x_min) && !std::isnan(staged.x_min)) {
1707 this->area_edits_.x_min = staged.x_min;
1708 this->area_x_min_ = staged.x_min;
1709 }
1710 if (std::isnan(this->area_edits_.x_max) && !std::isnan(staged.x_max)) {
1711 this->area_edits_.x_max = staged.x_max;
1712 this->area_x_max_ = staged.x_max;
1713 }
1714 if (std::isnan(this->area_edits_.y_min) && !std::isnan(staged.y_min)) {
1715 this->area_edits_.y_min = staged.y_min;
1716 this->area_y_min_ = staged.y_min;
1717 }
1718 if (std::isnan(this->area_edits_.y_max) && !std::isnan(staged.y_max)) {
1719 this->area_edits_.y_max = staged.y_max;
1720 this->area_y_max_ = staged.y_max;
1721 }
1722 if (std::isnan(this->area_edits_.z_min) && !std::isnan(staged.z_min)) {
1723 this->area_edits_.z_min = staged.z_min;
1724 this->area_z_min_ = staged.z_min;
1725 }
1726 if (std::isnan(this->area_edits_.z_max) && !std::isnan(staged.z_max)) {
1727 this->area_edits_.z_max = staged.z_max;
1728 this->area_z_max_ = staged.z_max;
1729 }
1730 this->publish_area_numbers_();
1731}
1732
1734 if (!this->area_presence_any_) {
1735 return;
1736 }
1737 // Nothing else corrects this: 0x0A0A carries no period the protocol states and no
1738 // command stops it, so the module going unattended is the only moment the
1739 // component can know a stored "occupied" has stopped being true.
1740 this->area_presence_any_ = false;
1741#ifdef USE_BINARY_SENSOR
1742 for (uint8_t i = 0; i < AREA_COUNT; i++) {
1743 if (this->area_presence_[i] != nullptr) {
1744 this->area_presence_[i]->publish_state(false);
1745 }
1746 }
1747 const bool presence = this->target_presence_any_ || this->area_presence_any_;
1748 if (this->presence_binary_sensor_ != nullptr) {
1749 this->presence_binary_sensor_->publish_state(presence);
1750 }
1751#endif
1752}
1753
1755 // Nothing corrects any of this until the stream comes back. The slot table goes
1756 // with it: slots key on cluster ids, which only track a person while reports are
1757 // arriving, and the room can empty and refill across the gap -- so the next
1758 // report starts from an empty table and fills slots in wire order, rather than
1759 // handing one back to whoever last held that id.
1760 for (uint8_t i = 0; i < MAX_TARGETS; i++) {
1761#ifdef USE_SENSOR
1762 this->clear_target_slot_(i);
1763 this->last_target_presence_[i] = false;
1764#endif
1765 if (this->slot_occupied_[i]) {
1766 this->slot_occupied_[i] = false;
1767#ifdef USE_BINARY_SENSOR
1768 if (this->target_presence_[i] != nullptr) {
1769 this->target_presence_[i]->publish_state(false);
1770 }
1771#endif
1772 }
1773 }
1774#ifdef USE_SENSOR
1775 if (this->last_target_count_ != 0xFFFFFFFF) {
1776 if (this->target_count_sensor_ != nullptr) {
1778 }
1779 this->last_target_count_ = 0xFFFFFFFF;
1780 }
1781#endif
1782 if (this->target_presence_any_) {
1783 this->target_presence_any_ = false;
1784#ifdef USE_BINARY_SENSOR
1785 bool presence = this->target_presence_any_ || this->area_presence_any_;
1786 if (this->presence_binary_sensor_ != nullptr) {
1787 this->presence_binary_sensor_->publish_state(presence);
1788 }
1789#endif
1791 }
1792}
1793
1795 switch (type) {
1797 this->low_power_enabled_ = state;
1798 this->low_power_reported_ = true;
1799 this->send_control_command_(state ? CMD_LOW_POWER_ON : CMD_LOW_POWER_OFF);
1801 break;
1804 this->send_control_command_(state ? CMD_POINT_CLOUD_ON : CMD_POINT_CLOUD_OFF);
1805#ifdef USE_SENSOR
1806 // The count only moves while the stream runs, so the last one would stand as
1807 // a live reading. The dedup sentinel is cleared with it: the same count is
1808 // new again when the stream comes back.
1809 if (!state && this->point_count_sensor_ != nullptr && this->last_point_count_ != 0xFFFFFFFF) {
1811 this->last_point_count_ = 0xFFFFFFFF;
1812 }
1813#endif
1814 break;
1817 this->send_control_command_(state ? CMD_TARGET_DISPLAY_ON : CMD_TARGET_DISPLAY_OFF);
1818 if (!state) {
1819 // Every target entity is fed by the reports this just stopped.
1820 this->clear_target_state_();
1821 }
1822 break;
1823 }
1824}
1825
1827 switch (type) {
1829 this->apply_area_config_();
1830 break;
1832 this->send_control_command_(CMD_AUTO_INTERFERENCE);
1833 // The module recomputes the interference areas without reporting them.
1834 this->send_control_command_(CMD_GET_AREAS);
1835 break;
1837 this->send_control_command_(CMD_GET_AREAS);
1838 break;
1840 this->send_control_command_(CMD_CLEAR_INTERFERENCE);
1841 // The module rewrites the areas but does not report them, so ask for the new geometry the
1842 // way the apply_area ack path does; the queue keeps it behind the command above.
1843 this->send_control_command_(CMD_GET_AREAS);
1844 break;
1846 this->send_control_command_(CMD_RESET_DETECTION_AREA);
1847 this->send_control_command_(CMD_GET_AREAS);
1848 break;
1850 this->send_control_command_(CMD_GET_DELAY);
1851 break;
1853 this->send_control_command_(CMD_GET_SENSITIVITY);
1854 break;
1856 this->send_control_command_(CMD_GET_TRIGGER);
1857 break;
1859 this->send_control_command_(CMD_GET_Z_RANGE);
1860 break;
1862 this->send_control_command_(CMD_GET_INSTALLATION);
1863 break;
1865 this->send_control_command_(CMD_GET_LOW_POWER);
1866 break;
1868 this->send_control_command_(CMD_GET_LOW_POWER_SLEEP);
1869 break;
1871 this->send_control_command_(CMD_RESET_UNATTENDED);
1872 break;
1873 case ButtonType::WAKE:
1874 this->wake_();
1875 break;
1876 }
1877}
1878
1879} // namespace esphome::ld6002b
uint8_t raw[35]
Definition bl0939.h:0
void mark_failed()
Mark this component as failed.
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
const StringRef & get_name() const
Definition entity_base.h:71
ESPPreferenceObject make_entity_preference(uint32_t version=0)
Create a preference object for storing this entity's state/settings.
bool has_state() const
virtual void setup()=0
virtual void digital_write(bool value)=0
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2099
T * allocate(size_t n)
Definition helpers.h:2126
constexpr const char * c_str() const
Definition string_ref.h:73
void publish_state(bool new_state)
Publish a new state to the front-end.
text_sensor::TextSensor * work_mode_text_sensor_
Definition ld6002b.h:353
select::Select * area_id_select_
Definition ld6002b.h:375
bool queue_area_config_(uint8_t area_id, const AreaConfig &desired)
Definition ld6002b.cpp:1512
binary_sensor::BinarySensor * presence_binary_sensor_
Definition ld6002b.h:348
number::Number * area_z_min_number_
Definition ld6002b.h:368
void handle_target_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:698
text_sensor::TextSensor * ota_version_text_sensor_
Definition ld6002b.h:354
std::array< uint8_t, CMD_MAX_DATA_LEN > wake_scratch_
Definition ld6002b.h:433
static constexpr uint8_t CMD_QUEUE_SIZE
Definition ld6002b.h:409
static constexpr const char * WAKE_BUTTON_TIMEOUT
Definition ld6002b.h:418
number::Number * area_z_max_number_
Definition ld6002b.h:369
static void write_int32_le(uint8_t *data, int32_t value)
Definition ld6002b.cpp:234
void set_select_value(SelectType type, size_t index)
Definition ld6002b.cpp:1432
void save_area_id_pref_(uint8_t value)
Definition ld6002b.cpp:1623
static void write_u32_le(uint8_t *data, uint32_t value)
Definition ld6002b.cpp:227
std::array< PendingCommand, CMD_QUEUE_SIZE > cmd_queue_
Definition ld6002b.h:425
static float read_f32_le(const uint8_t *data)
Definition ld6002b.cpp:220
ESPPreferenceObject version_pref_
Definition ld6002b.h:355
void handle_installation_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:964
void set_switch_state(SwitchType type, bool state)
Definition ld6002b.cpp:1794
std::array< bool, MAX_TARGETS > last_cluster_id_valid_
Definition ld6002b.h:497
std::array< int32_t, MAX_TARGETS > last_cluster_id_
Definition ld6002b.h:496
void set_number_value(NumberType type, float value)
Definition ld6002b.cpp:1381
void handle_trigger_speed_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:938
select::Select * installation_select_
Definition ld6002b.h:374
std::array< AreaSensors, AREA_COUNT > detection_areas_
Definition ld6002b.h:345
select::Select * trigger_speed_select_
Definition ld6002b.h:373
static uint32_t read_u32_le(const uint8_t *data)
Definition ld6002b.cpp:208
void save_version_pref_(const char *value)
Definition ld6002b.cpp:1648
number::Number * area_x_max_number_
Definition ld6002b.h:365
sensor::Sensor * point_count_sensor_
Definition ld6002b.h:343
static constexpr uint8_t CMD_MAX_RETRIES
Definition ld6002b.h:415
void update_area_numbers_for_id_(uint8_t area_id)
Definition ld6002b.cpp:1501
void update_area_numbers_(const AreaConfig &area)
Definition ld6002b.cpp:1468
std::array< AreaConfig, AREA_COUNT > interference_area_values_
Definition ld6002b.h:467
void handle_version_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:1080
number::Number * area_y_max_number_
Definition ld6002b.h:367
switch_::Switch * target_display_switch_
Definition ld6002b.h:382
void send_command_internal_(uint16_t type, const uint8_t *data, uint8_t len, bool track)
Definition ld6002b.cpp:1210
static uint16_t read_u16_be(const uint8_t *data)
Definition ld6002b.cpp:206
static constexpr const char * AREA_REFRESH_TIMEOUT
Definition ld6002b.h:421
void handle_area_presence_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:842
void publish_number_clamped_(number::Number *number, float value)
Definition ld6002b.cpp:1054
select::Select * sensitivity_select_
Definition ld6002b.h:372
number::Number * hold_delay_number_
Definition ld6002b.h:359
static constexpr uint32_t MODULE_AWAKE_MS
Definition ld6002b.h:414
static constexpr uint32_t CMD_FIRST_ACK_TIMEOUT_MS
Definition ld6002b.h:412
static int32_t read_int32_le(const uint8_t *data)
Definition ld6002b.cpp:213
void handle_area_report_(bool interference, const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:868
std::array< bool, MAX_TARGETS > slot_occupied_
Definition ld6002b.h:474
void handle_low_power_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:977
std::array< AreaConfig, AREA_COUNT > detection_area_values_
Definition ld6002b.h:468
static constexpr uint32_t CMD_ACK_TIMEOUT_MS
Definition ld6002b.h:410
std::array< int32_t, MAX_TARGETS > slot_cluster_
Definition ld6002b.h:473
std::array< binary_sensor::BinarySensor *, AREA_COUNT > area_presence_
Definition ld6002b.h:350
void handle_delay_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:916
std::array< AreaSensors, AREA_COUNT > interference_areas_
Definition ld6002b.h:344
void handle_sensitivity_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:925
std::array< TargetSensors, MAX_TARGETS > targets_
Definition ld6002b.h:341
void handle_frame_(uint16_t type, const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:608
void send_command_(uint16_t type, const uint8_t *data, uint8_t len)
Definition ld6002b.cpp:1206
switch_::Switch * low_power_switch_
Definition ld6002b.h:380
sensor::Sensor * target_count_sensor_
Definition ld6002b.h:342
switch_::Switch * point_cloud_switch_
Definition ld6002b.h:381
std::array< bool, MAX_TARGETS > last_target_presence_
Definition ld6002b.h:494
number::Number * area_y_min_number_
Definition ld6002b.h:366
void publish_work_mode_(bool low_power)
Definition ld6002b.cpp:1039
void write_frame_(uint16_t type, const uint8_t *data, uint8_t len, bool track)
Definition ld6002b.cpp:1249
std::array< binary_sensor::BinarySensor *, MAX_TARGETS > target_presence_
Definition ld6002b.h:349
void handle_low_power_sleep_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:991
void handle_work_mode_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:1000
void press_button(ButtonType type)
Definition ld6002b.cpp:1826
number::Number * area_x_min_number_
Definition ld6002b.h:364
void try_apply_pending_area_(bool reported_interference)
Definition ld6002b.cpp:1553
bool queue_command_(uint16_t type, const uint8_t *data, uint8_t len)
Definition ld6002b.cpp:1101
void clear_target_slot_(uint8_t index)
Definition ld6002b.cpp:1661
number::Number * low_power_sleep_number_
Definition ld6002b.h:362
static constexpr uint32_t STALE_ACK_MAX_AGE_MS
Definition ld6002b.h:423
ESPPreferenceObject area_id_pref_
Definition ld6002b.h:376
bool send_control_command_(uint32_t command)
Definition ld6002b.cpp:1290
void handle_point_cloud_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:818
void handle_z_range_report_(const uint8_t *data, uint16_t len)
Definition ld6002b.cpp:951
static void write_f32_le(uint8_t *data, float value)
Definition ld6002b.cpp:238
Base-class for all numbers.
Definition number.h:29
void publish_state(float state)
Definition number.cpp:22
NumberTraits traits
Definition number.h:41
void publish_state(const std::string &state)
Definition select.cpp:11
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
void turn_on()
Turn this switch on.
Definition switch.cpp:20
void turn_off()
Turn this switch off.
Definition switch.cpp:24
void publish_state(bool state)
Publish a state to the front-end from the back-end.
Definition switch.cpp:56
optional< bool > get_initial_state_with_restore_mode()
Returns the initial state of the switch, after applying restore mode rules.
Definition switch.cpp:42
void publish_state(const std::string &state)
void write_byte(uint8_t data)
Definition uart.h:18
uint16_t type
bool state
Definition fan.h:2
bool z
Definition msa3xx.h:1
const void size_t len
Definition hal.h:64
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t
sensor::Sensor * z_max
Definition ld6002b.h:101
sensor::Sensor * z_min
Definition ld6002b.h:100
sensor::Sensor * x_min
Definition ld6002b.h:96
sensor::Sensor * y_max
Definition ld6002b.h:99
sensor::Sensor * y_min
Definition ld6002b.h:98
sensor::Sensor * x_max
Definition ld6002b.h:97
std::array< uint8_t, CMD_MAX_DATA_LEN > data
Definition ld6002b.h:278
sensor::Sensor * cluster_id
Definition ld6002b.h:92
sensor::Sensor * dop_idx
Definition ld6002b.h:91
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6