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