ESPHome 2026.3.0
Loading...
Searching...
No Matches
ld2412.cpp
Go to the documentation of this file.
1#include "ld2412.h"
2
3#ifdef USE_NUMBER
5#endif
6#ifdef USE_SENSOR
8#endif
9
12
13namespace esphome::ld2412 {
14
15static const char *const TAG = "ld2412";
16
27
33
39
40enum OutPinLevel : uint8_t {
43};
44
45/*
46Data Type: 6th byte
47Target states: 9th byte
48 Moving target distance: 10~11th bytes
49 Moving target energy: 12th byte
50 Still target distance: 13~14th bytes
51 Still target energy: 15th byte
52 Detect distance: 16~17th bytes
53*/
68
69enum PeriodicDataValue : uint8_t {
70 HEADER = 0XAA,
71 FOOTER = 0x55,
72 CHECK = 0x00,
73};
74
75enum AckData : uint8_t {
78};
79
80// Memory-efficient lookup tables
81struct StringToUint8 {
82 const char *str;
83 const uint8_t value;
84};
85
86struct Uint8ToString {
87 const uint8_t value;
88 const char *str;
89};
90
91constexpr StringToUint8 BAUD_RATES_BY_STR[] = {
92 {"9600", BAUD_RATE_9600}, {"19200", BAUD_RATE_19200}, {"38400", BAUD_RATE_38400},
93 {"57600", BAUD_RATE_57600}, {"115200", BAUD_RATE_115200}, {"230400", BAUD_RATE_230400},
94 {"256000", BAUD_RATE_256000}, {"460800", BAUD_RATE_460800},
95};
96
97constexpr StringToUint8 DISTANCE_RESOLUTIONS_BY_STR[] = {
100 {"0.75m", DISTANCE_RESOLUTION_0_75},
101};
102
103constexpr Uint8ToString DISTANCE_RESOLUTIONS_BY_UINT[] = {
104 {DISTANCE_RESOLUTION_0_2, "0.2m"},
105 {DISTANCE_RESOLUTION_0_5, "0.5m"},
106 {DISTANCE_RESOLUTION_0_75, "0.75m"},
107};
108
109constexpr StringToUint8 LIGHT_FUNCTIONS_BY_STR[] = {
110 {"off", LIGHT_FUNCTION_OFF},
111 {"below", LIGHT_FUNCTION_BELOW},
112 {"above", LIGHT_FUNCTION_ABOVE},
113};
114
115constexpr Uint8ToString LIGHT_FUNCTIONS_BY_UINT[] = {
116 {LIGHT_FUNCTION_OFF, "off"},
117 {LIGHT_FUNCTION_BELOW, "below"},
118 {LIGHT_FUNCTION_ABOVE, "above"},
119};
120
121constexpr StringToUint8 OUT_PIN_LEVELS_BY_STR[] = {
122 {"low", OUT_PIN_LEVEL_LOW},
123 {"high", OUT_PIN_LEVEL_HIGH},
124};
125
126constexpr Uint8ToString OUT_PIN_LEVELS_BY_UINT[] = {
127 {OUT_PIN_LEVEL_LOW, "low"},
128 {OUT_PIN_LEVEL_HIGH, "high"},
129};
130
131constexpr uint32_t BAUD_RATES[] = {9600, 19200, 38400, 57600, 115200, 230400, 256000, 460800};
132
133// Helper functions for lookups
134template<size_t N> uint8_t find_uint8(const StringToUint8 (&arr)[N], const char *str) {
135 for (const auto &entry : arr) {
136 if (strcmp(str, entry.str) == 0) {
137 return entry.value;
138 }
139 }
140 return 0xFF; // Not found
141}
142
143template<size_t N> const char *find_str(const Uint8ToString (&arr)[N], uint8_t value) {
144 for (const auto &entry : arr) {
145 if (value == entry.value) {
146 return entry.str;
147 }
148 }
149 return ""; // Not found
150}
151
152static constexpr uint8_t DEFAULT_PRESENCE_TIMEOUT = 5; // Default used when number component is not defined
153// Commands
154static constexpr uint8_t CMD_ENABLE_CONF = 0xFF;
155static constexpr uint8_t CMD_DISABLE_CONF = 0xFE;
156static constexpr uint8_t CMD_ENABLE_ENG = 0x62;
157static constexpr uint8_t CMD_DISABLE_ENG = 0x63;
158static constexpr uint8_t CMD_QUERY_BASIC_CONF = 0x12;
159static constexpr uint8_t CMD_BASIC_CONF = 0x02;
160static constexpr uint8_t CMD_QUERY_VERSION = 0xA0;
161static constexpr uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0x11;
162static constexpr uint8_t CMD_SET_DISTANCE_RESOLUTION = 0x01;
163static constexpr uint8_t CMD_QUERY_LIGHT_CONTROL = 0x1C;
164static constexpr uint8_t CMD_SET_LIGHT_CONTROL = 0x0C;
165static constexpr uint8_t CMD_SET_BAUD_RATE = 0xA1;
166static constexpr uint8_t CMD_QUERY_MAC_ADDRESS = 0xA5;
167static constexpr uint8_t CMD_FACTORY_RESET = 0xA2;
168static constexpr uint8_t CMD_RESTART = 0xA3;
169static constexpr uint8_t CMD_BLUETOOTH = 0xA4;
170static constexpr uint8_t CMD_DYNAMIC_BACKGROUND_CORRECTION = 0x0B;
171static constexpr uint8_t CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION = 0x1B;
172static constexpr uint8_t CMD_MOTION_GATE_SENS = 0x03;
173static constexpr uint8_t CMD_QUERY_MOTION_GATE_SENS = 0x13;
174static constexpr uint8_t CMD_STATIC_GATE_SENS = 0x04;
175static constexpr uint8_t CMD_QUERY_STATIC_GATE_SENS = 0x14;
176static constexpr uint8_t CMD_NONE = 0x00;
177// Commands values
178static constexpr uint8_t CMD_MAX_MOVE_VALUE = 0x00;
179static constexpr uint8_t CMD_MAX_STILL_VALUE = 0x01;
180static constexpr uint8_t CMD_DURATION_VALUE = 0x02;
181// Bitmasks for target states
182static constexpr uint8_t MOVE_BITMASK = 0x01;
183static constexpr uint8_t STILL_BITMASK = 0x02;
184// Header & Footer size
185static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
186// Command Header & Footer
187static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xFD, 0xFC, 0xFB, 0xFA};
188static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0x04, 0x03, 0x02, 0x01};
189// Data Header & Footer
190static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
191static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
192// MAC address the module uses when Bluetooth is disabled
193static constexpr uint8_t NO_MAC[] = {0x08, 0x05, 0x04, 0x03, 0x02, 0x01};
194
195static inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
196 return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;
197}
198
199void LD2412Component::dump_config() {
200 char mac_s[18];
201 char version_s[20];
202 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
203 ld24xx::format_version_str(this->version_, version_s);
204 ESP_LOGCONFIG(TAG,
205 "LD2412:\n"
206 " Firmware version: %s\n"
207 " MAC address: %s",
208 version_s, mac_str);
209#ifdef USE_BINARY_SENSOR
210 ESP_LOGCONFIG(TAG, "Binary Sensors:");
211 LOG_BINARY_SENSOR(" ", "DynamicBackgroundCorrectionStatus",
212 this->dynamic_background_correction_status_binary_sensor_);
213 LOG_BINARY_SENSOR(" ", "MovingTarget", this->moving_target_binary_sensor_);
214 LOG_BINARY_SENSOR(" ", "StillTarget", this->still_target_binary_sensor_);
215 LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_);
216#endif
217#ifdef USE_SENSOR
218 ESP_LOGCONFIG(TAG, "Sensors:");
219 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "Light", this->light_sensor_);
220 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "DetectionDistance", this->detection_distance_sensor_);
221 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "MovingTargetDistance", this->moving_target_distance_sensor_);
222 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "MovingTargetEnergy", this->moving_target_energy_sensor_);
223 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "StillTargetDistance", this->still_target_distance_sensor_);
224 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "StillTargetEnergy", this->still_target_energy_sensor_);
225 for (auto &s : this->gate_still_sensors_) {
226 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "GateStill", s);
227 }
228 for (auto &s : this->gate_move_sensors_) {
229 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "GateMove", s);
230 }
231#endif
232#ifdef USE_TEXT_SENSOR
233 ESP_LOGCONFIG(TAG, "Text Sensors:");
234 LOG_TEXT_SENSOR(" ", "MAC address", this->mac_text_sensor_);
235 LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_);
236#endif
237#ifdef USE_NUMBER
238 ESP_LOGCONFIG(TAG, "Numbers:");
239 LOG_NUMBER(" ", "LightThreshold", this->light_threshold_number_);
240 LOG_NUMBER(" ", "MaxDistanceGate", this->max_distance_gate_number_);
241 LOG_NUMBER(" ", "MinDistanceGate", this->min_distance_gate_number_);
242 LOG_NUMBER(" ", "Timeout", this->timeout_number_);
243 for (number::Number *n : this->gate_move_threshold_numbers_) {
244 LOG_NUMBER(" ", "Move Thresholds", n);
245 }
246 for (number::Number *n : this->gate_still_threshold_numbers_) {
247 LOG_NUMBER(" ", "Still Thresholds", n);
248 }
249#endif
250#ifdef USE_SELECT
251 ESP_LOGCONFIG(TAG, "Selects:");
252 LOG_SELECT(" ", "BaudRate", this->baud_rate_select_);
253 LOG_SELECT(" ", "DistanceResolution", this->distance_resolution_select_);
254 LOG_SELECT(" ", "LightFunction", this->light_function_select_);
255 LOG_SELECT(" ", "OutPinLevel", this->out_pin_level_select_);
256#endif
257#ifdef USE_SWITCH
258 ESP_LOGCONFIG(TAG, "Switches:");
259 LOG_SWITCH(" ", "Bluetooth", this->bluetooth_switch_);
260 LOG_SWITCH(" ", "EngineeringMode", this->engineering_mode_switch_);
261#endif
262#ifdef USE_BUTTON
263 ESP_LOGCONFIG(TAG, "Buttons:");
264 LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_);
265 LOG_BUTTON(" ", "Query", this->query_button_);
266 LOG_BUTTON(" ", "Restart", this->restart_button_);
267 LOG_BUTTON(" ", "StartDynamicBackgroundCorrection", this->start_dynamic_background_correction_button_);
268#endif
269}
270
272 ESP_LOGCONFIG(TAG, "Running setup");
273 this->read_all_info();
274}
275
276void LD2412Component::read_all_info() {
277 this->set_config_mode_(true);
278 this->get_version_();
279 delay(10); // NOLINT
280 this->get_mac_();
281 delay(10); // NOLINT
283 delay(10); // NOLINT
284 this->query_parameters_();
285 delay(10); // NOLINT
287 delay(10); // NOLINT
288 this->query_light_control_();
289 delay(10); // NOLINT
290#ifdef USE_NUMBER
291 this->get_gate_threshold();
292 delay(10); // NOLINT
293#endif
294 this->set_config_mode_(false);
295#ifdef USE_SELECT
296 if (this->baud_rate_select_ != nullptr) {
297 if (auto index = ld24xx::find_index(BAUD_RATES, this->parent_->get_baud_rate())) {
298 this->baud_rate_select_->publish_state(*index);
299 }
300 }
301#endif
302}
303
304void LD2412Component::restart_and_read_all_info() {
305 this->set_config_mode_(true);
306 this->restart_();
307 this->set_timeout(1000, [this]() { this->read_all_info(); });
308}
309
310void LD2412Component::loop() {
311 // Read all available bytes in batches to reduce UART call overhead.
312 size_t avail = this->available();
313 uint8_t buf[MAX_LINE_LENGTH];
314 while (avail > 0) {
315 size_t to_read = std::min(avail, sizeof(buf));
316 if (!this->read_array(buf, to_read)) {
317 break;
318 }
319 avail -= to_read;
320
321 for (size_t i = 0; i < to_read; i++) {
322 this->readline_(buf[i]);
323 }
324 }
325}
326
327void LD2412Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
328 ESP_LOGV(TAG, "Sending COMMAND %02X", command);
329 // frame header bytes
330 this->write_array(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
331 // length bytes
332 uint8_t len = 2;
333 if (command_value != nullptr) {
334 len += command_value_len;
335 }
336 // 2 length bytes (low, high) + 2 command bytes (low, high)
337 uint8_t len_cmd[] = {len, 0x00, command, 0x00};
338 this->write_array(len_cmd, sizeof(len_cmd));
339
340 // command value bytes
341 if (command_value != nullptr) {
342 this->write_array(command_value, command_value_len);
343 }
344 // frame footer bytes
345 this->write_array(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
346
347 if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
348 delay(30); // NOLINT
349 }
350 delay(20); // NOLINT
351}
352
354 // 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
355 // data header=0xAA, data footer=0x55, crc=0x00
356 if (this->buffer_pos_ < 12 || !ld2412::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
357 this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER) {
358 return;
359 }
360 /*
361 Data Type: 7th
362 0x01: Engineering mode
363 0x02: Normal mode
364 */
365 bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
366#ifdef USE_SWITCH
367 if (this->engineering_mode_switch_ != nullptr) {
368 this->engineering_mode_switch_->publish_state(engineering_mode);
369 }
370#endif
371
372#ifdef USE_BINARY_SENSOR
373 /*
374 Target states: 9th
375 0x00 = No target
376 0x01 = Moving targets
377 0x02 = Still targets
378 0x03 = Moving+Still targets
379 */
380 char target_state = this->buffer_data_[TARGET_STATES];
381 if (this->target_binary_sensor_ != nullptr) {
382 this->target_binary_sensor_->publish_state(target_state != 0x00);
383 }
384 if (this->moving_target_binary_sensor_ != nullptr) {
385 this->moving_target_binary_sensor_->publish_state(target_state & MOVE_BITMASK);
386 }
387 if (this->still_target_binary_sensor_ != nullptr) {
388 this->still_target_binary_sensor_->publish_state(target_state & STILL_BITMASK);
389 }
390#endif
391 /*
392 Moving target distance: 10~11th bytes
393 Moving target energy: 12th byte
394 Still target distance: 13~14th bytes
395 Still target energy: 15th byte
396 Detect distance: 16~17th bytes
397 */
398#ifdef USE_SENSOR
399 SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
401 SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY])
402 SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
404 SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY])
405 if (this->detection_distance_sensor_ != nullptr) {
406 int new_detect_distance = 0;
407 if (target_state != 0x00 && (target_state & MOVE_BITMASK)) {
408 new_detect_distance =
409 encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]);
410 } else if (target_state != 0x00) {
411 new_detect_distance = encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]);
412 }
413 this->detection_distance_sensor_->publish_state_if_not_dup(new_detect_distance);
414 }
415 if (engineering_mode) {
416 // Engineering mode needs at least LIGHT_SENSOR + 1 bytes
417 if (this->buffer_pos_ < LIGHT_SENSOR + 1) {
418 ESP_LOGW(TAG, "Engineering mode packet too short: %u", this->buffer_pos_);
419 } else {
420 /*
421 Moving distance range: 18th byte
422 Still distance range: 19th byte
423 Moving energy: 20~28th bytes
424 */
425 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
426 SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i])
427 }
428 /*
429 Still energy: 29~37th bytes
430 */
431 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
432 SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i])
433 }
434 /*
435 Light sensor value
436 */
437 SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR])
438 }
439 } else {
440 for (auto &gate_move_sensor : this->gate_move_sensors_) {
441 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_move_sensor)
442 }
443 for (auto &gate_still_sensor : this->gate_still_sensors_) {
444 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_still_sensor)
445 }
446 SAFE_PUBLISH_SENSOR_UNKNOWN(this->light_sensor_)
447 }
448#endif
449 // the radar module won't tell us when it's done, so we just have to keep polling...
451 this->set_config_mode_(true);
453 this->set_config_mode_(false);
454 }
455}
456
457#ifdef USE_NUMBER
458std::function<void(void)> set_number_value(number::Number *n, float value) {
459 if (n != nullptr && (!n->has_state() || n->state != value)) {
460 n->state = value;
461 return [n, value]() { n->publish_state(value); };
462 }
463 return []() {};
464}
465#endif
466
468 ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
469 if (this->buffer_pos_ < 10) {
470 ESP_LOGW(TAG, "Invalid length");
471 return true;
472 }
473 if (!ld2412::validate_header_footer(CMD_FRAME_HEADER, this->buffer_data_)) {
474 char hex_buf[format_hex_pretty_size(HEADER_FOOTER_SIZE)];
475 ESP_LOGW(TAG, "Invalid header: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, HEADER_FOOTER_SIZE));
476 return true;
477 }
478 if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
479 ESP_LOGW(TAG, "Invalid status");
480 return true;
481 }
482 if (this->buffer_data_[8] || this->buffer_data_[9]) {
483 ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
484 return true;
485 }
486
487 switch (this->buffer_data_[COMMAND]) {
488 case CMD_ENABLE_CONF:
489 ESP_LOGV(TAG, "Enable conf");
490 break;
491
492 case CMD_DISABLE_CONF:
493 ESP_LOGV(TAG, "Disabled conf");
494 break;
495
496 case CMD_SET_BAUD_RATE:
497 ESP_LOGV(TAG, "Baud rate change");
498#ifdef USE_SELECT
499 if (this->baud_rate_select_ != nullptr) {
500 auto baud = this->baud_rate_select_->current_option();
501 ESP_LOGW(TAG, "Change baud rate to %.*s and reinstall", (int) baud.size(), baud.c_str());
502 }
503#endif
504 break;
505
506 case CMD_QUERY_VERSION: {
507 std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
508 char version_s[20];
509 ld24xx::format_version_str(this->version_, version_s);
510 ESP_LOGV(TAG, "Firmware version: %s", version_s);
511#ifdef USE_TEXT_SENSOR
512 if (this->version_text_sensor_ != nullptr) {
513 this->version_text_sensor_->publish_state(version_s);
514 }
515#endif
516 break;
517 }
518 case CMD_QUERY_DISTANCE_RESOLUTION: {
519 const auto *distance_resolution = find_str(DISTANCE_RESOLUTIONS_BY_UINT, this->buffer_data_[10]);
520 ESP_LOGV(TAG, "Distance resolution: %s", distance_resolution);
521#ifdef USE_SELECT
522 if (this->distance_resolution_select_ != nullptr) {
523 this->distance_resolution_select_->publish_state(distance_resolution);
524 }
525#endif
526 break;
527 }
528
529 case CMD_QUERY_LIGHT_CONTROL: {
530 this->light_function_ = this->buffer_data_[10];
531 this->light_threshold_ = this->buffer_data_[11];
532 const auto *light_function_str = find_str(LIGHT_FUNCTIONS_BY_UINT, this->light_function_);
533 ESP_LOGV(TAG, "Light function: %s, threshold: %u", light_function_str, this->light_threshold_);
534#ifdef USE_SELECT
535 if (this->light_function_select_ != nullptr) {
536 this->light_function_select_->publish_state(light_function_str);
537 }
538#endif
539#ifdef USE_NUMBER
540 if (this->light_threshold_number_ != nullptr) {
541 this->light_threshold_number_->publish_state(static_cast<float>(this->light_threshold_));
542 }
543#endif
544 break;
545 }
546
547 case CMD_QUERY_MAC_ADDRESS: {
548 if (this->buffer_pos_ < 20) {
549 return false;
550 }
551
552 this->bluetooth_on_ = std::memcmp(&this->buffer_data_[10], NO_MAC, sizeof(NO_MAC)) != 0;
553 if (this->bluetooth_on_) {
554 std::memcpy(this->mac_address_, &this->buffer_data_[10], sizeof(this->mac_address_));
555 }
556
557 char mac_s[18];
558 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
559 ESP_LOGV(TAG, "MAC address: %s", mac_str);
560#ifdef USE_TEXT_SENSOR
561 if (this->mac_text_sensor_ != nullptr) {
562 this->mac_text_sensor_->publish_state(mac_str);
563 }
564#endif
565#ifdef USE_SWITCH
566 if (this->bluetooth_switch_ != nullptr) {
567 this->bluetooth_switch_->publish_state(this->bluetooth_on_);
568 }
569#endif
570 break;
571 }
572
573 case CMD_SET_DISTANCE_RESOLUTION:
574 ESP_LOGV(TAG, "Handled set distance resolution command");
575 break;
576
577 case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
578 ESP_LOGV(TAG, "Handled query dynamic background correction");
579 bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
580#ifdef USE_BINARY_SENSOR
581 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
582 this->dynamic_background_correction_status_binary_sensor_->publish_state(dynamic_background_correction_active);
583 }
584#endif
585 this->dynamic_background_correction_active_ = dynamic_background_correction_active;
586 break;
587 }
588
589 case CMD_BLUETOOTH:
590 ESP_LOGV(TAG, "Handled bluetooth command");
591 break;
592
593 case CMD_SET_LIGHT_CONTROL:
594 ESP_LOGV(TAG, "Handled set light control command");
595 break;
596
597 case CMD_QUERY_MOTION_GATE_SENS: {
598#ifdef USE_NUMBER
599 std::vector<std::function<void(void)>> updates;
600 updates.reserve(this->gate_still_threshold_numbers_.size());
601 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
602 updates.push_back(set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[10 + i]));
603 }
604 for (auto &update : updates) {
605 update();
606 }
607#endif
608 break;
609 }
610
611 case CMD_QUERY_STATIC_GATE_SENS: {
612#ifdef USE_NUMBER
613 std::vector<std::function<void(void)>> updates;
614 updates.reserve(this->gate_still_threshold_numbers_.size());
615 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
616 updates.push_back(set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[10 + i]));
617 }
618 for (auto &update : updates) {
619 update();
620 }
621#endif
622 break;
623 }
624
625 case CMD_QUERY_BASIC_CONF: // Query parameters response
626 {
627#ifdef USE_NUMBER
628 /*
629 Moving distance range: 9th byte
630 Still distance range: 10th byte
631 */
632 std::vector<std::function<void(void)>> updates;
633 updates.push_back(set_number_value(this->min_distance_gate_number_, this->buffer_data_[10]));
634 updates.push_back(set_number_value(this->max_distance_gate_number_, this->buffer_data_[11] - 1));
635 ESP_LOGV(TAG, "min_distance_gate_number_: %u, max_distance_gate_number_ %u", this->buffer_data_[10],
636 this->buffer_data_[11]);
637 /*
638 None Duration: 11~12th bytes
639 */
640 updates.push_back(
641 set_number_value(this->timeout_number_, encode_uint16(this->buffer_data_[13], this->buffer_data_[12])));
642 ESP_LOGV(TAG, "timeout_number_: %u", encode_uint16(this->buffer_data_[13], this->buffer_data_[12]));
643 /*
644 Output pin configuration: 13th bytes
645 */
646 this->out_pin_level_ = this->buffer_data_[14];
647#ifdef USE_SELECT
648 const auto *out_pin_level_str = find_str(OUT_PIN_LEVELS_BY_UINT, this->out_pin_level_);
649 if (this->out_pin_level_select_ != nullptr) {
650 this->out_pin_level_select_->publish_state(out_pin_level_str);
651 }
652#endif
653 for (auto &update : updates) {
654 update();
655 }
656#endif
657 } break;
658 default:
659 break;
660 }
661
662 return true;
663}
664
666 if (readch < 0) {
667 return; // No data available
668 }
669 if (this->buffer_pos_ < HEADER_FOOTER_SIZE && readch != DATA_FRAME_HEADER[this->buffer_pos_] &&
670 readch != CMD_FRAME_HEADER[this->buffer_pos_]) {
671 this->buffer_pos_ = 0;
672 return;
673 }
674 if (this->buffer_pos_ < MAX_LINE_LENGTH - 1) {
675 this->buffer_data_[this->buffer_pos_++] = readch;
676 this->buffer_data_[this->buffer_pos_] = 0;
677 } else {
678 // We should never get here, but just in case...
679 ESP_LOGW(TAG, "Max command length exceeded; ignoring");
680 this->buffer_pos_ = 0;
681 }
682 if (this->buffer_pos_ < 4) {
683 return; // Not enough data to process yet
684 }
685 if (ld2412::validate_header_footer(DATA_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
686#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
687 char hex_buf[format_hex_pretty_size(MAX_LINE_LENGTH)];
688 ESP_LOGV(TAG, "Handling Periodic Data: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, this->buffer_pos_));
689#endif
690 this->handle_periodic_data_();
691 this->buffer_pos_ = 0; // Reset position index for next message
692 } else if (ld2412::validate_header_footer(CMD_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
693#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
694 char hex_buf[format_hex_pretty_size(MAX_LINE_LENGTH)];
695 ESP_LOGV(TAG, "Handling Ack Data: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, this->buffer_pos_));
696#endif
697 if (this->handle_ack_data_()) {
698 this->buffer_pos_ = 0; // Reset position index for next message
699 } else {
700 ESP_LOGV(TAG, "Ack Data incomplete");
701 }
702 }
703}
704
706 const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF;
707 const uint8_t cmd_value[2] = {0x01, 0x00};
708 this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value));
709}
710
711void LD2412Component::set_bluetooth(bool enable) {
712 this->set_config_mode_(true);
713 const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00};
714 this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value));
715 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
716}
717
718void LD2412Component::set_distance_resolution(const char *state) {
719 this->set_config_mode_(true);
720 const uint8_t cmd_value[6] = {find_uint8(DISTANCE_RESOLUTIONS_BY_STR, state), 0x00, 0x00, 0x00, 0x00, 0x00};
721 this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, sizeof(cmd_value));
722 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
723}
724
725void LD2412Component::set_baud_rate(const char *state) {
726 this->set_config_mode_(true);
727 const uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00};
728 this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value));
729 this->set_timeout(200, [this]() { this->restart_(); });
730}
731
733 this->send_command_(CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
734}
735
736void LD2412Component::start_dynamic_background_correction() {
738 return; // Already in progress
739 }
740#ifdef USE_BINARY_SENSOR
741 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
742 this->dynamic_background_correction_status_binary_sensor_->publish_state(true);
743 }
744#endif
746 this->set_config_mode_(true);
747 this->send_command_(CMD_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
748 this->set_config_mode_(false);
749}
750
751void LD2412Component::set_engineering_mode(bool enable) {
752 const uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG;
753 this->set_config_mode_(true);
754 this->send_command_(cmd, nullptr, 0);
755 this->set_config_mode_(false);
756}
757
758void LD2412Component::factory_reset() {
759 this->set_config_mode_(true);
760 this->send_command_(CMD_FACTORY_RESET, nullptr, 0);
761 this->set_timeout(2000, [this]() { this->restart_and_read_all_info(); });
762}
763
764void LD2412Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); }
765
766void LD2412Component::query_parameters_() { this->send_command_(CMD_QUERY_BASIC_CONF, nullptr, 0); }
767
768void LD2412Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); }
769
771 const uint8_t cmd_value[2] = {0x01, 0x00};
772 this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, sizeof(cmd_value));
773}
774
775void LD2412Component::get_distance_resolution_() { this->send_command_(CMD_QUERY_DISTANCE_RESOLUTION, nullptr, 0); }
776
777void LD2412Component::query_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); }
778
779void LD2412Component::set_basic_config() {
780#ifdef USE_NUMBER
781 if (!this->min_distance_gate_number_->has_state() || !this->max_distance_gate_number_->has_state() ||
782 !this->timeout_number_->has_state()) {
783 return;
784 }
785#endif
786#ifdef USE_SELECT
787 if (!this->out_pin_level_select_->has_state()) {
788 return;
789 }
790#endif
791
792 uint8_t value[5] = {
793#ifdef USE_NUMBER
794 lowbyte(static_cast<int>(this->min_distance_gate_number_->state)),
795 lowbyte(static_cast<int>(this->max_distance_gate_number_->state) + 1),
796 lowbyte(static_cast<int>(this->timeout_number_->state)),
797 highbyte(static_cast<int>(this->timeout_number_->state)),
798#else
799 1, TOTAL_GATES, DEFAULT_PRESENCE_TIMEOUT, 0,
800#endif
801#ifdef USE_SELECT
802 find_uint8(OUT_PIN_LEVELS_BY_STR, this->out_pin_level_select_->current_option().c_str()),
803#else
804 0x01, // Default value if not using select
805#endif
806 };
807 this->set_config_mode_(true);
808 this->send_command_(CMD_BASIC_CONF, value, sizeof(value));
809 this->set_config_mode_(false);
810}
811
812#ifdef USE_NUMBER
813void LD2412Component::set_gate_threshold() {
814 if (this->gate_move_threshold_numbers_.empty() && this->gate_still_threshold_numbers_.empty()) {
815 return; // No gate threshold numbers set; nothing to do here
816 }
817 uint8_t value[TOTAL_GATES] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
818 this->set_config_mode_(true);
819 if (!this->gate_move_threshold_numbers_.empty()) {
820 for (size_t i = 0; i < this->gate_move_threshold_numbers_.size(); i++) {
821 value[i] = lowbyte(static_cast<int>(this->gate_move_threshold_numbers_[i]->state));
822 }
823 this->send_command_(CMD_MOTION_GATE_SENS, value, sizeof(value));
824 }
825 if (!this->gate_still_threshold_numbers_.empty()) {
826 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
827 value[i] = lowbyte(static_cast<int>(this->gate_still_threshold_numbers_[i]->state));
828 }
829 this->send_command_(CMD_STATIC_GATE_SENS, value, sizeof(value));
830 }
831 this->set_config_mode_(false);
832}
833
834void LD2412Component::get_gate_threshold() {
835 this->send_command_(CMD_QUERY_MOTION_GATE_SENS, nullptr, 0);
836 this->send_command_(CMD_QUERY_STATIC_GATE_SENS, nullptr, 0);
837}
838
839void LD2412Component::set_gate_still_threshold_number(uint8_t gate, number::Number *n) {
840 this->gate_still_threshold_numbers_[gate] = n;
841}
842
843void LD2412Component::set_gate_move_threshold_number(uint8_t gate, number::Number *n) {
844 this->gate_move_threshold_numbers_[gate] = n;
845}
846#endif
847
848void LD2412Component::set_light_out_control() {
849#ifdef USE_NUMBER
850 if (this->light_threshold_number_ != nullptr && this->light_threshold_number_->has_state()) {
851 this->light_threshold_ = static_cast<uint8_t>(this->light_threshold_number_->state);
852 }
853#endif
854#ifdef USE_SELECT
855 if (this->light_function_select_ != nullptr && this->light_function_select_->has_state()) {
856 this->light_function_ = find_uint8(LIGHT_FUNCTIONS_BY_STR, this->light_function_select_->current_option().c_str());
857 }
858#endif
859 uint8_t value[2] = {this->light_function_, this->light_threshold_};
860 this->set_config_mode_(true);
861 this->send_command_(CMD_SET_LIGHT_CONTROL, value, sizeof(value));
862 this->query_light_control_();
863 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
864}
865
866#ifdef USE_SENSOR
867// These could leak memory, but they are only set once prior to 'setup()' and should never be used again.
868void LD2412Component::set_gate_move_sensor(uint8_t gate, sensor::Sensor *s) {
869 this->gate_move_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
870}
871void LD2412Component::set_gate_still_sensor(uint8_t gate, sensor::Sensor *s) {
872 this->gate_still_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
873}
874#endif
875
876} // namespace esphome::ld2412
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:94
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:451
bool has_state() const
void set_config_mode_(bool enable)
Definition ld2412.cpp:705
std::array< number::Number *, TOTAL_GATES > gate_move_threshold_numbers_
Definition ld2412.h:130
std::array< SensorWithDedup< uint8_t > *, TOTAL_GATES > gate_move_sensors_
Definition ld2412.h:134
std::array< SensorWithDedup< uint8_t > *, TOTAL_GATES > gate_still_sensors_
Definition ld2412.h:135
std::array< number::Number *, TOTAL_GATES > gate_still_threshold_numbers_
Definition ld2412.h:131
uint8_t buffer_data_[MAX_LINE_LENGTH]
Definition ld2412.h:124
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len)
Definition ld2412.cpp:327
Base-class for all numbers.
Definition number.h:29
void publish_state(float state)
Definition number.cpp:22
optional< std::array< uint8_t, N > > read_array()
Definition uart.h:38
UARTComponent * parent_
Definition uart.h:73
void write_array(const uint8_t *data, size_t len)
Definition uart.h:26
bool state
Definition fan.h:2
uint8_t find_uint8(const StringToUint8(&arr)[N], const char *str)
Definition ld2412.cpp:134
constexpr Uint8ToString OUT_PIN_LEVELS_BY_UINT[]
Definition ld2412.cpp:126
std::function< void(void)> set_number_value(number::Number *n, float value)
Definition ld2412.cpp:458
constexpr Uint8ToString LIGHT_FUNCTIONS_BY_UINT[]
Definition ld2412.cpp:115
@ DISTANCE_RESOLUTION_0_5
Definition ld2412.cpp:30
@ DISTANCE_RESOLUTION_0_2
Definition ld2412.cpp:29
@ DISTANCE_RESOLUTION_0_75
Definition ld2412.cpp:31
const char * find_str(const Uint8ToString(&arr)[N], uint8_t value)
Definition ld2412.cpp:143
constexpr uint32_t BAUD_RATES[]
Definition ld2412.cpp:131
constexpr StringToUint8 BAUD_RATES_BY_STR[]
Definition ld2412.cpp:91
constexpr StringToUint8 LIGHT_FUNCTIONS_BY_STR[]
Definition ld2412.cpp:109
constexpr StringToUint8 DISTANCE_RESOLUTIONS_BY_STR[]
Definition ld2412.cpp:97
constexpr Uint8ToString DISTANCE_RESOLUTIONS_BY_UINT[]
Definition ld2412.cpp:103
constexpr StringToUint8 OUT_PIN_LEVELS_BY_STR[]
Definition ld2412.cpp:121
void format_version_str(const uint8_t *version, std::span< char, 20 > buffer)
Definition ld24xx.h:67
const char * format_mac_str(const uint8_t *mac_address, std::span< char, 18 > buffer)
Definition ld24xx.h:57
optional< size_t > find_index(const uint32_t(&arr)[N], uint32_t value)
Definition ld24xx.h:43
std::string size_t len
Definition helpers.h:892
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:353
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1200
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:728
void HOT delay(uint32_t ms)
Definition core.cpp:28
static void uint32_t