ESPHome 2026.11.0b6
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
13
14#include <algorithm>
15#include <cmath>
16
17namespace esphome::ld2412 {
18
19ESPHOME_LOG_TAG(TAG, "ld2412");
20
26
27enum OutPinLevel : uint8_t {
30};
31
32/*
33Data Type: 6th byte
34Target states: 9th byte
35 Moving target distance: 10~11th bytes
36 Moving target energy: 12th byte
37 Still target distance: 13~14th bytes
38 Still target energy: 15th byte
39 Detect distance: 16~17th bytes
40*/
55
56enum PeriodicDataValue : uint8_t {
57 HEADER = 0XAA,
58 FOOTER = 0x55,
59 CHECK = 0x00,
60};
61
62enum AckData : uint8_t {
63 FRAME_LENGTH = 4, // little-endian count of the bytes between it and the footer
67};
68
69// Index + 1 is the BaudRate value; the select options use the same order
70PROGMEM_STRING_TABLE(BaudRateStrings, "9600", "19200", "38400", "57600", "115200", "230400", "256000", "460800");
71static_assert(BAUD_RATE_9600 == 1 && BAUD_RATE_460800 == BaudRateStrings::COUNT, "BaudRate is index + 1");
72// Same order as DISTANCE_RESOLUTIONS
73PROGMEM_STRING_TABLE(DistanceResolutionStrings, "0.2m", "0.5m", "0.75m");
74// The light function select options are in enum order
75static_assert(LIGHT_FUNCTION_OFF == 0 && LIGHT_FUNCTION_BELOW == 1 && LIGHT_FUNCTION_ABOVE == 2,
76 "LightFunction is the select option index");
77// Device values of the out pin level select options, in option order
78static constexpr uint8_t OUT_PIN_LEVELS[] PROGMEM = {OUT_PIN_LEVEL_LOW, OUT_PIN_LEVEL_HIGH};
79
80static constexpr uint32_t BAUD_RATES[] PROGMEM = {9600, 19200, 38400, 57600, 115200, 230400, 256000, 460800};
81
82// Commands
83static constexpr uint8_t CMD_ENABLE_CONF = 0xFF;
84static constexpr uint8_t CMD_DISABLE_CONF = 0xFE;
85static constexpr uint8_t CMD_ENABLE_ENG = 0x62;
86static constexpr uint8_t CMD_DISABLE_ENG = 0x63;
87static constexpr uint8_t CMD_QUERY_BASIC_CONF = 0x12;
88static constexpr uint8_t CMD_BASIC_CONF = 0x02;
89static constexpr uint8_t CMD_QUERY_VERSION = 0xA0;
90static constexpr uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0x11;
91static constexpr uint8_t CMD_SET_DISTANCE_RESOLUTION = 0x01;
92static constexpr uint8_t CMD_QUERY_LIGHT_CONTROL = 0x1C;
93static constexpr uint8_t CMD_SET_LIGHT_CONTROL = 0x0C;
94static constexpr uint8_t CMD_SET_BAUD_RATE = 0xA1;
95static constexpr uint8_t CMD_QUERY_MAC_ADDRESS = 0xA5;
96static constexpr uint8_t CMD_FACTORY_RESET = 0xA2;
97static constexpr uint8_t CMD_RESTART = 0xA3;
98static constexpr uint8_t CMD_BLUETOOTH = 0xA4;
99static constexpr uint8_t CMD_DYNAMIC_BACKGROUND_CORRECTION = 0x0B;
100static constexpr uint8_t CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION = 0x1B;
101static constexpr uint8_t CMD_MOTION_GATE_SENS = 0x03;
102static constexpr uint8_t CMD_QUERY_MOTION_GATE_SENS = 0x13;
103static constexpr uint8_t CMD_STATIC_GATE_SENS = 0x04;
104static constexpr uint8_t CMD_QUERY_STATIC_GATE_SENS = 0x14;
105static constexpr uint8_t CMD_NONE = 0x00;
106// Commands values
107static constexpr uint8_t CMD_MAX_MOVE_VALUE = 0x00;
108static constexpr uint8_t CMD_MAX_STILL_VALUE = 0x01;
109static constexpr uint8_t CMD_DURATION_VALUE = 0x02;
110// Bitmasks for target states
111static constexpr uint8_t MOVE_BITMASK = 0x01;
112static constexpr uint8_t STILL_BITMASK = 0x02;
113using ld24xx::CMD_FRAME_FOOTER;
114using ld24xx::CMD_FRAME_HEADER;
115using ld24xx::HEADER_FOOTER_SIZE;
117// Smallest frames whose values can all be read: the last value, data footer and check, then the frame footer
118static constexpr uint8_t PERIODIC_FRAME_MIN = STILL_ENERGY + 3 + HEADER_FOOTER_SIZE;
119static constexpr uint8_t ENGINEERING_FRAME_MIN = LIGHT_SENSOR + 3 + HEADER_FOOTER_SIZE;
120// Data Header & Footer
121static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
122static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
123static constexpr uint8_t GATE_SENS_ACK_SIZE = ACK_PAYLOAD + TOTAL_GATES + HEADER_FOOTER_SIZE;
124
125void LD2412Component::dump_config() {
126 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
127 char version_s[20];
128 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
129 ld24xx::format_version_str(this->version_, version_s);
130 ESP_LOGCONFIG(TAG,
131 "LD2412:\n"
132 " Firmware version: %s\n"
133 " MAC address: %s",
134 version_s, mac_str);
135#ifdef USE_BINARY_SENSOR
136 ESP_LOGCONFIG(TAG, "Binary Sensors:");
137 LOG_BINARY_SENSOR(" ", "DynamicBackgroundCorrectionStatus",
138 this->dynamic_background_correction_status_binary_sensor_);
139 LOG_BINARY_SENSOR(" ", "MovingTarget", this->moving_target_binary_sensor_);
140 LOG_BINARY_SENSOR(" ", "StillTarget", this->still_target_binary_sensor_);
141 LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_);
142#endif
143#ifdef USE_SENSOR
144 ESP_LOGCONFIG(TAG, "Sensors:");
145 LOG_SENSOR_WITH_DEDUP(" ", "Light", this->light_sensor_);
146 LOG_SENSOR_WITH_DEDUP(" ", "DetectionDistance", this->detection_distance_sensor_);
147 LOG_SENSOR_WITH_DEDUP(" ", "MovingTargetDistance", this->moving_target_distance_sensor_);
148 LOG_SENSOR_WITH_DEDUP(" ", "MovingTargetEnergy", this->moving_target_energy_sensor_);
149 LOG_SENSOR_WITH_DEDUP(" ", "StillTargetDistance", this->still_target_distance_sensor_);
150 LOG_SENSOR_WITH_DEDUP(" ", "StillTargetEnergy", this->still_target_energy_sensor_);
151 for (auto &s : this->gate_still_sensors_) {
152 LOG_SENSOR_WITH_DEDUP(" ", "GateStill", s);
153 }
154 for (auto &s : this->gate_move_sensors_) {
155 LOG_SENSOR_WITH_DEDUP(" ", "GateMove", s);
156 }
157#endif
158#ifdef USE_TEXT_SENSOR
159 ESP_LOGCONFIG(TAG, "Text Sensors:");
160 LOG_TEXT_SENSOR(" ", "MAC address", this->mac_text_sensor_);
161 LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_);
162#endif
163#ifdef USE_NUMBER
164 ESP_LOGCONFIG(TAG, "Numbers:");
165 LOG_NUMBER(" ", "LightThreshold", this->light_threshold_number_);
166 LOG_NUMBER(" ", "MaxDistanceGate", this->max_distance_gate_number_);
167 LOG_NUMBER(" ", "MinDistanceGate", this->min_distance_gate_number_);
168 LOG_NUMBER(" ", "Timeout", this->timeout_number_);
169 for (number::Number *n : this->gate_move_thresholds_.numbers) {
170 LOG_NUMBER(" ", "Move Thresholds", n);
171 }
172 for (number::Number *n : this->gate_still_thresholds_.numbers) {
173 LOG_NUMBER(" ", "Still Thresholds", n);
174 }
175#endif
176#ifdef USE_SELECT
177 ESP_LOGCONFIG(TAG, "Selects:");
178 LOG_SELECT(" ", "BaudRate", this->baud_rate_select_);
179 LOG_SELECT(" ", "DistanceResolution", this->distance_resolution_select_);
180 LOG_SELECT(" ", "LightFunction", this->light_function_select_);
181 LOG_SELECT(" ", "OutPinLevel", this->out_pin_level_select_);
182#endif
183#ifdef USE_SWITCH
184 ESP_LOGCONFIG(TAG, "Switches:");
185 LOG_SWITCH(" ", "Bluetooth", this->bluetooth_switch_);
186 LOG_SWITCH(" ", "EngineeringMode", this->engineering_mode_switch_);
187#endif
188#ifdef USE_BUTTON
189 ESP_LOGCONFIG(TAG, "Buttons:");
190 LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_);
191 LOG_BUTTON(" ", "Query", this->query_button_);
192 LOG_BUTTON(" ", "Restart", this->restart_button_);
193 LOG_BUTTON(" ", "StartDynamicBackgroundCorrection", this->start_dynamic_background_correction_button_);
194#endif
195}
196
198 ESP_LOGCONFIG(TAG, "Running setup");
199 this->read_all_info();
200}
201
202void LD2412Component::read_all_info() {
203 this->set_config_mode_(true);
204 this->get_version_();
205 delay(10); // NOLINT
206 this->get_mac_();
207 delay(10); // NOLINT
209 delay(10); // NOLINT
210 this->query_parameters_();
211 delay(10); // NOLINT
213 delay(10); // NOLINT
214 this->query_light_control_();
215 delay(10); // NOLINT
216#ifdef USE_NUMBER
217 this->get_gate_threshold();
218 delay(10); // NOLINT
219#endif
220 this->set_config_mode_(false);
221#ifdef USE_SELECT
222 if (this->baud_rate_select_ != nullptr) {
223 if (auto index = ld24xx::find_index(BAUD_RATES, this->parent_->get_baud_rate())) {
224 this->baud_rate_select_->publish_state(*index);
225 }
226 }
227#endif
228}
229
230void LD2412Component::restart_and_read_all_info() {
231 this->set_config_mode_(true);
232 this->restart_();
233 this->set_timeout(1000, [this]() { this->read_all_info(); });
234}
235
236void LD2412Component::loop() {
237 this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
238}
239
240void LD2412Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
241 ESP_LOGV(TAG, "Sending COMMAND %02X", command);
242 // frame header bytes
243 this->write_array(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
244 // length bytes
245 uint8_t len = 2;
246 if (command_value != nullptr) {
247 len += command_value_len;
248 }
249 // 2 length bytes (low, high) + 2 command bytes (low, high)
250 uint8_t len_cmd[] = {len, 0x00, command, 0x00};
251 this->write_array(len_cmd, sizeof(len_cmd));
252
253 // command value bytes
254 if (command_value != nullptr) {
255 this->write_array(command_value, command_value_len);
256 }
257 // frame footer bytes
258 this->write_array(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
259
260 if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
261 delay(30); // NOLINT
262 }
263 delay(20); // NOLINT
264}
265
267 // 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
268 // data header=0xAA, data footer=0x55, crc=0x00
269 if (this->buffer_pos_ < 12 || !ld2412::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
270 this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER) {
271 return;
272 }
273 /*
274 Data Type: 7th
275 0x01: Engineering mode
276 0x02: Normal mode
277 */
278 bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
279 if (this->buffer_pos_ < PERIODIC_FRAME_MIN) {
280 return; // too short to hold the values
281 }
282#ifdef USE_SWITCH
283 PUBLISH_STATE(this->engineering_mode_switch_, engineering_mode);
284#endif
285
286#ifdef USE_BINARY_SENSOR
287 /*
288 Target states: 9th
289 0x00 = No target
290 0x01 = Moving targets
291 0x02 = Still targets
292 0x03 = Moving+Still targets
293 */
294 char target_state = this->buffer_data_[TARGET_STATES];
295 PUBLISH_STATE(this->target_binary_sensor_, target_state != 0x00);
296 PUBLISH_STATE(this->moving_target_binary_sensor_, target_state & MOVE_BITMASK);
297 PUBLISH_STATE(this->still_target_binary_sensor_, target_state & STILL_BITMASK);
298#endif
299 /*
300 Moving target distance: 10~11th bytes
301 Moving target energy: 12th byte
302 Still target distance: 13~14th bytes
303 Still target energy: 15th byte
304 Detect distance: 16~17th bytes
305 */
306#ifdef USE_SENSOR
307 SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
309 SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY]);
310 SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
312 SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY]);
313 if (this->detection_distance_sensor_.has_sensor()) {
314 int new_detect_distance = 0;
315 if (target_state != 0x00 && (target_state & MOVE_BITMASK)) {
316 new_detect_distance =
317 encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]);
318 } else if (target_state != 0x00) {
319 new_detect_distance = encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]);
320 }
321 this->detection_distance_sensor_.publish_state_if_not_dup(new_detect_distance);
322 }
323 if (engineering_mode) {
324 if (this->buffer_pos_ < ENGINEERING_FRAME_MIN) {
325 ESP_LOGW(TAG, "Engineering mode packet too short: %u", this->buffer_pos_);
326 } else {
327 /*
328 Moving distance range: 18th byte
329 Still distance range: 19th byte
330 Moving energy: 20~28th bytes
331 */
332 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
333 SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i]);
334 }
335 /*
336 Still energy: 29~37th bytes
337 */
338 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
339 SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
340 }
341 /*
342 Light sensor value
343 */
344 SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
345 }
346 } else {
347 for (auto &gate_move_sensor : this->gate_move_sensors_) {
348 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_move_sensor);
349 }
350 for (auto &gate_still_sensor : this->gate_still_sensors_) {
351 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_still_sensor);
352 }
353 SAFE_PUBLISH_SENSOR_UNKNOWN(this->light_sensor_);
354 }
355#endif
356 // the radar module won't tell us when it's done, so we just have to keep polling...
358 this->set_config_mode_(true);
360 this->set_config_mode_(false);
361 }
362}
363
364#ifdef USE_NUMBER
366 if (n != nullptr && (!n->has_state() || n->state != value)) {
368 }
369}
370
371// NaN marks a value the module never received
372static inline bool has_value(number::Number *n) { return n != nullptr && n->has_state() && !std::isnan(n->state); }
373
374// Timeout ids 0 (still) and 1 (motion) for a write waiting on a re-query
375static constexpr uint32_t GATE_QUERY_TIMEOUT_ID = 0;
376#endif
377// Timeout id for a basic configuration write waiting on a re-query, and how long any such write waits
378static constexpr uint32_t BASIC_CONF_TIMEOUT_ID = 2;
379static constexpr uint32_t QUERY_TIMEOUT_MS = 2000;
380
382 ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
383 if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
384 ESP_LOGW(TAG, "Invalid status");
385 return;
386 }
387 if (this->buffer_data_[8] || this->buffer_data_[9]) {
388 ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
389 return;
390 }
391
392 switch (this->buffer_data_[COMMAND]) {
393 case CMD_ENABLE_CONF:
394 ESP_LOGV(TAG, "Enable conf");
395 break;
396
397 case CMD_DISABLE_CONF:
398 ESP_LOGV(TAG, "Disabled conf");
399 break;
400
401 case CMD_SET_BAUD_RATE:
402 ESP_LOGV(TAG, "Baud rate change");
403#ifdef USE_SELECT
404 if (this->baud_rate_select_ != nullptr) {
405 auto baud = this->baud_rate_select_->current_option();
406 ESP_LOGW(TAG, "Change baud rate to %.*s and reinstall", (int) baud.size(), baud.c_str());
407 }
408#endif
409 break;
410
411 case CMD_QUERY_VERSION: {
412 if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
413 break; // too short to hold a version
414 }
415 std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
416 char version_s[20];
417 ld24xx::format_version_str(this->version_, version_s);
418 ESP_LOGV(TAG, "Firmware version: %s", version_s);
419#ifdef USE_TEXT_SENSOR
420 PUBLISH_STATE(this->version_text_sensor_, version_s);
421#endif
422 break;
423 }
424 case CMD_QUERY_DISTANCE_RESOLUTION: {
425 if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
426 break; // too short to hold the resolution
427 }
428 const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
429 if (!index) {
430 ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
431 break;
432 }
433 ESP_LOGV(TAG, "Distance resolution: %s",
434 LOG_STR_ARG(DistanceResolutionStrings::get_log_str(*index, DistanceResolutionStrings::LAST_INDEX)));
435#ifdef USE_SELECT
436 PUBLISH_STATE(this->distance_resolution_select_, *index);
437#endif
438 break;
439 }
440
441 case CMD_QUERY_LIGHT_CONTROL: {
442 if (this->buffer_pos_ < 12 + HEADER_FOOTER_SIZE) {
443 break; // too short to hold the light settings
444 }
445 this->light_function_ = this->buffer_data_[10];
446 this->light_threshold_ = this->buffer_data_[11];
447 ESP_LOGV(TAG, "Light function: %u, threshold: %u", this->light_function_, this->light_threshold_);
448#ifdef USE_SELECT
449 PUBLISH_STATE(this->light_function_select_, static_cast<size_t>(this->light_function_));
450#endif
451#ifdef USE_NUMBER
452 PUBLISH_STATE(this->light_threshold_number_, static_cast<float>(this->light_threshold_));
453#endif
454 break;
455 }
456
457 case CMD_QUERY_MAC_ADDRESS: {
458 if (this->buffer_pos_ < 20) {
459 break; // too short to hold a MAC address
460 }
461
462 this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
463
464 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
465 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
466 ESP_LOGV(TAG, "MAC address: %s", mac_str);
467#ifdef USE_TEXT_SENSOR
468 PUBLISH_STATE(this->mac_text_sensor_, mac_str);
469#endif
470#ifdef USE_SWITCH
471 PUBLISH_STATE(this->bluetooth_switch_, this->bluetooth_on_);
472#endif
473 break;
474 }
475
476 case CMD_SET_DISTANCE_RESOLUTION:
477 ESP_LOGV(TAG, "Handled set distance resolution command");
478 break;
479
480 case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
481 if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
482 break; // too short to hold the state
483 }
484 ESP_LOGV(TAG, "Handled query dynamic background correction");
485 bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
486#ifdef USE_BINARY_SENSOR
487 PUBLISH_STATE(this->dynamic_background_correction_status_binary_sensor_, dynamic_background_correction_active);
488#endif
489 this->dynamic_background_correction_active_ = dynamic_background_correction_active;
490 break;
491 }
492
493 case CMD_BLUETOOTH:
494 ESP_LOGV(TAG, "Handled bluetooth command");
495 break;
496
497 case CMD_SET_LIGHT_CONTROL:
498 ESP_LOGV(TAG, "Handled set light control command");
499 break;
500
501 case CMD_QUERY_MOTION_GATE_SENS:
502 case CMD_QUERY_STATIC_GATE_SENS: {
503#ifdef USE_NUMBER
504 if (this->buffer_pos_ != GATE_SENS_ACK_SIZE) {
505 // A length this driver does not know
506 ESP_LOGW(TAG, "Dropping gate threshold answer of %u bytes", this->buffer_pos_);
507 return;
508 }
509 const bool motion = this->buffer_data_[COMMAND] == CMD_QUERY_MOTION_GATE_SENS;
510 GateThresholds &group = this->gate_thresholds_(motion);
511 // True only while a held-back write waits for this answer
512 const bool pending = this->cancel_timeout(GATE_QUERY_TIMEOUT_ID + motion);
513 for (size_t i = 0; i < TOTAL_GATES; i++) {
514 group.last_read[i] = this->buffer_data_[ACK_PAYLOAD + i];
515 // The pending write's user values must survive the answer
516 if (!pending || !has_value(group.numbers[i])) {
517 set_number_value(group.numbers[i], group.last_read[i]);
518 }
519 }
520 group.read = true;
521 if (pending) {
522 this->set_config_mode_(true);
523 this->send_gate_thresholds_(motion);
524 this->set_config_mode_(false);
525 }
526#endif
527 break;
528 }
529
530 case CMD_QUERY_BASIC_CONF: { // Query parameters response
531 if (this->buffer_pos_ < 15 + HEADER_FOOTER_SIZE) {
532 break; // too short to hold the configuration
533 }
534 // True only while a held-back write waits for this answer
535 const bool pending = this->cancel_timeout(BASIC_CONF_TIMEOUT_ID);
536 this->basic_conf_read_ = true;
537 // Min gate: 9th byte, max gate: 10th byte, timeout: 11~12th bytes, output pin level: 13th byte
538 this->min_gate_ = this->buffer_data_[10];
539 this->max_gate_ = this->buffer_data_[11];
540 this->timeout_ = encode_uint16(this->buffer_data_[13], this->buffer_data_[12]);
541 this->out_pin_level_ = this->buffer_data_[14];
542 ESP_LOGV(TAG, "min_distance_gate_number_: %u, max_distance_gate_number_ %u", this->min_gate_, this->max_gate_);
543 ESP_LOGV(TAG, "timeout_number_: %u", this->timeout_);
544 // The pending write's user values must survive the answer
545#ifdef USE_NUMBER
546 if (!pending || !has_value(this->min_distance_gate_number_)) {
547 set_number_value(this->min_distance_gate_number_, this->min_gate_);
548 }
549 if (!pending || !has_value(this->max_distance_gate_number_)) {
550 set_number_value(this->max_distance_gate_number_, this->max_gate_ - 1);
551 }
552 if (!pending || !has_value(this->timeout_number_)) {
553 set_number_value(this->timeout_number_, this->timeout_);
554 }
555#endif
556#ifdef USE_SELECT
557 if (this->out_pin_level_select_ != nullptr && !(pending && this->out_pin_level_select_->has_state())) {
558 if (const auto index = ld24xx::find_index(OUT_PIN_LEVELS, this->out_pin_level_)) {
559 this->out_pin_level_select_->publish_state(*index);
560 }
561 }
562#endif
563 if (pending) {
564 this->set_basic_config();
565 }
566 break;
567 }
568 default:
569 break;
570 }
571}
572
574 if (readch < 0) {
575 return; // No data available
576 }
577 // Periodic and command frames both carry their count after the header
579 this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld24xx::cmd_frame_length,
580 [this](uint8_t frame_len) { return this->handle_frame_(frame_len); }, []() { ESP_LOGW(TAG, "Invalid length"); });
581}
582
583// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
584bool LD2412Component::handle_frame_(uint8_t frame_len) {
585 this->buffer_pos_ = frame_len; // the handlers take the frame length from here
586 const uint8_t *tail = &this->buffer_data_[frame_len - HEADER_FOOTER_SIZE];
587 if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
588 if (!ld2412::validate_header_footer(DATA_FRAME_FOOTER, tail)) {
589 return false;
590 }
591 ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
592 this->handle_periodic_data_();
593 return true;
594 }
595 if (!ld2412::validate_header_footer(CMD_FRAME_FOOTER, tail)) {
596 return false;
597 }
598 ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
599 this->handle_ack_data_();
600 return true;
601}
602
604 const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF;
605 const uint8_t cmd_value[2] = {0x01, 0x00};
606 this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value));
607}
608
609void LD2412Component::set_bluetooth(bool enable) {
610 this->set_config_mode_(true);
611 const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00};
612 this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value));
613 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
614}
615
616void LD2412Component::set_distance_resolution(const char *state) {
618 if (index >= 0) {
619 this->set_distance_resolution(static_cast<DistanceResolution>(progmem_read_byte(&DISTANCE_RESOLUTIONS[index])));
620 }
621}
622
623void LD2412Component::set_distance_resolution(DistanceResolution resolution) {
624 this->set_config_mode_(true);
625 const uint8_t cmd_value[6] = {resolution, 0x00, 0x00, 0x00, 0x00, 0x00};
626 this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, sizeof(cmd_value));
627 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
628}
629
630void LD2412Component::set_baud_rate(const char *state) {
631 const int16_t index = progmem_string_table_find<BaudRateStrings>(state, strlen(state));
632 if (index >= 0) {
633 this->set_baud_rate(static_cast<BaudRate>(index + 1));
634 }
635}
636
637void LD2412Component::set_baud_rate(BaudRate rate) {
638 this->set_config_mode_(true);
639 const uint8_t cmd_value[2] = {rate, 0x00};
640 this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value));
641 this->set_timeout(200, [this]() { this->restart_(); });
642}
643
645 this->send_command_(CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
646}
647
648void LD2412Component::start_dynamic_background_correction() {
650 return; // Already in progress
651 }
652#ifdef USE_BINARY_SENSOR
653 PUBLISH_STATE(this->dynamic_background_correction_status_binary_sensor_, true);
654#endif
656 this->set_config_mode_(true);
657 this->send_command_(CMD_DYNAMIC_BACKGROUND_CORRECTION, nullptr, 0);
658 this->set_config_mode_(false);
659}
660
661void LD2412Component::set_engineering_mode(bool enable) {
662 const uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG;
663 this->set_config_mode_(true);
664 this->send_command_(cmd, nullptr, 0);
665 this->set_config_mode_(false);
666}
667
668void LD2412Component::factory_reset() {
669 this->set_config_mode_(true);
670 this->send_command_(CMD_FACTORY_RESET, nullptr, 0);
671 // Reset discards the settings; the next write must wait for the re-read
672 this->basic_conf_read_ = false;
673#ifdef USE_NUMBER
674 this->gate_move_thresholds_.read = false;
675 this->gate_still_thresholds_.read = false;
676#endif
677 this->set_timeout(2000, [this]() { this->restart_and_read_all_info(); });
678}
679
680void LD2412Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); }
681
682void LD2412Component::query_parameters_() { this->send_command_(CMD_QUERY_BASIC_CONF, nullptr, 0); }
683
684void LD2412Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); }
685
687 const uint8_t cmd_value[2] = {0x01, 0x00};
688 this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, sizeof(cmd_value));
689}
690
691void LD2412Component::get_distance_resolution_() { this->send_command_(CMD_QUERY_DISTANCE_RESOLUTION, nullptr, 0); }
692
693void LD2412Component::query_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); }
694
695void LD2412Component::set_basic_config() {
696 // Entities that are not configured keep what the module last reported
697 uint8_t min_gate = this->min_gate_;
698 uint8_t max_gate = this->max_gate_;
699 uint16_t timeout = this->timeout_;
700 uint8_t out_pin_level = this->out_pin_level_;
701 bool from_module = false;
702
703#ifdef USE_NUMBER
704 from_module = this->min_distance_gate_number_ == nullptr || this->max_distance_gate_number_ == nullptr ||
705 this->timeout_number_ == nullptr;
706#else
707 from_module = true;
708#endif
709#ifndef USE_SELECT
710 from_module = true;
711#endif
712
713#ifdef USE_NUMBER
714 if (this->min_distance_gate_number_ != nullptr) {
715 if (!this->min_distance_gate_number_->has_state())
716 return;
717 min_gate = static_cast<int>(this->min_distance_gate_number_->state);
718 }
719 if (this->max_distance_gate_number_ != nullptr) {
720 if (!this->max_distance_gate_number_->has_state())
721 return;
722 max_gate = static_cast<int>(this->max_distance_gate_number_->state) + 1;
723 }
724 if (this->timeout_number_ != nullptr) {
725 if (!this->timeout_number_->has_state())
726 return;
727 timeout = static_cast<int>(this->timeout_number_->state);
728 }
729#endif
730#ifdef USE_SELECT
731 if (this->out_pin_level_select_ != nullptr) {
732 const auto index = this->out_pin_level_select_->active_index();
733 if (!index)
734 return;
735 out_pin_level = progmem_read_byte(&OUT_PIN_LEVELS[*index]);
736 } else {
737 from_module = true;
738 }
739#endif
740 if (from_module && !this->basic_conf_read_) {
741 // The module never reported, so the values on hand are the built in defaults
742 ESP_LOGW(TAG, "Command %02X held back until the module reports its settings", CMD_BASIC_CONF);
743 this->set_config_mode_(true);
744 this->query_parameters_();
745 this->set_config_mode_(false);
746 this->set_timeout(BASIC_CONF_TIMEOUT_ID, QUERY_TIMEOUT_MS, [this]() { this->basic_conf_timeout_(); });
747 return;
748 }
749
750 uint8_t value[5] = {
751 lowbyte(min_gate), lowbyte(max_gate), lowbyte(timeout), highbyte(timeout), out_pin_level,
752 };
753 this->set_config_mode_(true);
754 this->send_command_(CMD_BASIC_CONF, value, sizeof(value));
755 this->set_config_mode_(false);
756}
757
759 ESP_LOGE(TAG, "Command %02X not sent, the module did not report its settings", CMD_BASIC_CONF);
760#ifdef USE_NUMBER
761 // The values on hand never reached the module, so forgetting them loses nothing
762 for (number::Number *n : {this->min_distance_gate_number_, this->max_distance_gate_number_, this->timeout_number_}) {
763 PUBLISH_STATE(n, NAN);
764 }
765#endif
766#ifdef USE_SELECT
767 // Show the last known or default level until the module reports one
768 if (this->out_pin_level_select_ != nullptr) {
769 if (const auto index = ld24xx::find_index(OUT_PIN_LEVELS, this->out_pin_level_)) {
770 this->out_pin_level_select_->publish_state(*index);
771 }
772 }
773#endif
774}
775
776#ifdef USE_NUMBER
778 GateThresholds &group = this->gate_thresholds_(motion);
779 const uint8_t command = motion ? CMD_MOTION_GATE_SENS : CMD_STATIC_GATE_SENS;
780 uint8_t value[TOTAL_GATES];
781 uint8_t configured = 0;
782 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
783 number::Number *n = group.numbers[i];
784 if (has_value(n)) {
785 value[i] = static_cast<uint8_t>(n->state);
786 configured++;
787 } else {
788 value[i] = group.last_read[i];
789 }
790 }
791 if (configured < TOTAL_GATES && !group.read) {
792 // Unread gates would go out as zero, which is maximum sensitivity
793 ESP_LOGW(TAG, "Command %02X held back until the module reports its settings", command);
794 this->send_command_(motion ? CMD_QUERY_MOTION_GATE_SENS : CMD_QUERY_STATIC_GATE_SENS, nullptr, 0);
795 this->set_timeout(GATE_QUERY_TIMEOUT_ID + motion, QUERY_TIMEOUT_MS,
796 [this, motion]() { this->gate_query_timeout_(motion); });
797 return;
798 }
799 this->send_command_(command, value, sizeof(value));
800}
801
803 ESP_LOGE(TAG, "Command %02X not sent, the module did not report its settings",
804 motion ? CMD_MOTION_GATE_SENS : CMD_STATIC_GATE_SENS);
805 // The values on hand never reached the module or are stale, so forgetting them loses nothing
806 for (number::Number *n : this->gate_thresholds_(motion).numbers) {
807 PUBLISH_STATE(n, NAN);
808 }
809}
810
811void LD2412Component::set_gate_threshold(number::Number *n) {
812 // Found by pointer: 14 compares per write beat a flag per number
813 const auto &motion_numbers = this->gate_move_thresholds_.numbers;
814 const bool motion = std::find(motion_numbers.begin(), motion_numbers.end(), n) != motion_numbers.end();
815 this->set_config_mode_(true);
816 this->send_gate_thresholds_(motion);
817 this->set_config_mode_(false);
818}
819
820void LD2412Component::get_gate_threshold() {
821 this->send_command_(CMD_QUERY_MOTION_GATE_SENS, nullptr, 0);
822 this->send_command_(CMD_QUERY_STATIC_GATE_SENS, nullptr, 0);
823}
824
825#endif
826
827void LD2412Component::set_light_out_control() {
828#ifdef USE_NUMBER
829 if (this->light_threshold_number_ != nullptr && this->light_threshold_number_->has_state()) {
830 this->light_threshold_ = static_cast<uint8_t>(this->light_threshold_number_->state);
831 }
832#endif
833#ifdef USE_SELECT
834 if (this->light_function_select_ != nullptr) {
835 if (const auto index = this->light_function_select_->active_index()) {
836 this->light_function_ = *index;
837 }
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
848void LD2412Component::set_gate_move_sensor(uint8_t gate, sensor::Sensor *s) {
849 this->gate_move_sensors_[gate].set_sensor(s);
850}
851void LD2412Component::set_gate_still_sensor(uint8_t gate, sensor::Sensor *s) {
852 this->gate_still_sensors_[gate].set_sensor(s);
853}
854#endif
855
856} // namespace esphome::ld2412
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
bool has_state() const
bool handle_frame_(uint8_t frame_len)
Definition ld2412.cpp:584
void set_config_mode_(bool enable)
Definition ld2412.cpp:603
void send_gate_thresholds_(bool motion)
Definition ld2412.cpp:777
std::array< sensor::SensorWithDedup< uint8_t >, TOTAL_GATES > gate_still_sensors_
Definition ld2412.h:183
GateThresholds & gate_thresholds_(bool motion)
Definition ld2412.h:156
std::array< sensor::SensorWithDedup< uint8_t >, TOTAL_GATES > gate_move_sensors_
Definition ld2412.h:182
void gate_query_timeout_(bool motion)
Definition ld2412.cpp:802
GateThresholds gate_still_thresholds_
Definition ld2412.h:179
uint8_t buffer_data_[MAX_LINE_LENGTH]
Definition ld2412.h:172
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len)
Definition ld2412.cpp:240
uint8_t mac_address_[MAC_ADDRESS_SIZE]
Definition ld2412.h:173
GateThresholds gate_move_thresholds_
Definition ld2412.h:178
Base-class for all numbers.
Definition number.h:29
void publish_state(float state)
Definition number.cpp:20
UARTComponent * parent_
Definition uart.h:134
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
bool state
Definition fan.h:2
Resolution resolution
Definition msa3xx.h:1
ESPHOME_LOG_TAG(TAG, "ld2412")
PROGMEM_STRING_TABLE(BaudRateStrings, "9600", "19200", "38400", "57600", "115200", "230400", "256000", "460800")
void set_number_value(number::Number *n, float value)
Definition ld2412.cpp:365
bool store_mac(const uint8_t *reported, uint8_t *mac_address)
Definition ld24xx.h:64
void format_version_str(const uint8_t *version, std::span< char, 20 > buffer)
Definition ld24xx.h:77
bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer)
Definition ld24xx.h:87
const char * format_mac_str(const uint8_t *mac_address, std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buffer)
Definition ld24xx.h:43
void feed_frame_byte(uint8_t(&buffer)[N], uint8_t &pos, uint8_t byte, const uint8_t *data_header, LengthFn frame_length, HandleFn handle_frame, DropFn on_drop)
Definition ld24xx.h:116
optional< size_t > find_index(const T(&arr)[N], T value)
Definition ld24xx.h:27
uint32_t cmd_frame_length(const uint8_t *buffer, uint8_t count)
Definition ld24xx.h:92
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
int16_t progmem_string_table_find(const char *value, size_t len)
The index of the string value (len bytes, in RAM) in a PROGMEM_STRING_TABLE, or -1 when it is not one...
Definition progmem.h:160
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1043
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51
static void uint32_t
std::array< uint8_t, TOTAL_GATES > last_read
Definition ld2412.h:153
std::array< number::Number *, TOTAL_GATES > numbers
Definition ld2412.h:152