ESPHome 2025.9.0-dev
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 {
14namespace ld2412 {
15
16static const char *const TAG = "ld2412";
17static const char *const UNKNOWN_MAC = "unknown";
18static const char *const VERSION_FMT = "%u.%02X.%02X%02X%02X%02X";
19
30
36
42
43enum OutPinLevel : uint8_t {
46};
47
48/*
49Data Type: 6th byte
50Target states: 9th byte
51 Moving target distance: 10~11th bytes
52 Moving target energy: 12th byte
53 Still target distance: 13~14th bytes
54 Still target energy: 15th byte
55 Detect distance: 16~17th bytes
56*/
71
72enum PeriodicDataValue : uint8_t {
73 HEADER = 0XAA,
74 FOOTER = 0x55,
75 CHECK = 0x00,
76};
77
78enum AckData : uint8_t {
81};
82
83// Memory-efficient lookup tables
84struct StringToUint8 {
85 const char *str;
86 const uint8_t value;
87};
88
89struct Uint8ToString {
90 const uint8_t value;
91 const char *str;
92};
93
94constexpr StringToUint8 BAUD_RATES_BY_STR[] = {
95 {"9600", BAUD_RATE_9600}, {"19200", BAUD_RATE_19200}, {"38400", BAUD_RATE_38400},
96 {"57600", BAUD_RATE_57600}, {"115200", BAUD_RATE_115200}, {"230400", BAUD_RATE_230400},
97 {"256000", BAUD_RATE_256000}, {"460800", BAUD_RATE_460800},
98};
99
100constexpr StringToUint8 DISTANCE_RESOLUTIONS_BY_STR[] = {
101 {"0.2m", DISTANCE_RESOLUTION_0_2},
102 {"0.5m", DISTANCE_RESOLUTION_0_5},
103 {"0.75m", DISTANCE_RESOLUTION_0_75},
104};
105
106constexpr Uint8ToString DISTANCE_RESOLUTIONS_BY_UINT[] = {
107 {DISTANCE_RESOLUTION_0_2, "0.2m"},
108 {DISTANCE_RESOLUTION_0_5, "0.5m"},
109 {DISTANCE_RESOLUTION_0_75, "0.75m"},
110};
111
112constexpr StringToUint8 LIGHT_FUNCTIONS_BY_STR[] = {
113 {"off", LIGHT_FUNCTION_OFF},
114 {"below", LIGHT_FUNCTION_BELOW},
115 {"above", LIGHT_FUNCTION_ABOVE},
116};
117
118constexpr Uint8ToString LIGHT_FUNCTIONS_BY_UINT[] = {
119 {LIGHT_FUNCTION_OFF, "off"},
120 {LIGHT_FUNCTION_BELOW, "below"},
121 {LIGHT_FUNCTION_ABOVE, "above"},
122};
123
124constexpr StringToUint8 OUT_PIN_LEVELS_BY_STR[] = {
125 {"low", OUT_PIN_LEVEL_LOW},
126 {"high", OUT_PIN_LEVEL_HIGH},
127};
128
129constexpr Uint8ToString OUT_PIN_LEVELS_BY_UINT[] = {
130 {OUT_PIN_LEVEL_LOW, "low"},
131 {OUT_PIN_LEVEL_HIGH, "high"},
132};
133
134// Helper functions for lookups
135template<size_t N> uint8_t find_uint8(const StringToUint8 (&arr)[N], const std::string &str) {
136 for (const auto &entry : arr) {
137 if (str == entry.str) {
138 return entry.value;
139 }
140 }
141 return 0xFF; // Not found
142}
143
144template<size_t N> const char *find_str(const Uint8ToString (&arr)[N], uint8_t value) {
145 for (const auto &entry : arr) {
146 if (value == entry.value) {
147 return entry.str;
148 }
149 }
150 return ""; // Not found
151}
152
153static constexpr uint8_t DEFAULT_PRESENCE_TIMEOUT = 5; // Default used when number component is not defined
154// Commands
155static constexpr uint8_t CMD_ENABLE_CONF = 0xFF;
156static constexpr uint8_t CMD_DISABLE_CONF = 0xFE;
157static constexpr uint8_t CMD_ENABLE_ENG = 0x62;
158static constexpr uint8_t CMD_DISABLE_ENG = 0x63;
159static constexpr uint8_t CMD_QUERY_BASIC_CONF = 0x12;
160static constexpr uint8_t CMD_BASIC_CONF = 0x02;
161static constexpr uint8_t CMD_QUERY_VERSION = 0xA0;
162static constexpr uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0x11;
163static constexpr uint8_t CMD_SET_DISTANCE_RESOLUTION = 0x01;
164static constexpr uint8_t CMD_QUERY_LIGHT_CONTROL = 0x1C;
165static constexpr uint8_t CMD_SET_LIGHT_CONTROL = 0x0C;
166static constexpr uint8_t CMD_SET_BAUD_RATE = 0xA1;
167static constexpr uint8_t CMD_QUERY_MAC_ADDRESS = 0xA5;
168static constexpr uint8_t CMD_FACTORY_RESET = 0xA2;
169static constexpr uint8_t CMD_RESTART = 0xA3;
170static constexpr uint8_t CMD_BLUETOOTH = 0xA4;
171static constexpr uint8_t CMD_DYNAMIC_BACKGROUND_CORRECTION = 0x0B;
172static constexpr uint8_t CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION = 0x1B;
173static constexpr uint8_t CMD_MOTION_GATE_SENS = 0x03;
174static constexpr uint8_t CMD_QUERY_MOTION_GATE_SENS = 0x13;
175static constexpr uint8_t CMD_STATIC_GATE_SENS = 0x04;
176static constexpr uint8_t CMD_QUERY_STATIC_GATE_SENS = 0x14;
177static constexpr uint8_t CMD_NONE = 0x00;
178// Commands values
179static constexpr uint8_t CMD_MAX_MOVE_VALUE = 0x00;
180static constexpr uint8_t CMD_MAX_STILL_VALUE = 0x01;
181static constexpr uint8_t CMD_DURATION_VALUE = 0x02;
182// Bitmasks for target states
183static constexpr uint8_t MOVE_BITMASK = 0x01;
184static constexpr uint8_t STILL_BITMASK = 0x02;
185// Header & Footer size
186static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
187// Command Header & Footer
188static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xFD, 0xFC, 0xFB, 0xFA};
189static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0x04, 0x03, 0x02, 0x01};
190// Data Header & Footer
191static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
192static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
193// MAC address the module uses when Bluetooth is disabled
194static constexpr uint8_t NO_MAC[] = {0x08, 0x05, 0x04, 0x03, 0x02, 0x01};
195
196static inline int two_byte_to_int(char firstbyte, char secondbyte) { return (int16_t) (secondbyte << 8) + firstbyte; }
197
198static inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
199 return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;
200}
201
202void LD2412Component::dump_config() {
203 std::string mac_str =
205 std::string version = str_sprintf(VERSION_FMT, this->version_[1], this->version_[0], this->version_[5],
206 this->version_[4], this->version_[3], this->version_[2]);
207 ESP_LOGCONFIG(TAG,
208 "LD2412:\n"
209 " Firmware version: %s\n"
210 " MAC address: %s",
211 version.c_str(), mac_str.c_str());
212#ifdef USE_BINARY_SENSOR
213 ESP_LOGCONFIG(TAG, "Binary Sensors:");
214 LOG_BINARY_SENSOR(" ", "DynamicBackgroundCorrectionStatus",
215 this->dynamic_background_correction_status_binary_sensor_);
216 LOG_BINARY_SENSOR(" ", "MovingTarget", this->moving_target_binary_sensor_);
217 LOG_BINARY_SENSOR(" ", "StillTarget", this->still_target_binary_sensor_);
218 LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_);
219#endif
220#ifdef USE_SENSOR
221 ESP_LOGCONFIG(TAG, "Sensors:");
222 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "Light", this->light_sensor_);
223 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "DetectionDistance", this->detection_distance_sensor_);
224 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "MovingTargetDistance", this->moving_target_distance_sensor_);
225 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "MovingTargetEnergy", this->moving_target_energy_sensor_);
226 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "StillTargetDistance", this->still_target_distance_sensor_);
227 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "StillTargetEnergy", this->still_target_energy_sensor_);
228 for (auto &s : this->gate_still_sensors_) {
229 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "GateStill", s);
230 }
231 for (auto &s : this->gate_move_sensors_) {
232 LOG_SENSOR_WITH_DEDUP_SAFE(" ", "GateMove", s);
233 }
234#endif
235#ifdef USE_TEXT_SENSOR
236 ESP_LOGCONFIG(TAG, "Text Sensors:");
237 LOG_TEXT_SENSOR(" ", "MAC address", this->mac_text_sensor_);
238 LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_);
239#endif
240#ifdef USE_NUMBER
241 ESP_LOGCONFIG(TAG, "Numbers:");
242 LOG_NUMBER(" ", "LightThreshold", this->light_threshold_number_);
243 LOG_NUMBER(" ", "MaxDistanceGate", this->max_distance_gate_number_);
244 LOG_NUMBER(" ", "MinDistanceGate", this->min_distance_gate_number_);
245 LOG_NUMBER(" ", "Timeout", this->timeout_number_);
246 for (number::Number *n : this->gate_move_threshold_numbers_) {
247 LOG_NUMBER(" ", "Move Thresholds", n);
248 }
249 for (number::Number *n : this->gate_still_threshold_numbers_) {
250 LOG_NUMBER(" ", "Still Thresholds", n);
251 }
252#endif
253#ifdef USE_SELECT
254 ESP_LOGCONFIG(TAG, "Selects:");
255 LOG_SELECT(" ", "BaudRate", this->baud_rate_select_);
256 LOG_SELECT(" ", "DistanceResolution", this->distance_resolution_select_);
257 LOG_SELECT(" ", "LightFunction", this->light_function_select_);
258 LOG_SELECT(" ", "OutPinLevel", this->out_pin_level_select_);
259#endif
260#ifdef USE_SWITCH
261 ESP_LOGCONFIG(TAG, "Switches:");
262 LOG_SWITCH(" ", "Bluetooth", this->bluetooth_switch_);
263 LOG_SWITCH(" ", "EngineeringMode", this->engineering_mode_switch_);
264#endif
265#ifdef USE_BUTTON
266 ESP_LOGCONFIG(TAG, "Buttons:");
267 LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_);
268 LOG_BUTTON(" ", "Query", this->query_button_);
269 LOG_BUTTON(" ", "Restart", this->restart_button_);
270 LOG_BUTTON(" ", "StartDynamicBackgroundCorrection", this->start_dynamic_background_correction_button_);
271#endif
272}
273
275 ESP_LOGCONFIG(TAG, "Running setup");
276 this->read_all_info();
277}
278
279void LD2412Component::read_all_info() {
280 this->set_config_mode_(true);
281 this->get_version_();
282 delay(10); // NOLINT
283 this->get_mac_();
284 delay(10); // NOLINT
286 delay(10); // NOLINT
287 this->query_parameters_();
288 delay(10); // NOLINT
290 delay(10); // NOLINT
291 this->query_light_control_();
292 delay(10); // NOLINT
293#ifdef USE_NUMBER
294 this->get_gate_threshold();
295 delay(10); // NOLINT
296#endif
297 this->set_config_mode_(false);
298#ifdef USE_SELECT
299 const auto baud_rate = std::to_string(this->parent_->get_baud_rate());
300 if (this->baud_rate_select_ != nullptr) {
301 this->baud_rate_select_->publish_state(baud_rate);
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 ESP_LOGW(TAG, "Invalid header: %s", format_hex_pretty(this->buffer_data_, HEADER_FOOTER_SIZE).c_str());
464 return true;
465 }
466 if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
467 ESP_LOGW(TAG, "Invalid status");
468 return true;
469 }
470 if (this->buffer_data_[8] || this->buffer_data_[9]) {
471 ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
472 return true;
473 }
474
475 switch (this->buffer_data_[COMMAND]) {
476 case CMD_ENABLE_CONF:
477 ESP_LOGV(TAG, "Enable conf");
478 break;
479
480 case CMD_DISABLE_CONF:
481 ESP_LOGV(TAG, "Disabled conf");
482 break;
483
484 case CMD_SET_BAUD_RATE:
485 ESP_LOGV(TAG, "Baud rate change");
486#ifdef USE_SELECT
487 if (this->baud_rate_select_ != nullptr) {
488 ESP_LOGW(TAG, "Change baud rate to %s and reinstall", this->baud_rate_select_->state.c_str());
489 }
490#endif
491 break;
492
493 case CMD_QUERY_VERSION: {
494 std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
495 std::string version = str_sprintf(VERSION_FMT, this->version_[1], this->version_[0], this->version_[5],
496 this->version_[4], this->version_[3], this->version_[2]);
497 ESP_LOGV(TAG, "Firmware version: %s", version.c_str());
498#ifdef USE_TEXT_SENSOR
499 if (this->version_text_sensor_ != nullptr) {
500 this->version_text_sensor_->publish_state(version);
501 }
502#endif
503 break;
504 }
505 case CMD_QUERY_DISTANCE_RESOLUTION: {
506 const auto *distance_resolution = find_str(DISTANCE_RESOLUTIONS_BY_UINT, this->buffer_data_[10]);
507 ESP_LOGV(TAG, "Distance resolution: %s", distance_resolution);
508#ifdef USE_SELECT
509 if (this->distance_resolution_select_ != nullptr) {
510 this->distance_resolution_select_->publish_state(distance_resolution);
511 }
512#endif
513 break;
514 }
515
516 case CMD_QUERY_LIGHT_CONTROL: {
517 this->light_function_ = this->buffer_data_[10];
518 this->light_threshold_ = this->buffer_data_[11];
519 const auto *light_function_str = find_str(LIGHT_FUNCTIONS_BY_UINT, this->light_function_);
520 ESP_LOGV(TAG,
521 "Light function: %s\n"
522 "Light threshold: %u",
523 light_function_str, this->light_threshold_);
524#ifdef USE_SELECT
525 if (this->light_function_select_ != nullptr) {
526 this->light_function_select_->publish_state(light_function_str);
527 }
528#endif
529#ifdef USE_NUMBER
530 if (this->light_threshold_number_ != nullptr) {
531 this->light_threshold_number_->publish_state(static_cast<float>(this->light_threshold_));
532 }
533#endif
534 break;
535 }
536
537 case CMD_QUERY_MAC_ADDRESS: {
538 if (this->buffer_pos_ < 20) {
539 return false;
540 }
541
542 this->bluetooth_on_ = std::memcmp(&this->buffer_data_[10], NO_MAC, sizeof(NO_MAC)) != 0;
543 if (this->bluetooth_on_) {
544 std::memcpy(this->mac_address_, &this->buffer_data_[10], sizeof(this->mac_address_));
545 }
546
547 std::string mac_str =
549 ESP_LOGV(TAG, "MAC address: %s", mac_str.c_str());
550#ifdef USE_TEXT_SENSOR
551 if (this->mac_text_sensor_ != nullptr) {
552 this->mac_text_sensor_->publish_state(mac_str);
553 }
554#endif
555#ifdef USE_SWITCH
556 if (this->bluetooth_switch_ != nullptr) {
557 this->bluetooth_switch_->publish_state(this->bluetooth_on_);
558 }
559#endif
560 break;
561 }
562
563 case CMD_SET_DISTANCE_RESOLUTION:
564 ESP_LOGV(TAG, "Handled set distance resolution command");
565 break;
566
567 case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
568 ESP_LOGV(TAG, "Handled query dynamic background correction");
569 bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
570#ifdef USE_BINARY_SENSOR
571 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
572 this->dynamic_background_correction_status_binary_sensor_->publish_state(dynamic_background_correction_active);
573 }
574#endif
575 this->dynamic_background_correction_active_ = dynamic_background_correction_active;
576 break;
577 }
578
579 case CMD_BLUETOOTH:
580 ESP_LOGV(TAG, "Handled bluetooth command");
581 break;
582
583 case CMD_SET_LIGHT_CONTROL:
584 ESP_LOGV(TAG, "Handled set light control command");
585 break;
586
587 case CMD_QUERY_MOTION_GATE_SENS: {
588#ifdef USE_NUMBER
589 std::vector<std::function<void(void)>> updates;
590 updates.reserve(this->gate_still_threshold_numbers_.size());
591 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
592 updates.push_back(set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[10 + i]));
593 }
594 for (auto &update : updates) {
595 update();
596 }
597#endif
598 break;
599 }
600
601 case CMD_QUERY_STATIC_GATE_SENS: {
602#ifdef USE_NUMBER
603 std::vector<std::function<void(void)>> updates;
604 updates.reserve(this->gate_still_threshold_numbers_.size());
605 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
606 updates.push_back(set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[10 + i]));
607 }
608 for (auto &update : updates) {
609 update();
610 }
611#endif
612 break;
613 }
614
615 case CMD_QUERY_BASIC_CONF: // Query parameters response
616 {
617#ifdef USE_NUMBER
618 /*
619 Moving distance range: 9th byte
620 Still distance range: 10th byte
621 */
622 std::vector<std::function<void(void)>> updates;
623 updates.push_back(set_number_value(this->min_distance_gate_number_, this->buffer_data_[10]));
624 updates.push_back(set_number_value(this->max_distance_gate_number_, this->buffer_data_[11] - 1));
625 ESP_LOGV(TAG, "min_distance_gate_number_: %u, max_distance_gate_number_ %u", this->buffer_data_[10],
626 this->buffer_data_[11]);
627 /*
628 None Duration: 11~12th bytes
629 */
630 updates.push_back(set_number_value(this->timeout_number_,
631 ld2412::two_byte_to_int(this->buffer_data_[12], this->buffer_data_[13])));
632 ESP_LOGV(TAG, "timeout_number_: %u", ld2412::two_byte_to_int(this->buffer_data_[12], this->buffer_data_[13]));
633 /*
634 Output pin configuration: 13th bytes
635 */
636 this->out_pin_level_ = this->buffer_data_[14];
637#ifdef USE_SELECT
638 const auto *out_pin_level_str = find_str(OUT_PIN_LEVELS_BY_UINT, this->out_pin_level_);
639 if (this->out_pin_level_select_ != nullptr) {
640 this->out_pin_level_select_->publish_state(out_pin_level_str);
641 }
642#endif
643 for (auto &update : updates) {
644 update();
645 }
646#endif
647 } break;
648 default:
649 break;
650 }
651
652 return true;
653}
654
656 if (readch < 0) {
657 return; // No data available
658 }
659 if (this->buffer_pos_ < HEADER_FOOTER_SIZE && readch != DATA_FRAME_HEADER[this->buffer_pos_] &&
660 readch != CMD_FRAME_HEADER[this->buffer_pos_]) {
661 this->buffer_pos_ = 0;
662 return;
663 }
664 if (this->buffer_pos_ < MAX_LINE_LENGTH - 1) {
665 this->buffer_data_[this->buffer_pos_++] = readch;
666 this->buffer_data_[this->buffer_pos_] = 0;
667 } else {
668 // We should never get here, but just in case...
669 ESP_LOGW(TAG, "Max command length exceeded; ignoring");
670 this->buffer_pos_ = 0;
671 }
672 if (this->buffer_pos_ < 4) {
673 return; // Not enough data to process yet
674 }
675 if (ld2412::validate_header_footer(DATA_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
676 ESP_LOGV(TAG, "Handling Periodic Data: %s", format_hex_pretty(this->buffer_data_, this->buffer_pos_).c_str());
677 this->handle_periodic_data_();
678 this->buffer_pos_ = 0; // Reset position index for next message
679 } else if (ld2412::validate_header_footer(CMD_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) {
680 ESP_LOGV(TAG, "Handling Ack Data: %s", format_hex_pretty(this->buffer_data_, this->buffer_pos_).c_str());
681 if (this->handle_ack_data_()) {
682 this->buffer_pos_ = 0; // Reset position index for next message
683 } else {
684 ESP_LOGV(TAG, "Ack Data incomplete");
685 }
686 }
687}
688
690 const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF;
691 const uint8_t cmd_value[2] = {0x01, 0x00};
692 this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value));
693}
694
695void LD2412Component::set_bluetooth(bool enable) {
696 this->set_config_mode_(true);
697 const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00};
698 this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value));
699 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
700}
701
702void LD2412Component::set_distance_resolution(const std::string &state) {
703 this->set_config_mode_(true);
704 const uint8_t cmd_value[6] = {find_uint8(DISTANCE_RESOLUTIONS_BY_STR, state), 0x00, 0x00, 0x00, 0x00, 0x00};
705 this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, sizeof(cmd_value));
706 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
707}
708
709void LD2412Component::set_baud_rate(const std::string &state) {
710 this->set_config_mode_(true);
711 const uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00};
712 this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value));
713 this->set_timeout(200, [this]() { this->restart_(); });
714}
715
717 this->send_command_(CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
718}
719
720void LD2412Component::start_dynamic_background_correction() {
722 return; // Already in progress
723 }
724#ifdef USE_BINARY_SENSOR
725 if (this->dynamic_background_correction_status_binary_sensor_ != nullptr) {
726 this->dynamic_background_correction_status_binary_sensor_->publish_state(true);
727 }
728#endif
730 this->set_config_mode_(true);
731 this->send_command_(CMD_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
732 this->set_config_mode_(false);
733}
734
735void LD2412Component::set_engineering_mode(bool enable) {
736 const uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG;
737 this->set_config_mode_(true);
738 this->send_command_(cmd, nullptr, 0);
739 this->set_config_mode_(false);
740}
741
742void LD2412Component::factory_reset() {
743 this->set_config_mode_(true);
744 this->send_command_(CMD_FACTORY_RESET, nullptr, 0);
745 this->set_timeout(2000, [this]() { this->restart_and_read_all_info(); });
746}
747
748void LD2412Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); }
749
750void LD2412Component::query_parameters_() { this->send_command_(CMD_QUERY_BASIC_CONF, nullptr, 0); }
751
752void LD2412Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); }
753
755 const uint8_t cmd_value[2] = {0x01, 0x00};
756 this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, sizeof(cmd_value));
757}
758
759void LD2412Component::get_distance_resolution_() { this->send_command_(CMD_QUERY_DISTANCE_RESOLUTION, nullptr, 0); }
760
761void LD2412Component::query_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); }
762
763void LD2412Component::set_basic_config() {
764#ifdef USE_NUMBER
765 if (!this->min_distance_gate_number_->has_state() || !this->max_distance_gate_number_->has_state() ||
766 !this->timeout_number_->has_state()) {
767 return;
768 }
769#endif
770#ifdef USE_SELECT
771 if (!this->out_pin_level_select_->has_state()) {
772 return;
773 }
774#endif
775
776 uint8_t value[5] = {
777#ifdef USE_NUMBER
778 lowbyte(static_cast<int>(this->min_distance_gate_number_->state)),
779 lowbyte(static_cast<int>(this->max_distance_gate_number_->state) + 1),
780 lowbyte(static_cast<int>(this->timeout_number_->state)),
781 highbyte(static_cast<int>(this->timeout_number_->state)),
782#else
783 1, TOTAL_GATES, DEFAULT_PRESENCE_TIMEOUT, 0,
784#endif
785#ifdef USE_SELECT
786 find_uint8(OUT_PIN_LEVELS_BY_STR, this->out_pin_level_select_->state),
787#else
788 0x01, // Default value if not using select
789#endif
790 };
791 this->set_config_mode_(true);
792 this->send_command_(CMD_BASIC_CONF, value, sizeof(value));
793 this->set_config_mode_(false);
794}
795
796#ifdef USE_NUMBER
797void LD2412Component::set_gate_threshold() {
798 if (this->gate_move_threshold_numbers_.empty() && this->gate_still_threshold_numbers_.empty()) {
799 return; // No gate threshold numbers set; nothing to do here
800 }
801 uint8_t value[TOTAL_GATES] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
802 this->set_config_mode_(true);
803 if (!this->gate_move_threshold_numbers_.empty()) {
804 for (size_t i = 0; i < this->gate_move_threshold_numbers_.size(); i++) {
805 value[i] = lowbyte(static_cast<int>(this->gate_move_threshold_numbers_[i]->state));
806 }
807 this->send_command_(CMD_MOTION_GATE_SENS, value, sizeof(value));
808 }
809 if (!this->gate_still_threshold_numbers_.empty()) {
810 for (size_t i = 0; i < this->gate_still_threshold_numbers_.size(); i++) {
811 value[i] = lowbyte(static_cast<int>(this->gate_still_threshold_numbers_[i]->state));
812 }
813 this->send_command_(CMD_STATIC_GATE_SENS, value, sizeof(value));
814 }
815 this->set_config_mode_(false);
816}
817
818void LD2412Component::get_gate_threshold() {
819 this->send_command_(CMD_QUERY_MOTION_GATE_SENS, nullptr, 0);
820 this->send_command_(CMD_QUERY_STATIC_GATE_SENS, nullptr, 0);
821}
822
823void LD2412Component::set_gate_still_threshold_number(uint8_t gate, number::Number *n) {
824 this->gate_still_threshold_numbers_[gate] = n;
825}
826
827void LD2412Component::set_gate_move_threshold_number(uint8_t gate, number::Number *n) {
828 this->gate_move_threshold_numbers_[gate] = n;
829}
830#endif
831
832void LD2412Component::set_light_out_control() {
833#ifdef USE_NUMBER
834 if (this->light_threshold_number_ != nullptr && this->light_threshold_number_->has_state()) {
835 this->light_threshold_ = static_cast<uint8_t>(this->light_threshold_number_->state);
836 }
837#endif
838#ifdef USE_SELECT
839 if (this->light_function_select_ != nullptr && this->light_function_select_->has_state()) {
840 this->light_function_ = find_uint8(LIGHT_FUNCTIONS_BY_STR, this->light_function_select_->state);
841 }
842#endif
843 uint8_t value[2] = {this->light_function_, this->light_threshold_};
844 this->set_config_mode_(true);
845 this->send_command_(CMD_SET_LIGHT_CONTROL, value, sizeof(value));
846 this->query_light_control_();
847 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
848}
849
850#ifdef USE_SENSOR
851// These could leak memory, but they are only set once prior to 'setup()' and should never be used again.
852void LD2412Component::set_gate_move_sensor(uint8_t gate, sensor::Sensor *s) {
853 this->gate_move_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
854}
855void LD2412Component::set_gate_still_sensor(uint8_t gate, sensor::Sensor *s) {
856 this->gate_still_sensors_[gate] = new SensorWithDedup<uint8_t>(s);
857}
858#endif
859
860} // namespace ld2412
861} // namespace esphome
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:85
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:78
void set_config_mode_(bool enable)
Definition ld2412.cpp:689
std::array< number::Number *, TOTAL_GATES > gate_move_threshold_numbers_
Definition ld2412.h:131
std::array< SensorWithDedup< uint8_t > *, TOTAL_GATES > gate_move_sensors_
Definition ld2412.h:135
std::array< SensorWithDedup< uint8_t > *, TOTAL_GATES > gate_still_sensors_
Definition ld2412.h:136
std::array< number::Number *, TOTAL_GATES > gate_still_threshold_numbers_
Definition ld2412.h:132
uint8_t buffer_data_[MAX_LINE_LENGTH]
Definition ld2412.h:125
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:39
void publish_state(float state)
Definition number.cpp:9
UARTComponent * parent_
Definition uart.h:68
void write_array(const uint8_t *data, size_t len)
Definition uart.h:21
bool state
Definition fan.h:0
constexpr Uint8ToString OUT_PIN_LEVELS_BY_UINT[]
Definition ld2412.cpp:129
uint8_t find_uint8(const StringToUint8(&arr)[N], const std::string &str)
Definition ld2412.cpp:135
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:118
@ DISTANCE_RESOLUTION_0_5
Definition ld2412.cpp:33
@ DISTANCE_RESOLUTION_0_2
Definition ld2412.cpp:32
@ DISTANCE_RESOLUTION_0_75
Definition ld2412.cpp:34
const char * find_str(const Uint8ToString(&arr)[N], uint8_t value)
Definition ld2412.cpp:144
constexpr StringToUint8 BAUD_RATES_BY_STR[]
Definition ld2412.cpp:94
constexpr StringToUint8 LIGHT_FUNCTIONS_BY_STR[]
Definition ld2412.cpp:112
constexpr StringToUint8 DISTANCE_RESOLUTIONS_BY_STR[]
Definition ld2412.cpp:100
constexpr Uint8ToString DISTANCE_RESOLUTIONS_BY_UINT[]
Definition ld2412.cpp:106
constexpr StringToUint8 OUT_PIN_LEVELS_BY_STR[]
Definition ld2412.cpp:124
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:594
std::string size_t len
Definition helpers.h:279
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:280
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:244
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:208
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29