ESPHome 2026.1.5
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 while (this->available()) {
314 this->readline_(this->read());
315 }
316}
317
318void LD2412Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
319 ESP_LOGV(TAG, "Sending COMMAND %02X", command);
320 // frame header bytes
321 this->write_array(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
322 // length bytes
323 uint8_t len = 2;
324 if (command_value != nullptr) {
325 len += command_value_len;
326 }
327 // 2 length bytes (low, high) + 2 command bytes (low, high)
328 uint8_t len_cmd[] = {len, 0x00, command, 0x00};
329 this->write_array(len_cmd, sizeof(len_cmd));
330
331 // command value bytes
332 if (command_value != nullptr) {
333 this->write_array(command_value, command_value_len);
334 }
335 // frame footer bytes
336 this->write_array(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
337
338 if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
339 delay(30); // NOLINT
340 }
341 delay(20); // NOLINT
342}
343
345 // 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
346 // data header=0xAA, data footer=0x55, crc=0x00
347 if (this->buffer_pos_ < 12 || !ld2412::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
348 this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER) {
349 return;
350 }
351 /*
352 Data Type: 7th
353 0x01: Engineering mode
354 0x02: Normal mode
355 */
356 bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
357#ifdef USE_SWITCH
358 if (this->engineering_mode_switch_ != nullptr) {
359 this->engineering_mode_switch_->publish_state(engineering_mode);
360 }
361#endif
362
363#ifdef USE_BINARY_SENSOR
364 /*
365 Target states: 9th
366 0x00 = No target
367 0x01 = Moving targets
368 0x02 = Still targets
369 0x03 = Moving+Still targets
370 */
371 char target_state = this->buffer_data_[TARGET_STATES];
372 if (this->target_binary_sensor_ != nullptr) {
373 this->target_binary_sensor_->publish_state(target_state != 0x00);
374 }
375 if (this->moving_target_binary_sensor_ != nullptr) {
376 this->moving_target_binary_sensor_->publish_state(target_state & MOVE_BITMASK);
377 }
378 if (this->still_target_binary_sensor_ != nullptr) {
379 this->still_target_binary_sensor_->publish_state(target_state & STILL_BITMASK);
380 }
381#endif
382 /*
383 Moving target distance: 10~11th bytes
384 Moving target energy: 12th byte
385 Still target distance: 13~14th bytes
386 Still target energy: 15th byte
387 Detect distance: 16~17th bytes
388 */
389#ifdef USE_SENSOR
390 SAFE_PUBLISH_SENSOR(
391 this->moving_target_distance_sensor_,
392 ld2412::two_byte_to_int(this->buffer_data_[MOVING_TARGET_LOW], this->buffer_data_[MOVING_TARGET_HIGH]))
393 SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY])
394 SAFE_PUBLISH_SENSOR(
395 this->still_target_distance_sensor_,
396 ld2412::two_byte_to_int(this->buffer_data_[STILL_TARGET_LOW], this->buffer_data_[STILL_TARGET_HIGH]))
397 SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY])
398 if (this->detection_distance_sensor_ != nullptr) {
399 int new_detect_distance = 0;
400 if (target_state != 0x00 && (target_state & MOVE_BITMASK)) {
401 new_detect_distance =
402 ld2412::two_byte_to_int(this->buffer_data_[MOVING_TARGET_LOW], this->buffer_data_[MOVING_TARGET_HIGH]);
403 } else if (target_state != 0x00) {
404 new_detect_distance =
405 ld2412::two_byte_to_int(this->buffer_data_[STILL_TARGET_LOW], this->buffer_data_[STILL_TARGET_HIGH]);
406 }
407 this->detection_distance_sensor_->publish_state_if_not_dup(new_detect_distance);
408 }
409 if (engineering_mode) {
410 /*
411 Moving distance range: 18th byte
412 Still distance range: 19th byte
413 Moving energy: 20~28th bytes
414 */
415 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
416 SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i])
417 }
418 /*
419 Still energy: 29~37th bytes
420 */
421 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
422 SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i])
423 }
424 /*
425 Light sensor: 38th bytes
426 */
427 SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR])
428 } else {
429 for (auto &gate_move_sensor : this->gate_move_sensors_) {
430 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_move_sensor)
431 }
432 for (auto &gate_still_sensor : this->gate_still_sensors_) {
433 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_still_sensor)
434 }
435 SAFE_PUBLISH_SENSOR_UNKNOWN(this->light_sensor_)
436 }
437#endif
438 // the radar module won't tell us when it's done, so we just have to keep polling...
440 this->set_config_mode_(true);
442 this->set_config_mode_(false);
443 }
444}
445
446#ifdef USE_NUMBER
447std::function<void(void)> set_number_value(number::Number *n, float value) {
448 if (n != nullptr && (!n->has_state() || n->state != value)) {
449 n->state = value;
450 return [n, value]() { n->publish_state(value); };
451 }
452 return []() {};
453}
454#endif
455
457 ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
458 if (this->buffer_pos_ < 10) {
459 ESP_LOGW(TAG, "Invalid length");
460 return true;
461 }
462 if (!ld2412::validate_header_footer(CMD_FRAME_HEADER, this->buffer_data_)) {
463 char hex_buf[format_hex_pretty_size(HEADER_FOOTER_SIZE)];
464 ESP_LOGW(TAG, "Invalid header: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, HEADER_FOOTER_SIZE));
465 return true;
466 }
467 if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
468 ESP_LOGW(TAG, "Invalid status");
469 return true;
470 }
471 if (this->buffer_data_[8] || this->buffer_data_[9]) {
472 ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
473 return true;
474 }
475
476 switch (this->buffer_data_[COMMAND]) {
477 case CMD_ENABLE_CONF:
478 ESP_LOGV(TAG, "Enable conf");
479 break;
480
481 case CMD_DISABLE_CONF:
482 ESP_LOGV(TAG, "Disabled conf");
483 break;
484
485 case CMD_SET_BAUD_RATE:
486 ESP_LOGV(TAG, "Baud rate change");
487#ifdef USE_SELECT
488 if (this->baud_rate_select_ != nullptr) {
489 auto baud = this->baud_rate_select_->current_option();
490 ESP_LOGW(TAG, "Change baud rate to %.*s and reinstall", (int) baud.size(), baud.c_str());
491 }
492#endif
493 break;
494
495 case CMD_QUERY_VERSION: {
496 std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
497 char version_s[20];
498 ld24xx::format_version_str(this->version_, version_s);
499 ESP_LOGV(TAG, "Firmware version: %s", version_s);
500#ifdef USE_TEXT_SENSOR
501 if (this->version_text_sensor_ != nullptr) {
502 this->version_text_sensor_->publish_state(version_s);
503 }
504#endif
505 break;
506 }
507 case CMD_QUERY_DISTANCE_RESOLUTION: {
508 const auto *distance_resolution = find_str(DISTANCE_RESOLUTIONS_BY_UINT, this->buffer_data_[10]);
509 ESP_LOGV(TAG, "Distance resolution: %s", distance_resolution);
510#ifdef USE_SELECT
511 if (this->distance_resolution_select_ != nullptr) {
512 this->distance_resolution_select_->publish_state(distance_resolution);
513 }
514#endif
515 break;
516 }
517
518 case CMD_QUERY_LIGHT_CONTROL: {
519 this->light_function_ = this->buffer_data_[10];
520 this->light_threshold_ = this->buffer_data_[11];
521 const auto *light_function_str = find_str(LIGHT_FUNCTIONS_BY_UINT, this->light_function_);
522 ESP_LOGV(TAG,
523 "Light function: %s\n"
524 "Light threshold: %u",
525 light_function_str, this->light_threshold_);
526#ifdef USE_SELECT
527 if (this->light_function_select_ != nullptr) {
528 this->light_function_select_->publish_state(light_function_str);
529 }
530#endif
531#ifdef USE_NUMBER
532 if (this->light_threshold_number_ != nullptr) {
533 this->light_threshold_number_->publish_state(static_cast<float>(this->light_threshold_));
534 }
535#endif
536 break;
537 }
538
539 case CMD_QUERY_MAC_ADDRESS: {
540 if (this->buffer_pos_ < 20) {
541 return false;
542 }
543
544 this->bluetooth_on_ = std::memcmp(&this->buffer_data_[10], NO_MAC, sizeof(NO_MAC)) != 0;
545 if (this->bluetooth_on_) {
546 std::memcpy(this->mac_address_, &this->buffer_data_[10], sizeof(this->mac_address_));
547 }
548
549 char mac_s[18];
550 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
551 ESP_LOGV(TAG, "MAC address: %s", mac_str);
552#ifdef USE_TEXT_SENSOR
553 if (this->mac_text_sensor_ != nullptr) {
554 this->mac_text_sensor_->publish_state(mac_str);
555 }
556#endif
557#ifdef USE_SWITCH
558 if (this->bluetooth_switch_ != nullptr) {
559 this->bluetooth_switch_->publish_state(this->bluetooth_on_);
560 }
561#endif
562 break;
563 }
564
565 case CMD_SET_DISTANCE_RESOLUTION:
566 ESP_LOGV(TAG, "Handled set distance resolution command");
567 break;
568
569 case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
570 ESP_LOGV(TAG, "Handled query dynamic background correction");
571 bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
572#ifdef USE_BINARY_SENSOR
573 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
574 this->dynamic_background_correction_status_binary_sensor_->publish_state(dynamic_background_correction_active);
575 }
576#endif
577 this->dynamic_background_correction_active_ = dynamic_background_correction_active;
578 break;
579 }
580
581 case CMD_BLUETOOTH:
582 ESP_LOGV(TAG, "Handled bluetooth command");
583 break;
584
585 case CMD_SET_LIGHT_CONTROL:
586 ESP_LOGV(TAG, "Handled set light control command");
587 break;
588
589 case CMD_QUERY_MOTION_GATE_SENS: {
590#ifdef USE_NUMBER
591 std::vector<std::function<void(void)>> updates;
592 updates.reserve(this->gate_still_threshold_numbers_.size());
593 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
594 updates.push_back(set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[10 + i]));
595 }
596 for (auto &update : updates) {
597 update();
598 }
599#endif
600 break;
601 }
602
603 case CMD_QUERY_STATIC_GATE_SENS: {
604#ifdef USE_NUMBER
605 std::vector<std::function<void(void)>> updates;
606 updates.reserve(this->gate_still_threshold_numbers_.size());
607 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
608 updates.push_back(set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[10 + i]));
609 }
610 for (auto &update : updates) {
611 update();
612 }
613#endif
614 break;
615 }
616
617 case CMD_QUERY_BASIC_CONF: // Query parameters response
618 {
619#ifdef USE_NUMBER
620 /*
621 Moving distance range: 9th byte
622 Still distance range: 10th byte
623 */
624 std::vector<std::function<void(void)>> updates;
625 updates.push_back(set_number_value(this->min_distance_gate_number_, this->buffer_data_[10]));
626 updates.push_back(set_number_value(this->max_distance_gate_number_, this->buffer_data_[11] - 1));
627 ESP_LOGV(TAG, "min_distance_gate_number_: %u, max_distance_gate_number_ %u", this->buffer_data_[10],
628 this->buffer_data_[11]);
629 /*
630 None Duration: 11~12th bytes
631 */
632 updates.push_back(set_number_value(this->timeout_number_,
633 ld2412::two_byte_to_int(this->buffer_data_[12], this->buffer_data_[13])));
634 ESP_LOGV(TAG, "timeout_number_: %u", ld2412::two_byte_to_int(this->buffer_data_[12], this->buffer_data_[13]));
635 /*
636 Output pin configuration: 13th bytes
637 */
638 this->out_pin_level_ = this->buffer_data_[14];
639#ifdef USE_SELECT
640 const auto *out_pin_level_str = find_str(OUT_PIN_LEVELS_BY_UINT, this->out_pin_level_);
641 if (this->out_pin_level_select_ != nullptr) {
642 this->out_pin_level_select_->publish_state(out_pin_level_str);
643 }
644#endif
645 for (auto &update : updates) {
646 update();
647 }
648#endif
649 } break;
650 default:
651 break;
652 }
653
654 return true;
655}
656
658 if (readch < 0) {
659 return; // No data available
660 }
661 if (this->buffer_pos_ < HEADER_FOOTER_SIZE && readch != DATA_FRAME_HEADER[this->buffer_pos_] &&
662 readch != CMD_FRAME_HEADER[this->buffer_pos_]) {
663 this->buffer_pos_ = 0;
664 return;
665 }
666 if (this->buffer_pos_ < MAX_LINE_LENGTH - 1) {
667 this->buffer_data_[this->buffer_pos_++] = readch;
668 this->buffer_data_[this->buffer_pos_] = 0;
669 } else {
670 // We should never get here, but just in case...
671 ESP_LOGW(TAG, "Max command length exceeded; ignoring");
672 this->buffer_pos_ = 0;
673 }
674 if (this->buffer_pos_ < 4) {
675 return; // Not enough data to process yet
676 }
677 if (ld2412::validate_header_footer(DATA_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
678#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
679 char hex_buf[format_hex_pretty_size(MAX_LINE_LENGTH)];
680 ESP_LOGV(TAG, "Handling Periodic Data: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, this->buffer_pos_));
681#endif
682 this->handle_periodic_data_();
683 this->buffer_pos_ = 0; // Reset position index for next message
684 } else if (ld2412::validate_header_footer(CMD_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
685#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
686 char hex_buf[format_hex_pretty_size(MAX_LINE_LENGTH)];
687 ESP_LOGV(TAG, "Handling Ack Data: %s", format_hex_pretty_to(hex_buf, this->buffer_data_, this->buffer_pos_));
688#endif
689 if (this->handle_ack_data_()) {
690 this->buffer_pos_ = 0; // Reset position index for next message
691 } else {
692 ESP_LOGV(TAG, "Ack Data incomplete");
693 }
694 }
695}
696
698 const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF;
699 const uint8_t cmd_value[2] = {0x01, 0x00};
700 this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value));
701}
702
703void LD2412Component::set_bluetooth(bool enable) {
704 this->set_config_mode_(true);
705 const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00};
706 this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value));
707 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
708}
709
710void LD2412Component::set_distance_resolution(const char *state) {
711 this->set_config_mode_(true);
712 const uint8_t cmd_value[6] = {find_uint8(DISTANCE_RESOLUTIONS_BY_STR, state), 0x00, 0x00, 0x00, 0x00, 0x00};
713 this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, sizeof(cmd_value));
714 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
715}
716
717void LD2412Component::set_baud_rate(const char *state) {
718 this->set_config_mode_(true);
719 const uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00};
720 this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value));
721 this->set_timeout(200, [this]() { this->restart_(); });
722}
723
725 this->send_command_(CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
726}
727
728void LD2412Component::start_dynamic_background_correction() {
730 return; // Already in progress
731 }
732#ifdef USE_BINARY_SENSOR
733 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
734 this->dynamic_background_correction_status_binary_sensor_->publish_state(true);
735 }
736#endif
738 this->set_config_mode_(true);
739 this->send_command_(CMD_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
740 this->set_config_mode_(false);
741}
742
743void LD2412Component::set_engineering_mode(bool enable) {
744 const uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG;
745 this->set_config_mode_(true);
746 this->send_command_(cmd, nullptr, 0);
747 this->set_config_mode_(false);
748}
749
750void LD2412Component::factory_reset() {
751 this->set_config_mode_(true);
752 this->send_command_(CMD_FACTORY_RESET, nullptr, 0);
753 this->set_timeout(2000, [this]() { this->restart_and_read_all_info(); });
754}
755
756void LD2412Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); }
757
758void LD2412Component::query_parameters_() { this->send_command_(CMD_QUERY_BASIC_CONF, nullptr, 0); }
759
760void LD2412Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); }
761
763 const uint8_t cmd_value[2] = {0x01, 0x00};
764 this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, sizeof(cmd_value));
765}
766
767void LD2412Component::get_distance_resolution_() { this->send_command_(CMD_QUERY_DISTANCE_RESOLUTION, nullptr, 0); }
768
769void LD2412Component::query_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); }
770
771void LD2412Component::set_basic_config() {
772#ifdef USE_NUMBER
773 if (!this->min_distance_gate_number_->has_state() || !this->max_distance_gate_number_->has_state() ||
774 !this->timeout_number_->has_state()) {
775 return;
776 }
777#endif
778#ifdef USE_SELECT
779 if (!this->out_pin_level_select_->has_state()) {
780 return;
781 }
782#endif
783
784 uint8_t value[5] = {
785#ifdef USE_NUMBER
786 lowbyte(static_cast<int>(this->min_distance_gate_number_->state)),
787 lowbyte(static_cast<int>(this->max_distance_gate_number_->state) + 1),
788 lowbyte(static_cast<int>(this->timeout_number_->state)),
789 highbyte(static_cast<int>(this->timeout_number_->state)),
790#else
791 1, TOTAL_GATES, DEFAULT_PRESENCE_TIMEOUT, 0,
792#endif
793#ifdef USE_SELECT
794 find_uint8(OUT_PIN_LEVELS_BY_STR, this->out_pin_level_select_->current_option().c_str()),
795#else
796 0x01, // Default value if not using select
797#endif
798 };
799 this->set_config_mode_(true);
800 this->send_command_(CMD_BASIC_CONF, value, sizeof(value));
801 this->set_config_mode_(false);
802}
803
804#ifdef USE_NUMBER
805void LD2412Component::set_gate_threshold() {
806 if (this->gate_move_threshold_numbers_.empty() && this->gate_still_threshold_numbers_.empty()) {
807 return; // No gate threshold numbers set; nothing to do here
808 }
809 uint8_t value[TOTAL_GATES] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
810 this->set_config_mode_(true);
811 if (!this->gate_move_threshold_numbers_.empty()) {
812 for (size_t i = 0; i < this->gate_move_threshold_numbers_.size(); i++) {
813 value[i] = lowbyte(static_cast<int>(this->gate_move_threshold_numbers_[i]->state));
814 }
815 this->send_command_(CMD_MOTION_GATE_SENS, value, sizeof(value));
816 }
817 if (!this->gate_still_threshold_numbers_.empty()) {
818 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
819 value[i] = lowbyte(static_cast<int>(this->gate_still_threshold_numbers_[i]->state));
820 }
821 this->send_command_(CMD_STATIC_GATE_SENS, value, sizeof(value));
822 }
823 this->set_config_mode_(false);
824}
825
826void LD2412Component::get_gate_threshold() {
827 this->send_command_(CMD_QUERY_MOTION_GATE_SENS, nullptr, 0);
828 this->send_command_(CMD_QUERY_STATIC_GATE_SENS, nullptr, 0);
829}
830
831void LD2412Component::set_gate_still_threshold_number(uint8_t gate, number::Number *n) {
832 this->gate_still_threshold_numbers_[gate] = n;
833}
834
835void LD2412Component::set_gate_move_threshold_number(uint8_t gate, number::Number *n) {
836 this->gate_move_threshold_numbers_[gate] = n;
837}
838#endif
839
840void LD2412Component::set_light_out_control() {
841#ifdef USE_NUMBER
842 if (this->light_threshold_number_ != nullptr && this->light_threshold_number_->has_state()) {
843 this->light_threshold_ = static_cast<uint8_t>(this->light_threshold_number_->state);
844 }
845#endif
846#ifdef USE_SELECT
847 if (this->light_function_select_ != nullptr && this->light_function_select_->has_state()) {
848 this->light_function_ = find_uint8(LIGHT_FUNCTIONS_BY_STR, this->light_function_select_->current_option().c_str());
849 }
850#endif
851 uint8_t value[2] = {this->light_function_, this->light_threshold_};
852 this->set_config_mode_(true);
853 this->send_command_(CMD_SET_LIGHT_CONTROL, value, sizeof(value));
854 this->query_light_control_();
855 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
856}
857
858#ifdef USE_SENSOR
859// These could leak memory, but they are only set once prior to 'setup()' and should never be used again.
860void LD2412Component::set_gate_move_sensor(uint8_t gate, sensor::Sensor *s) {
861 this->gate_move_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
862}
863void LD2412Component::set_gate_still_sensor(uint8_t gate, sensor::Sensor *s) {
864 this->gate_still_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
865}
866#endif
867
868} // 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:445
bool has_state() const
void set_config_mode_(bool enable)
Definition ld2412.cpp:697
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:318
Base-class for all numbers.
Definition number.h:29
void publish_state(float state)
Definition number.cpp:31
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:0
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:447
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:595
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:334
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:830
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:26