ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ld2410.cpp
Go to the documentation of this file.
1#include "ld2410.h"
2
3#ifdef USE_NUMBER
5#endif
6#ifdef USE_SENSOR
8#endif
9
13
14namespace esphome::ld2410 {
15
16ESPHOME_LOG_TAG(TAG, "ld2410");
17
23
24enum OutPinLevel : uint8_t {
27};
28
45
46enum PeriodicDataValue : uint8_t {
47 HEADER = 0xAA,
48 FOOTER = 0x55,
49 CHECK = 0x00,
50};
51
52enum AckData : uint8_t {
55};
56
57// Index + 1 is the BaudRate value; the select options use the same order
58PROGMEM_STRING_TABLE(BaudRateStrings, "9600", "19200", "38400", "57600", "115200", "230400", "256000", "460800");
59static_assert(BAUD_RATE_9600 == 1 && BAUD_RATE_460800 == BaudRateStrings::COUNT, "BaudRate is index + 1");
60// Same order as DISTANCE_RESOLUTIONS
61PROGMEM_STRING_TABLE(DistanceResolutionStrings, "0.2m", "0.75m");
62// The light function and out pin level select options are in enum order
63static_assert(LIGHT_FUNCTION_OFF == 0 && LIGHT_FUNCTION_BELOW == 1 && LIGHT_FUNCTION_ABOVE == 2,
64 "LightFunction is the select option index");
65static_assert(OUT_PIN_LEVEL_LOW == 0 && OUT_PIN_LEVEL_HIGH == 1, "OutPinLevel is the select option index");
66
67static constexpr uint32_t BAUD_RATES[] PROGMEM = {9600, 19200, 38400, 57600, 115200, 230400, 256000, 460800};
68
69// Commands
70static constexpr uint8_t CMD_ENABLE_CONF = 0xFF;
71static constexpr uint8_t CMD_DISABLE_CONF = 0xFE;
72static constexpr uint8_t CMD_ENABLE_ENG = 0x62;
73static constexpr uint8_t CMD_DISABLE_ENG = 0x63;
74static constexpr uint8_t CMD_MAXDIST_DURATION = 0x60;
75static constexpr uint8_t CMD_QUERY = 0x61;
76static constexpr uint8_t CMD_GATE_SENS = 0x64;
77static constexpr uint8_t CMD_QUERY_VERSION = 0xA0;
78static constexpr uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0xAB;
79static constexpr uint8_t CMD_SET_DISTANCE_RESOLUTION = 0xAA;
80static constexpr uint8_t CMD_QUERY_LIGHT_CONTROL = 0xAE;
81static constexpr uint8_t CMD_SET_LIGHT_CONTROL = 0xAD;
82static constexpr uint8_t CMD_SET_BAUD_RATE = 0xA1;
83static constexpr uint8_t CMD_BT_PASSWORD = 0xA9;
84static constexpr uint8_t CMD_QUERY_MAC_ADDRESS = 0xA5;
85static constexpr uint8_t CMD_RESET = 0xA2;
86static constexpr uint8_t CMD_RESTART = 0xA3;
87static constexpr uint8_t CMD_BLUETOOTH = 0xA4;
88#ifdef USE_LD2410_BG_CORRECTION
89// Background noise correction (firmware V2.44+): 0x0B starts it, 0x1B polls it
90static constexpr uint8_t CMD_BG_CORRECTION_START = 0x0B;
91static constexpr uint8_t CMD_BG_CORRECTION_QUERY = 0x1B;
92// Firmware V2.44 added the commands; older firmware ignores them without a NAK. version_[0] holds the minor in hex
93static constexpr uint8_t BG_CORRECTION_MIN_MAJOR = 2;
94static constexpr uint8_t BG_CORRECTION_MIN_MINOR = 0x44;
95static constexpr uint8_t BG_CORRECTION_IDLE = 0x00;
96static constexpr uint8_t BG_CORRECTION_COMPLETED = 0x02;
97static constexpr uint32_t BG_CORRECTION_POLL_INTERVAL_MS = 1000;
98// The module waits 10 s before it measures for the duration sent with 0x0B (serial protocol V1.07, 2.2.20), plus margin
99static constexpr uint32_t BG_CORRECTION_EXTRA_MS = 13000;
100static constexpr uint32_t BG_CORRECTION_POLL_ID = 0;
101static constexpr uint32_t BG_CORRECTION_DEADLINE_ID = 1;
102#endif
103// Commands values
104static constexpr uint8_t CMD_MAX_MOVE_VALUE = 0x00;
105static constexpr uint8_t CMD_MAX_STILL_VALUE = 0x01;
106static constexpr uint8_t CMD_DURATION_VALUE = 0x02;
107// Bitmasks for target states
108static constexpr uint8_t MOVE_BITMASK = 0x01;
109static constexpr uint8_t STILL_BITMASK = 0x02;
110// While correcting: 0x04 running, 0x05 success, 0x06 failure
111static constexpr uint8_t TARGET_STATE_CALIBRATING_MIN = 0x04;
112#ifdef USE_LD2410_BG_CORRECTION
113static constexpr uint8_t TARGET_STATE_BG_SUCCESS = 0x05;
114static constexpr uint8_t TARGET_STATE_BG_FAILED = 0x06;
115PROGMEM_STRING_TABLE(BgCorrectionResultStrings, "Success", "Failed", "Unconfirmed", "Refused", "Timed out", "Running");
116// An unknown result never reads as a pass
117static constexpr uint8_t UNCONFIRMED_INDEX = static_cast<uint8_t>(BgCorrectionResult::BG_CORRECTION_RESULT_UNCONFIRMED);
118#endif
119using ld24xx::CMD_FRAME_FOOTER;
120using ld24xx::CMD_FRAME_HEADER;
121using ld24xx::HEADER_FOOTER_SIZE;
123// Smallest frames whose values can all be read: the last value, data footer and check, then the frame footer
124static constexpr uint8_t PERIODIC_FRAME_MIN = DETECT_DISTANCE_HIGH + 3 + HEADER_FOOTER_SIZE;
125static constexpr uint8_t ENGINEERING_FRAME_MIN = OUT_PIN_SENSOR + 3 + HEADER_FOOTER_SIZE;
126// Data Header & Footer
127static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
128static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
129
130void LD2410Component::dump_config() {
131 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
132 char version_s[20];
133 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
134 ld24xx::format_version_str(this->version_, version_s);
135 ESP_LOGCONFIG(TAG,
136 "LD2410:\n"
137 " Firmware version: %s\n"
138 " MAC address: %s",
139 version_s, mac_str);
140#ifdef USE_BINARY_SENSOR
141 ESP_LOGCONFIG(TAG, "Binary Sensors:");
142 LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_);
143 LOG_BINARY_SENSOR(" ", "MovingTarget", this->moving_target_binary_sensor_);
144 LOG_BINARY_SENSOR(" ", "StillTarget", this->still_target_binary_sensor_);
145 LOG_BINARY_SENSOR(" ", "OutPinPresenceStatus", this->out_pin_presence_status_binary_sensor_);
146 LOG_BINARY_SENSOR(" ", "Calibration", this->calibration_binary_sensor_);
147#endif
148#ifdef USE_SENSOR
149 ESP_LOGCONFIG(TAG, "Sensors:");
150 LOG_SENSOR_WITH_DEDUP(" ", "Light", this->light_sensor_);
151 LOG_SENSOR_WITH_DEDUP(" ", "DetectionDistance", this->detection_distance_sensor_);
152 LOG_SENSOR_WITH_DEDUP(" ", "MovingTargetDistance", this->moving_target_distance_sensor_);
153 LOG_SENSOR_WITH_DEDUP(" ", "MovingTargetEnergy", this->moving_target_energy_sensor_);
154 LOG_SENSOR_WITH_DEDUP(" ", "StillTargetDistance", this->still_target_distance_sensor_);
155 LOG_SENSOR_WITH_DEDUP(" ", "StillTargetEnergy", this->still_target_energy_sensor_);
156 for (auto &s : this->gate_move_sensors_) {
157 LOG_SENSOR_WITH_DEDUP(" ", "GateMove", s);
158 }
159 for (auto &s : this->gate_still_sensors_) {
160 LOG_SENSOR_WITH_DEDUP(" ", "GateStill", s);
161 }
162#endif
163#ifdef USE_TEXT_SENSOR
164 ESP_LOGCONFIG(TAG, "Text Sensors:");
165 LOG_TEXT_SENSOR(" ", "Mac", this->mac_text_sensor_);
166 LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_);
167 LOG_TEXT_SENSOR(" ", "CalibrationResult", this->calibration_result_text_sensor_);
168#endif
169#ifdef USE_NUMBER
170 ESP_LOGCONFIG(TAG, "Numbers:");
171 LOG_NUMBER(" ", "LightThreshold", this->light_threshold_number_);
172 LOG_NUMBER(" ", "MaxMoveDistanceGate", this->max_move_distance_gate_number_);
173 LOG_NUMBER(" ", "MaxStillDistanceGate", this->max_still_distance_gate_number_);
174 LOG_NUMBER(" ", "Timeout", this->timeout_number_);
175 for (number::Number *n : this->gate_move_threshold_numbers_) {
176 LOG_NUMBER(" ", "MoveThreshold", n);
177 }
178 for (number::Number *n : this->gate_still_threshold_numbers_) {
179 LOG_NUMBER(" ", "StillThreshold", n);
180 }
181#endif
182#ifdef USE_SELECT
183 ESP_LOGCONFIG(TAG, "Selects:");
184 LOG_SELECT(" ", "BaudRate", this->baud_rate_select_);
185 LOG_SELECT(" ", "DistanceResolution", this->distance_resolution_select_);
186 LOG_SELECT(" ", "LightFunction", this->light_function_select_);
187 LOG_SELECT(" ", "OutPinLevel", this->out_pin_level_select_);
188#endif
189#ifdef USE_SWITCH
190 ESP_LOGCONFIG(TAG, "Switches:");
191 LOG_SWITCH(" ", "Bluetooth", this->bluetooth_switch_);
192 LOG_SWITCH(" ", "EngineeringMode", this->engineering_mode_switch_);
193#endif
194#ifdef USE_BUTTON
195 ESP_LOGCONFIG(TAG, "Buttons:");
196 LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_);
197 LOG_BUTTON(" ", "Query", this->query_button_);
198 LOG_BUTTON(" ", "Restart", this->restart_button_);
199 LOG_BUTTON(" ", "BackgroundCorrection", this->background_correction_button_);
200#endif
201}
202
204#ifdef USE_LD2410_BG_CORRECTION
205 this->publish_calibration_running_(false);
206#endif
207 this->read_all_info();
208}
209
210void LD2410Component::read_all_info() {
211 this->set_config_mode_(true);
212 this->get_version_();
213 this->get_mac_();
215 this->query_light_control_();
216 this->query_parameters_();
217 this->set_config_mode_(false);
218#ifdef USE_SELECT
219 if (this->baud_rate_select_ != nullptr) {
220 if (auto index = ld24xx::find_index(BAUD_RATES, this->parent_->get_baud_rate())) {
221 this->baud_rate_select_->publish_state(*index);
222 }
223 }
224#endif
225}
226
227void LD2410Component::restart_and_read_all_info() {
228 this->set_config_mode_(true);
229 this->restart_();
230 this->set_timeout(1000, [this]() { this->read_all_info(); });
231}
232
233void LD2410Component::loop() {
234 this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
235}
236
237void LD2410Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
238 ESP_LOGV(TAG, "Sending COMMAND %02X", command);
239 // frame header bytes
240 this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
241 // length bytes
242 uint8_t len = 2;
243 if (command_value != nullptr) {
244 len += command_value_len;
245 }
246 // 2 length bytes (low, high) + 2 command bytes (low, high)
247 uint8_t len_cmd[] = {len, 0x00, command, 0x00};
248 this->write_array(len_cmd, sizeof(len_cmd));
249 // command value bytes
250 if (command_value != nullptr) {
251 this->write_array(command_value, command_value_len);
252 }
253 // frame footer bytes
254 this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
255
256 if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
257 delay(50); // NOLINT
258 }
259}
260
262 // 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
263 // data header=0xAA, data footer=0x55, crc=0x00
264 if (this->buffer_pos_ < 12 || !ld2410::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
265 this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER ||
266 this->buffer_data_[this->buffer_pos_ - 5] != CHECK) {
267 return;
268 }
269 /*
270 Data Type: 7th
271 0x01: Engineering mode
272 0x02: Normal mode
273 */
274 bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
275 if (this->buffer_pos_ < (engineering_mode ? ENGINEERING_FRAME_MIN : PERIODIC_FRAME_MIN)) {
276 return; // too short to hold the values
277 }
278#ifdef USE_SWITCH
279 PUBLISH_STATE(this->engineering_mode_switch_, engineering_mode);
280#endif
281 /*
282 Target states: 9th
283 0x00 = No target
284 0x01 = Moving targets
285 0x02 = Still targets
286 0x03 = Moving+Still targets
287 */
288 const uint8_t target_state = this->buffer_data_[TARGET_STATES];
289#ifdef USE_LD2410_BG_CORRECTION
290 // Pass or fail comes only from these frames
291 if (this->bg_correction_running_) {
292 if (target_state == TARGET_STATE_BG_SUCCESS) {
294 } else if (target_state == TARGET_STATE_BG_FAILED) {
296 }
297 }
298#endif
299#ifdef USE_BINARY_SENSOR
300 if (target_state < TARGET_STATE_CALIBRATING_MIN) {
301 PUBLISH_STATE(this->target_binary_sensor_, target_state != 0x00);
302 PUBLISH_STATE(this->moving_target_binary_sensor_, target_state & MOVE_BITMASK);
303 PUBLISH_STATE(this->still_target_binary_sensor_, target_state & STILL_BITMASK);
304 }
305#endif
306 /*
307 Moving target distance: 10~11th bytes
308 Moving target energy: 12th byte
309 Still target distance: 13~14th bytes
310 Still target energy: 15th byte
311 Detect distance: 16~17th bytes
312 */
313#ifdef USE_SENSOR
314 SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
316 SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY]);
317 SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
319 SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY]);
320 SAFE_PUBLISH_SENSOR(this->detection_distance_sensor_,
322
323 if (engineering_mode) {
324 /*
325 Moving distance range: 18th byte
326 Still distance range: 19th byte
327 Moving energy: 20~28th bytes
328 */
329 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
330 SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i]);
331 }
332 /*
333 Still energy: 29~37th bytes
334 */
335 for (uint8_t i = 0; i < TOTAL_GATES; i++) {
336 SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
337 }
338 /*
339 Light sensor: 38th bytes
340 */
341 SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
342 } else {
343 for (auto &gate_move_sensor : this->gate_move_sensors_) {
344 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_move_sensor);
345 }
346 for (auto &gate_still_sensor : this->gate_still_sensors_) {
347 SAFE_PUBLISH_SENSOR_UNKNOWN(gate_still_sensor);
348 }
349 SAFE_PUBLISH_SENSOR_UNKNOWN(this->light_sensor_);
350 }
351#endif
352#ifdef USE_BINARY_SENSOR
353 PUBLISH_STATE(this->out_pin_presence_status_binary_sensor_,
354 engineering_mode ? this->buffer_data_[OUT_PIN_SENSOR] == 0x01 : false);
355#endif
356}
357
358#ifdef USE_NUMBER
360 if (n != nullptr && (!n->has_state() || n->state != value)) {
362 }
363}
364#endif
365
367 ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
368 if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
369 ESP_LOGE(TAG, "Invalid status");
370 return;
371 }
372 if (this->buffer_data_[8] || this->buffer_data_[9]) {
373 ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
374#ifdef USE_LD2410_BG_CORRECTION
375 // Only a refused start ends the run; a refused poll waits for the next poll or the deadline
376 if (this->buffer_data_[COMMAND] == CMD_BG_CORRECTION_START) {
378 }
379#endif
380 return;
381 }
382
383 switch (this->buffer_data_[COMMAND]) {
384 case CMD_ENABLE_CONF:
385 ESP_LOGV(TAG, "Enable conf");
386 break;
387
388 case CMD_DISABLE_CONF:
389 ESP_LOGV(TAG, "Disabled conf");
390 break;
391
392 case CMD_SET_BAUD_RATE:
393 ESP_LOGV(TAG, "Baud rate change");
394#ifdef USE_SELECT
395 if (this->baud_rate_select_ != nullptr) {
396 auto baud = this->baud_rate_select_->current_option();
397 ESP_LOGE(TAG, "Change baud rate to %.*s and reinstall", (int) baud.size(), baud.c_str());
398 }
399#endif
400 break;
401
402 case CMD_QUERY_VERSION: {
403 if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
404 break; // too short to hold a version
405 }
406 std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
407 char version_s[20];
408 ld24xx::format_version_str(this->version_, version_s);
409 ESP_LOGV(TAG, "Firmware version: %s", version_s);
410#ifdef USE_TEXT_SENSOR
411 PUBLISH_STATE(this->version_text_sensor_, version_s);
412#endif
413 break;
414 }
415
416 case CMD_QUERY_DISTANCE_RESOLUTION: {
417 if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
418 break; // too short to hold the resolution
419 }
420 const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
421 if (!index) {
422 ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
423 break;
424 }
425 ESP_LOGV(TAG, "Distance resolution: %s",
426 LOG_STR_ARG(DistanceResolutionStrings::get_log_str(*index, DistanceResolutionStrings::LAST_INDEX)));
427#ifdef USE_SELECT
428 PUBLISH_STATE(this->distance_resolution_select_, *index);
429#endif
430 break;
431 }
432
433 case CMD_QUERY_LIGHT_CONTROL: {
434 if (this->buffer_pos_ < 13 + HEADER_FOOTER_SIZE) {
435 break; // too short to hold the light settings
436 }
437 this->light_function_ = this->buffer_data_[10];
438 this->light_threshold_ = this->buffer_data_[11];
439 this->out_pin_level_ = this->buffer_data_[12];
440 ESP_LOGV(TAG, "Light function: %u, threshold: %u, out pin level: %u", this->light_function_,
441 this->light_threshold_, this->out_pin_level_);
442#ifdef USE_SELECT
443 PUBLISH_STATE(this->light_function_select_, static_cast<size_t>(this->light_function_));
444 PUBLISH_STATE(this->out_pin_level_select_, static_cast<size_t>(this->out_pin_level_));
445#endif
446#ifdef USE_NUMBER
447 PUBLISH_STATE(this->light_threshold_number_, static_cast<float>(this->light_threshold_));
448#endif
449 break;
450 }
451 case CMD_QUERY_MAC_ADDRESS: {
452 if (this->buffer_pos_ < 20) {
453 break; // too short to hold a MAC address
454 }
455
456 this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
457
458 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
459 const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
460 ESP_LOGV(TAG, "MAC address: %s", mac_str);
461#ifdef USE_TEXT_SENSOR
462 PUBLISH_STATE(this->mac_text_sensor_, mac_str);
463#endif
464#ifdef USE_SWITCH
465 PUBLISH_STATE(this->bluetooth_switch_, this->bluetooth_on_);
466#endif
467 break;
468 }
469
470 case CMD_GATE_SENS:
471 ESP_LOGV(TAG, "Sensitivity");
472 break;
473
474#ifdef USE_LD2410_BG_CORRECTION
475 case CMD_BG_CORRECTION_START:
476 ESP_LOGV(TAG, "Background correction started");
477 break;
478
479 case CMD_BG_CORRECTION_QUERY: {
480 const uint8_t status = this->buffer_data_[10];
481 ESP_LOGV(TAG, "Background correction status: %u", status);
482 // The module stops at idle after a fail frame; idle before the run starts is ignored
483 if (status == BG_CORRECTION_COMPLETED ||
484 (status == BG_CORRECTION_IDLE &&
487 }
488 break;
489 }
490#endif
491
492 case CMD_BLUETOOTH:
493 ESP_LOGV(TAG, "Bluetooth");
494 break;
495
496 case CMD_SET_DISTANCE_RESOLUTION:
497 ESP_LOGV(TAG, "Set distance resolution");
498 break;
499
500 case CMD_SET_LIGHT_CONTROL:
501 ESP_LOGV(TAG, "Set light control");
502 break;
503
504 case CMD_BT_PASSWORD:
505 ESP_LOGV(TAG, "Set bluetooth password");
506 break;
507
508 case CMD_QUERY: { // Query parameters response
509 if (this->buffer_pos_ < 38) {
510 break; // too short to hold the parameters
511 }
512 if (this->buffer_data_[10] != HEADER)
513 return; // value head=0xAA
514#ifdef USE_NUMBER
515 /*
516 Moving distance range: 13th byte
517 Still distance range: 14th byte
518 */
519 set_number_value(this->max_move_distance_gate_number_, this->buffer_data_[12]);
520 set_number_value(this->max_still_distance_gate_number_, this->buffer_data_[13]);
521 /*
522 Moving Sensitivities: 15~23th bytes
523 */
524 for (size_t i = 0; i < TOTAL_GATES; i++) {
525 set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[14 + i]);
526 }
527 /*
528 Still Sensitivities: 24~32th bytes
529 */
530 for (size_t i = 0; i < TOTAL_GATES; i++) {
532 }
533 /*
534 None Duration: 33~34th bytes
535 */
536 set_number_value(this->timeout_number_, encode_uint16(this->buffer_data_[33], this->buffer_data_[32]));
537#endif
538 break;
539 }
540 default:
541 break;
542 }
543}
544
546 if (readch < 0) {
547 return; // No data available
548 }
549 // Periodic and command frames both carry their count after the header
551 this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld24xx::cmd_frame_length,
552 [this](uint8_t frame_len) { return this->handle_frame_(frame_len); }, []() { ESP_LOGW(TAG, "Invalid length"); });
553}
554
555// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
556bool LD2410Component::handle_frame_(uint8_t frame_len) {
557 this->buffer_pos_ = frame_len; // the handlers take the frame length from here
558 const uint8_t *tail = &this->buffer_data_[frame_len - HEADER_FOOTER_SIZE];
559 if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
560 if (!ld2410::validate_header_footer(DATA_FRAME_FOOTER, tail)) {
561 return false;
562 }
563 ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
564 this->handle_periodic_data_();
565 return true;
566 }
567 if (!ld2410::validate_header_footer(CMD_FRAME_FOOTER, tail)) {
568 return false;
569 }
570 ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
571 this->handle_ack_data_();
572 return true;
573}
574
576 const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF;
577 const uint8_t cmd_value[2] = {0x01, 0x00};
578 this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value));
579}
580
581void LD2410Component::set_bluetooth(bool enable) {
582 this->set_config_mode_(true);
583 const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00};
584 this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value));
585 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
586}
587
588void LD2410Component::set_distance_resolution(const char *state) {
590 if (index >= 0) {
591 this->set_distance_resolution(static_cast<DistanceResolution>(progmem_read_byte(&DISTANCE_RESOLUTIONS[index])));
592 }
593}
594
595void LD2410Component::set_distance_resolution(DistanceResolution resolution) {
596 this->set_config_mode_(true);
597 const uint8_t cmd_value[2] = {resolution, 0x00};
598 this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, sizeof(cmd_value));
599 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
600}
601
602void LD2410Component::set_baud_rate(const char *state) {
603 const int16_t index = progmem_string_table_find<BaudRateStrings>(state, strlen(state));
604 if (index >= 0) {
605 this->set_baud_rate(static_cast<BaudRate>(index + 1));
606 }
607}
608
609void LD2410Component::set_baud_rate(BaudRate rate) {
610 this->set_config_mode_(true);
611 const uint8_t cmd_value[2] = {rate, 0x00};
612 this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value));
613 this->set_timeout(200, [this]() { this->restart_(); });
614}
615
616void LD2410Component::set_bluetooth_password(const std::string &password) {
617 if (password.length() != 6) {
618 ESP_LOGE(TAG, "Password must be exactly 6 chars");
619 return;
620 }
621 this->set_config_mode_(true);
622 uint8_t cmd_value[6];
623 std::copy(password.begin(), password.end(), std::begin(cmd_value));
624 this->send_command_(CMD_BT_PASSWORD, cmd_value, sizeof(cmd_value));
625 this->set_config_mode_(false);
626}
627
628void LD2410Component::set_engineering_mode(bool enable) {
629 const uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG;
630 this->set_config_mode_(true);
631 this->send_command_(cmd, nullptr, 0);
632 this->set_config_mode_(false);
633}
634
635void LD2410Component::factory_reset() {
636 this->set_config_mode_(true);
637 this->send_command_(CMD_RESET, nullptr, 0);
638 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
639}
640
641void LD2410Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); }
642
643void LD2410Component::query_parameters_() { this->send_command_(CMD_QUERY, nullptr, 0); }
644
645void LD2410Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); }
646
648 const uint8_t cmd_value[2] = {0x01, 0x00};
649 this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, sizeof(cmd_value));
650}
651
652void LD2410Component::get_distance_resolution_() { this->send_command_(CMD_QUERY_DISTANCE_RESOLUTION, nullptr, 0); }
653
654void LD2410Component::query_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); }
655
656#ifdef USE_LD2410_BG_CORRECTION
657void LD2410Component::start_background_correction() {
658 if (this->bg_correction_running_) {
659 ESP_LOGW(TAG, "Background correction already running");
660 return;
661 }
662 const uint8_t major = this->version_[1];
663 const uint8_t minor = this->version_[0];
664 // A version not read yet (0.00) is tried anyway; the deadline still ends the run
665 if (major != 0 &&
666 (major < BG_CORRECTION_MIN_MAJOR || (major == BG_CORRECTION_MIN_MAJOR && minor < BG_CORRECTION_MIN_MINOR))) {
667 ESP_LOGW(TAG, "Background correction needs firmware V2.44 or later, module has V%u.%02X", major, minor);
669 return;
670 }
671 ESP_LOGI(TAG, "Starting background correction (%u s); the room must be empty", this->bg_correction_duration_);
672 this->set_config_mode_(true);
673 const uint8_t value[2] = {this->bg_correction_duration_, 0x00};
674 this->send_command_(CMD_BG_CORRECTION_START, value, sizeof(value));
675 this->set_config_mode_(false);
677 this->bg_correction_running_ = true;
680 this->set_interval(BG_CORRECTION_POLL_ID, BG_CORRECTION_POLL_INTERVAL_MS, [this]() {
681 this->set_config_mode_(true);
682 this->send_command_(CMD_BG_CORRECTION_QUERY, nullptr, 0);
683 this->set_config_mode_(false);
684 });
685 // Firmware without 0x1B never reports completion
686 this->set_timeout(
687 BG_CORRECTION_DEADLINE_ID, this->bg_correction_duration_ * 1000U + BG_CORRECTION_EXTRA_MS,
689}
690
692 if (!this->bg_correction_running_) {
693 return;
694 }
695 this->cancel_interval(BG_CORRECTION_POLL_ID);
696 this->cancel_timeout(BG_CORRECTION_DEADLINE_ID);
697 ESP_LOGI(TAG, "Background correction: %s",
698 LOG_STR_ARG(BgCorrectionResultStrings::get_log_str(static_cast<uint8_t>(result), UNCONFIRMED_INDEX)));
699 this->publish_calibration_result_(result);
700 // The module may have rewritten the gate thresholds
701 this->set_config_mode_(true);
702 this->query_parameters_();
703 this->set_config_mode_(false);
704 // Last, so only an automation on this state can start the next run
705 this->bg_correction_running_ = false;
706 this->publish_calibration_running_(false);
707}
708
710#ifdef USE_BINARY_SENSOR
711 PUBLISH_STATE(this->calibration_binary_sensor_, running);
712#endif
713}
714
716#ifdef USE_TEXT_SENSOR
717 PUBLISH_STATE(this->calibration_result_text_sensor_,
718 BgCorrectionResultStrings::get_progmem_str(static_cast<uint8_t>(result), UNCONFIRMED_INDEX));
719#endif
720}
721#endif
722
723#ifdef USE_NUMBER
724void LD2410Component::set_max_distances_timeout() {
725 if (!this->max_move_distance_gate_number_->has_state() || !this->max_still_distance_gate_number_->has_state() ||
726 !this->timeout_number_->has_state()) {
727 return;
728 }
729 int max_moving_distance_gate_range = static_cast<int>(this->max_move_distance_gate_number_->state);
730 int max_still_distance_gate_range = static_cast<int>(this->max_still_distance_gate_number_->state);
731 int timeout = static_cast<int>(this->timeout_number_->state);
732 uint8_t value[18] = {0x00,
733 0x00,
734 lowbyte(max_moving_distance_gate_range),
735 highbyte(max_moving_distance_gate_range),
736 0x00,
737 0x00,
738 0x01,
739 0x00,
740 lowbyte(max_still_distance_gate_range),
741 highbyte(max_still_distance_gate_range),
742 0x00,
743 0x00,
744 0x02,
745 0x00,
746 lowbyte(timeout),
747 highbyte(timeout),
748 0x00,
749 0x00};
750 this->set_config_mode_(true);
751 this->send_command_(CMD_MAXDIST_DURATION, value, sizeof(value));
752 this->query_parameters_();
753 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
754 this->set_config_mode_(false);
755}
756
757void LD2410Component::set_gate_threshold(number::Number *n) {
758 // Found by pointer: up to 18 compares per write beat storing the gate in each number
759 uint8_t gate = 0;
760 while (gate < TOTAL_GATES && this->gate_move_threshold_numbers_[gate] != n &&
761 this->gate_still_threshold_numbers_[gate] != n)
762 gate++;
763 if (gate == TOTAL_GATES) {
764 ESP_LOGW(TAG, "Threshold number is not a known gate");
765 return;
766 }
767 number::Number *motionsens = this->gate_move_threshold_numbers_[gate];
768 number::Number *stillsens = this->gate_still_threshold_numbers_[gate];
769
770 if (!motionsens->has_state() || !stillsens->has_state()) {
771 return;
772 }
773 int motion = static_cast<int>(motionsens->state);
774 int still = static_cast<int>(stillsens->state);
775
776 this->set_config_mode_(true);
777 // reference
778 // https://drive.google.com/drive/folders/1p4dhbEJA3YubyIjIIC7wwVsSo8x29Fq-?spm=a2g0o.detail.1000023.17.93465697yFwVxH
779 // Send data: configure the motion sensitivity of distance gate 3 to 40, and the static sensitivity of 40
780 // 00 00 (gate)
781 // 03 00 00 00 (gate number)
782 // 01 00 (motion sensitivity)
783 // 28 00 00 00 (value)
784 // 02 00 (still sensitivtiy)
785 // 28 00 00 00 (value)
786 uint8_t value[18] = {0x00, 0x00, lowbyte(gate), highbyte(gate), 0x00, 0x00,
787 0x01, 0x00, lowbyte(motion), highbyte(motion), 0x00, 0x00,
788 0x02, 0x00, lowbyte(still), highbyte(still), 0x00, 0x00};
789 this->send_command_(CMD_GATE_SENS, value, sizeof(value));
790 this->query_parameters_();
791 this->set_config_mode_(false);
792}
793
794void LD2410Component::set_gate_still_threshold_number(uint8_t gate, number::Number *n) {
795 this->gate_still_threshold_numbers_[gate] = n;
796}
797
798void LD2410Component::set_gate_move_threshold_number(uint8_t gate, number::Number *n) {
799 this->gate_move_threshold_numbers_[gate] = n;
800}
801#endif
802
803void LD2410Component::set_light_out_control() {
804#ifdef USE_NUMBER
805 if (this->light_threshold_number_ != nullptr && this->light_threshold_number_->has_state()) {
806 this->light_threshold_ = static_cast<uint8_t>(this->light_threshold_number_->state);
807 }
808#endif
809#ifdef USE_SELECT
810 if (this->light_function_select_ != nullptr) {
811 if (const auto index = this->light_function_select_->active_index()) {
812 this->light_function_ = *index;
813 }
814 }
815 if (this->out_pin_level_select_ != nullptr) {
816 if (const auto index = this->out_pin_level_select_->active_index()) {
817 this->out_pin_level_ = *index;
818 }
819 }
820#endif
821 this->set_config_mode_(true);
822 uint8_t value[4] = {this->light_function_, this->light_threshold_, this->out_pin_level_, 0x00};
823 this->send_command_(CMD_SET_LIGHT_CONTROL, value, sizeof(value));
824 this->query_light_control_();
825 this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
826 this->set_config_mode_(false);
827}
828
829#ifdef USE_SENSOR
830void LD2410Component::set_gate_move_sensor(uint8_t gate, sensor::Sensor *s) {
831 this->gate_move_sensors_[gate].set_sensor(s);
832}
833
834void LD2410Component::set_gate_still_sensor(uint8_t gate, sensor::Sensor *s) {
835 this->gate_still_sensors_[gate].set_sensor(s);
836}
837#endif
838
839} // namespace esphome::ld2410
uint8_t status
Definition bl0942.h:8
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
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
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
bool has_state() const
std::array< number::Number *, TOTAL_GATES > gate_still_threshold_numbers_
Definition ld2410.h:179
void publish_calibration_running_(bool running)
Definition ld2410.cpp:709
BgCorrectionResult bg_correction_result_
Definition ld2410.h:175
void set_config_mode_(bool enable)
Definition ld2410.cpp:575
std::array< sensor::SensorWithDedup< uint8_t >, TOTAL_GATES > gate_move_sensors_
Definition ld2410.h:182
std::array< number::Number *, TOTAL_GATES > gate_move_threshold_numbers_
Definition ld2410.h:178
std::array< sensor::SensorWithDedup< uint8_t >, TOTAL_GATES > gate_still_sensors_
Definition ld2410.h:183
void finish_background_correction_(BgCorrectionResult result)
Definition ld2410.cpp:691
uint8_t mac_address_[MAC_ADDRESS_SIZE]
Definition ld2410.h:169
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len)
Definition ld2410.cpp:237
uint8_t buffer_data_[MAX_LINE_LENGTH]
Definition ld2410.h:168
void publish_calibration_result_(BgCorrectionResult result)
Definition ld2410.cpp:715
bool handle_frame_(uint8_t frame_len)
Definition ld2410.cpp:556
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
void set_number_value(number::Number *n, float value)
Definition ld2410.cpp:359
ESPHOME_LOG_TAG(TAG, "ld2410")
PROGMEM_STRING_TABLE(BaudRateStrings, "9600", "19200", "38400", "57600", "115200", "230400", "256000", "460800")
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