ESPHome 2026.2.3
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 int two_byte_to_int(char firstbyte, char secondbyte) { return (int16_t) (secondbyte << 8) + firstbyte; }
196
197static inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
198 return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;
199}
200
201void LD2412Component::dump_config() {
202 char mac_s[18];
203 char version_s[20];
204 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
205 ld24xx::format_version_str(this->version_, version_s);
206 ESP_LOGCONFIG(TAG,
207 "LD2412:\n"
208 " Firmware version: %s\n"
209 " MAC address: %s",
210 version_s, mac_str);
211#ifdef USE_BINARY_SENSOR
212 ESP_LOGCONFIG(TAG, "Binary Sensors:");
213 LOG_BINARY_SENSOR(" ", "DynamicBackgroundCorrectionStatus",
214 this->dynamic_background_correction_status_binary_sensor_);
215 LOG_BINARY_SENSOR(" ", "MovingTarget", this->moving_target_binary_sensor_);
216 LOG_BINARY_SENSOR(" ", "StillTarget", this->still_target_binary_sensor_);
217 LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_);
218#endif
219#ifdef USE_SENSOR
220 ESP_LOGCONFIG(TAG, "Sensors:");
221 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "Light", this->light_sensor_);
222 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "DetectionDistance", this->detection_distance_sensor_);
223 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "MovingTargetDistance", this->moving_target_distance_sensor_);
224 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "MovingTargetEnergy", this->moving_target_energy_sensor_);
225 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "StillTargetDistance", this->still_target_distance_sensor_);
226 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "StillTargetEnergy", this->still_target_energy_sensor_);
227 for (auto &s : this->gate_still_sensors_) {
228 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "GateStill", s);
229 }
230 for (auto &s : this->gate_move_sensors_) {
231 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "GateMove", s);
232 }
233#endif
234#ifdef USE_TEXT_SENSOR
235 ESP_LOGCONFIG(TAG, "Text Sensors:");
236 LOG_TEXT_SENSOR(" ", "MAC address", this->mac_text_sensor_);
237 LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_);
238#endif
239#ifdef USE_NUMBER
240 ESP_LOGCONFIG(TAG, "Numbers:");
241 LOG_NUMBER(" ", "LightThreshold", this->light_threshold_number_);
242 LOG_NUMBER(" ", "MaxDistanceGate", this->max_distance_gate_number_);
243 LOG_NUMBER(" ", "MinDistanceGate", this->min_distance_gate_number_);
244 LOG_NUMBER(" ", "Timeout", this->timeout_number_);
245 for (number::Number *n : this->gate_move_threshold_numbers_) {
246 LOG_NUMBER(" ", "Move Thresholds", n);
247 }
248 for (number::Number *n : this->gate_still_threshold_numbers_) {
249 LOG_NUMBER(" ", "Still Thresholds", n);
250 }
251#endif
252#ifdef USE_SELECT
253 ESP_LOGCONFIG(TAG, "Selects:");
254 LOG_SELECT(" ", "BaudRate", this->baud_rate_select_);
255 LOG_SELECT(" ", "DistanceResolution", this->distance_resolution_select_);
256 LOG_SELECT(" ", "LightFunction", this->light_function_select_);
257 LOG_SELECT(" ", "OutPinLevel", this->out_pin_level_select_);
258#endif
259#ifdef USE_SWITCH
260 ESP_LOGCONFIG(TAG, "Switches:");
261 LOG_SWITCH(" ", "Bluetooth", this->bluetooth_switch_);
262 LOG_SWITCH(" ", "EngineeringMode", this->engineering_mode_switch_);
263#endif
264#ifdef USE_BUTTON
265 ESP_LOGCONFIG(TAG, "Buttons:");
266 LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_);
267 LOG_BUTTON(" ", "Query", this->query_button_);
268 LOG_BUTTON(" ", "Restart", this->restart_button_);
269 LOG_BUTTON(" ", "StartDynamicBackgroundCorrection", this->start_dynamic_background_correction_button_);
270#endif
271}
272
274 ESP_LOGCONFIG(TAG, "Running setup");
275 this->read_all_info();
276}
277
278void LD2412Component::read_all_info() {
279 this->set_config_mode_(true);
280 this->get_version_();
281 delay(10); // NOLINT
282 this->get_mac_();
283 delay(10); // NOLINT
285 delay(10); // NOLINT
286 this->query_parameters_();
287 delay(10); // NOLINT
289 delay(10); // NOLINT
290 this->query_light_control_();
291 delay(10); // NOLINT
292#ifdef USE_NUMBER
293 this->get_gate_threshold();
294 delay(10); // NOLINT
295#endif
296 this->set_config_mode_(false);
297#ifdef USE_SELECT
298 if (this->baud_rate_select_ != nullptr) {
299 if (auto index = ld24xx::find_index(BAUD_RATES, this->parent_->get_baud_rate())) {
300 this->baud_rate_select_->publish_state(*index);
301 }
302 }
303#endif
304}
305
306void LD2412Component::restart_and_read_all_info() {
307 this->set_config_mode_(true);
308 this->restart_();
309 this->set_timeout(1000, [this]() { this->read_all_info(); });
310}
311
312void LD2412Component::loop() {
313 // Read all available bytes in batches to reduce UART call overhead.
314 size_t avail = this->available();
315 uint8_t buf[MAX_LINE_LENGTH];
316 while (avail > 0) {
317 size_t to_read = std::min(avail, sizeof(buf));
318 if (!this->read_array(buf, to_read)) {
319 break;
320 }
321 avail -= to_read;
322
323 for (size_t i = 0; i < to_read; i++) {
324 this->readline_(buf[i]);
325 }
326 }
327}
328
329void LD2412Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
330 ESP_LOGV(TAG, "Sending COMMAND %02X", command);
331 // frame header bytes
332 this->write_array(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
333 // length bytes
334 uint8_t len = 2;
335 if (command_value != nullptr) {
336 len += command_value_len;
337 }
338 // 2 length bytes (low, high) + 2 command bytes (low, high)
339 uint8_t len_cmd[] = {len, 0x00, command, 0x00};
340 this->write_array(len_cmd, sizeof(len_cmd));
341
342 // command value bytes
343 if (command_value != nullptr) {
344 this->write_array(command_value, command_value_len);
345 }
346 // frame footer bytes
347 this->write_array(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
348
349 if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
350 delay(30); // NOLINT
351 }
352 delay(20); // NOLINT
353}
354
356 // 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
357 // data header=0xAA, data footer=0x55, crc=0x00
358 if (this->buffer_pos_ < 12 || !ld2412::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
359 this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER) {
360 return;
361 }
362 /*
363 Data Type: 7th
364 0x01: Engineering mode
365 0x02: Normal mode
366 */
367 bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
368#ifdef USE_SWITCH
369 if (this->engineering_mode_switch_ != nullptr) {
370 this->engineering_mode_switch_->publish_state(engineering_mode);
371 }
372#endif
373
374#ifdef USE_BINARY_SENSOR
375 /*
376 Target states: 9th
377 0x00 = No target
378 0x01 = Moving targets
379 0x02 = Still targets
380 0x03 = Moving+Still targets
381 */
382 char target_state = this->buffer_data_[TARGET_STATES];
383 if (this->target_binary_sensor_ != nullptr) {
384 this->target_binary_sensor_->publish_state(target_state != 0x00);
385 }
386 if (this->moving_target_binary_sensor_ != nullptr) {
387 this->moving_target_binary_sensor_->publish_state(target_state & MOVE_BITMASK);
388 }
389 if (this->still_target_binary_sensor_ != nullptr) {
390 this->still_target_binary_sensor_->publish_state(target_state & STILL_BITMASK);
391 }
392#endif
393 /*
394 Moving target distance: 10~11th bytes
395 Moving target energy: 12th byte
396 Still target distance: 13~14th bytes
397 Still target energy: 15th byte
398 Detect distance: 16~17th bytes
399 */
400#ifdef USE_SENSOR
401 SAFE_PUBLISH_SENSOR(
402 this->moving_target_distance_sensor_,
403 ld2412::two_byte_to_int(this->buffer_data_[MOVING_TARGET_LOW], this->buffer_data_[MOVING_TARGET_HIGH]))
404 SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY])
405 SAFE_PUBLISH_SENSOR(
406 this->still_target_distance_sensor_,
407 ld2412::two_byte_to_int(this->buffer_data_[STILL_TARGET_LOW], this->buffer_data_[STILL_TARGET_HIGH]))
408 SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY])
409 if (this->detection_distance_sensor_ != nullptr) {
410 int new_detect_distance = 0;
411 if (target_state != 0x00 && (target_state & MOVE_BITMASK)) {
412 new_detect_distance =
413 ld2412::two_byte_to_int(this->buffer_data_[MOVING_TARGET_LOW], this->buffer_data_[MOVING_TARGET_HIGH]);
414 } else if (target_state != 0x00) {
415 new_detect_distance =
416 ld2412::two_byte_to_int(this->buffer_data_[STILL_TARGET_LOW], this->buffer_data_[STILL_TARGET_HIGH]);
417 }
418 this->detection_distance_sensor_->publish_state_if_not_dup(new_detect_distance);
419 }
420 if (engineering_mode) {
421 /*
422 Moving distance range: 18th byte
423 Still distance range: 19th byte
424 Moving energy: 20~28th bytes
425 */
426 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
427 SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i])
428 }
429 /*
430 Still energy: 29~37th bytes
431 */
432 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
433 SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i])
434 }
435 /*
436 Light sensor: 38th bytes
437 */
438 SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR])
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,
534 "Light function: %s\n"
535 "Light threshold: %u",
536 light_function_str, this->light_threshold_);
537#ifdef USE_SELECT
538 if (this->light_function_select_ != nullptr) {
539 this->light_function_select_->publish_state(light_function_str);
540 }
541#endif
542#ifdef USE_NUMBER
543 if (this->light_threshold_number_ != nullptr) {
544 this->light_threshold_number_->publish_state(static_cast<float>(this->light_threshold_));
545 }
546#endif
547 break;
548 }
549
550 case CMD_QUERY_MAC_ADDRESS: {
551 if (this->buffer_pos_ < 20) {
552 return false;
553 }
554
555 this->bluetooth_on_ = std::memcmp(&this->buffer_data_[10], NO_MAC, sizeof(NO_MAC)) != 0;
556 if (this->bluetooth_on_) {
557 std::memcpy(this->mac_address_, &this->buffer_data_[10], sizeof(this->mac_address_));
558 }
559
560 char mac_s[18];
561 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
562 ESP_LOGV(TAG, "MAC address: %s", mac_str);
563#ifdef USE_TEXT_SENSOR
564 if (this->mac_text_sensor_ != nullptr) {
565 this->mac_text_sensor_->publish_state(mac_str);
566 }
567#endif
568#ifdef USE_SWITCH
569 if (this->bluetooth_switch_ != nullptr) {
570 this->bluetooth_switch_->publish_state(this->bluetooth_on_);
571 }
572#endif
573 break;
574 }
575
576 case CMD_SET_DISTANCE_RESOLUTION:
577 ESP_LOGV(TAG, "Handled set distance resolution command");
578 break;
579
580 case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
581 ESP_LOGV(TAG, "Handled query dynamic background correction");
582 bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
583#ifdef USE_BINARY_SENSOR
584 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
585 this->dynamic_background_correction_status_binary_sensor_->publish_state(dynamic_background_correction_active);
586 }
587#endif
588 this->dynamic_background_correction_active_ = dynamic_background_correction_active;
589 break;
590 }
591
592 case CMD_BLUETOOTH:
593 ESP_LOGV(TAG, "Handled bluetooth command");
594 break;
595
596 case CMD_SET_LIGHT_CONTROL:
597 ESP_LOGV(TAG, "Handled set light control command");
598 break;
599
600 case CMD_QUERY_MOTION_GATE_SENS: {
601#ifdef USE_NUMBER
602 std::vector<std::function<void(void)>> updates;
603 updates.reserve(this->gate_still_threshold_numbers_.size());
604 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
605 updates.push_back(set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[10 + i]));
606 }
607 for (auto &update : updates) {
608 update();
609 }
610#endif
611 break;
612 }
613
614 case CMD_QUERY_STATIC_GATE_SENS: {
615#ifdef USE_NUMBER
616 std::vector<std::function<void(void)>> updates;
617 updates.reserve(this->gate_still_threshold_numbers_.size());
618 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
619 updates.push_back(set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[10 + i]));
620 }
621 for (auto &update : updates) {
622 update();
623 }
624#endif
625 break;
626 }
627
628 case CMD_QUERY_BASIC_CONF: // Query parameters response
629 {
630#ifdef USE_NUMBER
631 /*
632 Moving distance range: 9th byte
633 Still distance range: 10th byte
634 */
635 std::vector<std::function<void(void)>> updates;
636 updates.push_back(set_number_value(this->min_distance_gate_number_, this->buffer_data_[10]));
637 updates.push_back(set_number_value(this->max_distance_gate_number_, this->buffer_data_[11] - 1));
638 ESP_LOGV(TAG, "min_distance_gate_number_: %u, max_distance_gate_number_ %u", this->buffer_data_[10],
639 this->buffer_data_[11]);
640 /*
641 None Duration: 11~12th bytes
642 */
643 updates.push_back(set_number_value(this->timeout_number_,
644 ld2412::two_byte_to_int(this->buffer_data_[12], this->buffer_data_[13])));
645 ESP_LOGV(TAG, "timeout_number_: %u", ld2412::two_byte_to_int(this->buffer_data_[12], this->buffer_data_[13]));
646 /*
647 Output pin configuration: 13th bytes
648 */
649 this->out_pin_level_ = this->buffer_data_[14];
650#ifdef USE_SELECT
651 const auto *out_pin_level_str = find_str(OUT_PIN_LEVELS_BY_UINT, this->out_pin_level_);
652 if (this->out_pin_level_select_ != nullptr) {
653 this->out_pin_level_select_->publish_state(out_pin_level_str);
654 }
655#endif
656 for (auto &update : updates) {
657 update();
658 }
659#endif
660 } break;
661 default:
662 break;
663 }
664
665 return true;
666}
667
669 if (readch < 0) {
670 return; // No data available
671 }
672 if (this->buffer_pos_ < HEADER_FOOTER_SIZE && readch != DATA_FRAME_HEADER[this->buffer_pos_] &&
673 readch != CMD_FRAME_HEADER[this->buffer_pos_]) {
674 this->buffer_pos_ = 0;
675 return;
676 }
677 if (this->buffer_pos_ < MAX_LINE_LENGTH - 1) {
678 this->buffer_data_[this->buffer_pos_++] = readch;
679 this->buffer_data_[this->buffer_pos_] = 0;
680 } else {
681 // We should never get here, but just in case...
682 ESP_LOGW(TAG, "Max command length exceeded; ignoring");
683 this->buffer_pos_ = 0;
684 }
685 if (this->buffer_pos_ < 4) {
686 return; // Not enough data to process yet
687 }
688 if (ld2412::validate_header_footer(DATA_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
689#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
690 char hex_buf[format_hex_pretty_size(MAX_LINE_LENGTH)];
691 ESP_LOGV(TAG, "Handling Periodic Data: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, this->buffer_pos_));
692#endif
693 this->handle_periodic_data_();
694 this->buffer_pos_ = 0; // Reset position index for next message
695 } else if (ld2412::validate_header_footer(CMD_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
696#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
697 char hex_buf[format_hex_pretty_size(MAX_LINE_LENGTH)];
698 ESP_LOGV(TAG, "Handling Ack Data: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, this->buffer_pos_));
699#endif
700 if (this->handle_ack_data_()) {
701 this->buffer_pos_ = 0; // Reset position index for next message
702 } else {
703 ESP_LOGV(TAG, "Ack Data incomplete");
704 }
705 }
706}
707
709 const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF;
710 const uint8_t cmd_value[2] = {0x01, 0x00};
711 this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value));
712}
713
714void LD2412Component::set_bluetooth(bool enable) {
715 this->set_config_mode_(true);
716 const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00};
717 this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value));
718 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
719}
720
721void LD2412Component::set_distance_resolution(const char *state) {
722 this->set_config_mode_(true);
723 const uint8_t cmd_value[6] = {find_uint8(DISTANCE_RESOLUTIONS_BY_STR, state), 0x00, 0x00, 0x00, 0x00, 0x00};
724 this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, sizeof(cmd_value));
725 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
726}
727
728void LD2412Component::set_baud_rate(const char *state) {
729 this->set_config_mode_(true);
730 const uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00};
731 this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value));
732 this->set_timeout(200, [this]() { this->restart_(); });
733}
734
736 this->send_command_(CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
737}
738
739void LD2412Component::start_dynamic_background_correction() {
741 return; // Already in progress
742 }
743#ifdef USE_BINARY_SENSOR
744 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
745 this->dynamic_background_correction_status_binary_sensor_->publish_state(true);
746 }
747#endif
749 this->set_config_mode_(true);
750 this->send_command_(CMD_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
751 this->set_config_mode_(false);
752}
753
754void LD2412Component::set_engineering_mode(bool enable) {
755 const uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG;
756 this->set_config_mode_(true);
757 this->send_command_(cmd, nullptr, 0);
758 this->set_config_mode_(false);
759}
760
761void LD2412Component::factory_reset() {
762 this->set_config_mode_(true);
763 this->send_command_(CMD_FACTORY_RESET, nullptr, 0);
764 this->set_timeout(2000, [this]() { this->restart_and_read_all_info(); });
765}
766
767void LD2412Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); }
768
769void LD2412Component::query_parameters_() { this->send_command_(CMD_QUERY_BASIC_CONF, nullptr, 0); }
770
771void LD2412Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); }
772
774 const uint8_t cmd_value[2] = {0x01, 0x00};
775 this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, sizeof(cmd_value));
776}
777
778void LD2412Component::get_distance_resolution_() { this->send_command_(CMD_QUERY_DISTANCE_RESOLUTION, nullptr, 0); }
779
780void LD2412Component::query_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); }
781
782void LD2412Component::set_basic_config() {
783#ifdef USE_NUMBER
784 if (!this->min_distance_gate_number_->has_state() || !this->max_distance_gate_number_->has_state() ||
785 !this->timeout_number_->has_state()) {
786 return;
787 }
788#endif
789#ifdef USE_SELECT
790 if (!this->out_pin_level_select_->has_state()) {
791 return;
792 }
793#endif
794
795 uint8_t value[5] = {
796#ifdef USE_NUMBER
797 lowbyte(static_cast<int>(this->min_distance_gate_number_->state)),
798 lowbyte(static_cast<int>(this->max_distance_gate_number_->state) + 1),
799 lowbyte(static_cast<int>(this->timeout_number_->state)),
800 highbyte(static_cast<int>(this->timeout_number_->state)),
801#else
802 1, TOTAL_GATES, DEFAULT_PRESENCE_TIMEOUT, 0,
803#endif
804#ifdef USE_SELECT
805 find_uint8(OUT_PIN_LEVELS_BY_STR, this->out_pin_level_select_->current_option().c_str()),
806#else
807 0x01, // Default value if not using select
808#endif
809 };
810 this->set_config_mode_(true);
811 this->send_command_(CMD_BASIC_CONF, value, sizeof(value));
812 this->set_config_mode_(false);
813}
814
815#ifdef USE_NUMBER
816void LD2412Component::set_gate_threshold() {
817 if (this->gate_move_threshold_numbers_.empty() && this->gate_still_threshold_numbers_.empty()) {
818 return; // No gate threshold numbers set; nothing to do here
819 }
820 uint8_t value[TOTAL_GATES] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
821 this->set_config_mode_(true);
822 if (!this->gate_move_threshold_numbers_.empty()) {
823 for (size_t i = 0; i < this->gate_move_threshold_numbers_.size(); i++) {
824 value[i] = lowbyte(static_cast<int>(this->gate_move_threshold_numbers_[i]->state));
825 }
826 this->send_command_(CMD_MOTION_GATE_SENS, value, sizeof(value));
827 }
828 if (!this->gate_still_threshold_numbers_.empty()) {
829 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
830 value[i] = lowbyte(static_cast<int>(this->gate_still_threshold_numbers_[i]->state));
831 }
832 this->send_command_(CMD_STATIC_GATE_SENS, value, sizeof(value));
833 }
834 this->set_config_mode_(false);
835}
836
837void LD2412Component::get_gate_threshold() {
838 this->send_command_(CMD_QUERY_MOTION_GATE_SENS, nullptr, 0);
839 this->send_command_(CMD_QUERY_STATIC_GATE_SENS, nullptr, 0);
840}
841
842void LD2412Component::set_gate_still_threshold_number(uint8_t gate, number::Number *n) {
843 this->gate_still_threshold_numbers_[gate] = n;
844}
845
846void LD2412Component::set_gate_move_threshold_number(uint8_t gate, number::Number *n) {
847 this->gate_move_threshold_numbers_[gate] = n;
848}
849#endif
850
851void LD2412Component::set_light_out_control() {
852#ifdef USE_NUMBER
853 if (this->light_threshold_number_ != nullptr && this->light_threshold_number_->has_state()) {
854 this->light_threshold_ = static_cast<uint8_t>(this->light_threshold_number_->state);
855 }
856#endif
857#ifdef USE_SELECT
858 if (this->light_function_select_ != nullptr && this->light_function_select_->has_state()) {
859 this->light_function_ = find_uint8(LIGHT_FUNCTIONS_BY_STR, this->light_function_select_->current_option().c_str());
860 }
861#endif
862 uint8_t value[2] = {this->light_function_, this->light_threshold_};
863 this->set_config_mode_(true);
864 this->send_command_(CMD_SET_LIGHT_CONTROL, value, sizeof(value));
865 this->query_light_control_();
866 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
867}
868
869#ifdef USE_SENSOR
870// These could leak memory, but they are only set once prior to 'setup()' and should never be used again.
871void LD2412Component::set_gate_move_sensor(uint8_t gate, sensor::Sensor *s) {
872 this->gate_move_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
873}
874void LD2412Component::set_gate_still_sensor(uint8_t gate, sensor::Sensor *s) {
875 this->gate_still_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
876}
877#endif
878
879} // namespace esphome::ld2412
virtual void setup()
Where the component's initialization should happen.
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:429
bool has_state() const
void set_config_mode_(bool enable)
Definition ld2412.cpp:708
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:329
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:692
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:978
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:26