ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
dfrobot_sen0609.cpp
Go to the documentation of this file.
1#include "dfrobot_sen0609.h"
2
4#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
7
8#include <cmath>
9#include <cstdlib>
10#include <cstring>
11
13
14ESPHOME_LOG_TAG(TAG, "dfrobot_sen0609");
15
16static constexpr uint8_t MAX_ATTEMPTS = 3;
17// The module ignores a command that follows its last answer too closely
18static constexpr uint32_t COMMAND_GAP_MS = 100;
19// Gathers entity changes made close together into one flash write
20static constexpr uint32_t COALESCE_MS = 1000;
21static constexpr uint32_t DEFAULT_TIMEOUT_MS = 1000;
22static constexpr uint32_t LONG_TIMEOUT_MS = 2000;
23static constexpr uint32_t FACTORY_RESET_TIMEOUT_MS = 3000;
24// resetSystem has no answer; this is how long the module takes to boot again
25static constexpr uint32_t RESTART_MS = 1500;
26static constexpr uint32_t GIVE_UP_BACKOFF_MS = 30000;
27// Presence frames come every second (setUartOutput period); this long without one means the module lost them
28static constexpr uint32_t FRAME_TIMEOUT_MS = 10000;
29static constexpr uint8_t FRAME_FIELDS = 5;
30
31static constexpr uint8_t LINE_END[] = {'\r', '\n'};
32
33// Indexed by Param; empty for parameters that cannot be read
34PROGMEM_STRING_TABLE(ReadCommands, "", "", "getRange", "getTrigRange", "getSensitivity", "getLatency", "getInhibit",
35 "getThrFactor", "getMicroMotion", "getGpioMode 1", "", "", "getSWV", "getHWV");
36
37static_assert(PARAM_COUNT <= 16, "pending_writes_ and pending_reads_ hold one bit per parameter");
38static constexpr uint16_t param_bit(Param param) { return static_cast<uint16_t>(1U << param); }
39
40// Parameters kept in the module's flash only after saveConfig
41static constexpr uint16_t PERSISTENT_PARAMS =
42 param_bit(PARAM_RANGE) | param_bit(PARAM_TRIG_RANGE) | param_bit(PARAM_SENSITIVITY) | param_bit(PARAM_LATENCY) |
43 param_bit(PARAM_INHIBIT) | param_bit(PARAM_THR_FACTOR) | param_bit(PARAM_MICRO_MOTION) | param_bit(PARAM_GPIO_MODE);
44// The frames depend on these, so their writes are kept until they succeed
45static constexpr uint16_t FRAME_PARAMS = param_bit(PARAM_RUN_APP) | param_bit(PARAM_UART_OUTPUT);
46
47#ifdef USE_SWITCH
48static constexpr bool is_led(Param param) { return param == PARAM_RUN_LED || param == PARAM_OUT_LED; }
49static constexpr SwitchSetting led_switch(Param param) {
51}
52#endif
53
54#ifdef USE_NUMBER
55static_assert(NUMBER_COUNT <= 16, "changed_numbers_ holds one bit per number");
56static constexpr uint8_t NUMBER_PARAMS[NUMBER_COUNT] PROGMEM = {
59};
60#endif
61
62static bool starts_with(const char *str, ESPHOME_PGM_P prefix) {
63 return ESPHOME_strncmp_P(str, prefix, ESPHOME_strlen_P(prefix)) == 0;
64}
65
66// Splits "a,b,c*" in place; returns the number of fields stored in `fields`
67static uint8_t split_fields(char *str, char **fields, uint8_t max_fields) {
68 uint8_t count = 0;
69 char *start = str;
70 for (;; str++) {
71 if (*str != ',' && *str != '*' && *str != '\0')
72 continue;
73 const bool last = *str != ',';
74 *str = '\0';
75 if (count < max_fields)
76 fields[count++] = start;
77 if (last)
78 return count;
79 start = str + 1;
80 }
81}
82
83// Answers that refuse a command whose effect is already in place
84static bool answer_means_done(Operation operation, const char *line) {
85 switch (operation) {
87 return ESPHOME_strstr_P(line, ESPHOME_PSTR("stopped already")) != nullptr;
89 return ESPHOME_strstr_P(line, ESPHOME_PSTR("started already")) != nullptr;
91 return starts_with(line, ESPHOME_PSTR("no parameter"));
92 default:
93 return false;
94 }
95}
96
97// Indexed by Operation
98PROGMEM_STRING_TABLE(OperationStrings, "none", "stop", "start", "restart", "factory reset", "write", "save", "read");
99
100static const LogString *operation_to_str(Operation operation) {
101 return OperationStrings::get_log_str(operation, Operation::OPERATION_NONE);
102}
103
104DFRobotSEN0609Component::DFRobotSEN0609Component(RunMode mode) : mode_(mode) {
105#ifdef USE_NUMBER
106 this->number_values_.fill(NAN);
107#endif
108}
109
110void DFRobotSEN0609Component::dump_config() {
111 ESP_LOGCONFIG(
112 TAG,
113 "DFRobot SEN0609:\n"
114 " Mode: %s",
115 this->mode_ == RunMode::RUN_MODE_PRESENCE ? LOG_STR_LITERAL("presence") : LOG_STR_LITERAL("speed and distance"));
116#ifdef USE_BINARY_SENSOR
117 LOG_BINARY_SENSOR(" ", "HasTarget", this->has_target_binary_sensor_);
118#endif
119#ifdef USE_SENSOR
120 LOG_SENSOR_WITH_DEDUP(" ", "TargetDistance", this->target_distance_sensor_);
121 LOG_SENSOR_WITH_DEDUP(" ", "TargetSpeed", this->target_speed_sensor_);
122 LOG_SENSOR_WITH_DEDUP(" ", "TargetEnergy", this->target_energy_sensor_);
123#endif
124#ifdef USE_TEXT_SENSOR
125 LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_);
126 LOG_TEXT_SENSOR(" ", "HardwareVersion", this->hardware_version_text_sensor_);
127#endif
128#ifdef USE_NUMBER
129 for (number::Number *n : this->numbers_) {
130 LOG_NUMBER(" ", "Number", n);
131 }
132#endif
133#ifdef USE_SWITCH
134 for (switch_::Switch *s : this->switches_) {
135 LOG_SWITCH(" ", "Switch", s);
136 }
137#endif
138#ifdef USE_SELECT
139 LOG_SELECT(" ", "OutPinLevel", this->out_pin_level_select_);
140#endif
141#ifdef USE_BUTTON
142 LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_);
143 LOG_BUTTON(" ", "Query", this->query_button_);
144 LOG_BUTTON(" ", "Restart", this->restart_button_);
145#endif
146}
147
148void DFRobotSEN0609Component::setup() {
149#ifdef USE_SWITCH
150 // The module forgets the LED states at power off
151 for (uint8_t i = SWITCH_RUN_LED; i <= SWITCH_OUT_LED; i++) {
152 switch_::Switch *sw = this->switches_[i];
153 if (sw == nullptr)
154 continue;
155 // A disabled restore mode leaves the switch on, which an inverted switch writes as off
156 this->publish_switch_(static_cast<SwitchSetting>(i), sw->get_initial_write_state().value_or(!sw->is_inverted()));
157 }
158#endif
159 this->queue_configuration_();
160}
161
162void DFRobotSEN0609Component::loop() {
163 if (this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); })) {
164 this->read_failed_ = false;
165 } else if (!this->read_failed_) {
166 ESP_LOGW(TAG, "UART read failed");
167 this->read_failed_ = true;
168 }
169 this->run_sequencer_();
170}
171
172void DFRobotSEN0609Component::readline_(uint8_t c) {
173 char *line = this->line_reader_.feed(c);
174 if (line != nullptr) {
175 this->handle_line_(line);
176 return;
177 }
178 this->line_reader_.log_if_overflowed(TAG);
179 // The prompt has no line end, and the echo of the next command follows it on the same line
180 if (c == '>' && ESPHOME_strcmp_P(this->line_reader_.partial(), ESPHOME_PSTR("DFRobot:/>")) == 0) {
181 this->line_reader_.reset();
182 }
183}
184
185void DFRobotSEN0609Component::handle_line_(char *line) {
186 if (*line == '\0')
187 return;
188 ESP_LOGV(TAG, "RX: %s", line);
189 if (line[0] == '$') {
190 this->handle_frame_(line);
191 return;
192 }
193 // Version lines name their value, so they are used even when they arrive late
194 const bool software = starts_with(line, ESPHOME_PSTR("SoftwareVersion:"));
195 if (software || starts_with(line, ESPHOME_PSTR("HardwareVersion:"))) {
196 if (this->operation_ == Operation::OPERATION_READ &&
197 this->param_ == (software ? PARAM_SW_VERSION : PARAM_HW_VERSION))
198 this->version_received_ = true;
199#ifdef USE_TEXT_SENSOR
200 PUBLISH_STATE(software ? this->version_text_sensor_ : this->hardware_version_text_sensor_, line + 16);
201#endif
202 return;
203 }
204 if (this->operation_ == Operation::OPERATION_NONE) {
205 ESP_LOGD(TAG, "Ignored line, no command pending: %s", line);
206 return;
207 }
208 if (strcmp(line, this->command_) == 0) {
209 this->echo_seen_ = true;
210 return;
211 }
212 // The module echoes every command first; lines before the echo belong to an earlier command
213 if (!this->echo_seen_) {
214 ESP_LOGD(TAG, "Ignored line from an earlier command: %s", line);
215 return;
216 }
217
218 if (starts_with(line, ESPHOME_PSTR("Done")) || answer_means_done(this->operation_, line)) {
219 this->finish_operation_();
220 } else if (starts_with(line, ESPHOME_PSTR("Response "))) {
221 this->parse_response_(line + 9);
222 } else if (ESPHOME_strstr_P(line, ESPHOME_PSTR("not stopped")) != nullptr) {
223 // Stop the sensor before the next attempt
224 this->stopped_ = false;
225 this->fail_operation_();
226 } else if (starts_with(line, ESPHOME_PSTR("Error")) ||
227 ESPHOME_strstr_P(line, ESPHOME_PSTR("not recognized")) != nullptr) {
228 ESP_LOGW(TAG, "Command '%s' rejected: %s", this->command_, line);
229 this->fail_operation_();
230 } else {
231 ESP_LOGD(TAG, "Unexpected answer to '%s': %s", this->command_, line);
232 }
233}
234
235void DFRobotSEN0609Component::handle_frame_(char *line) {
236 // $DFHPD,<presence>, , , *
237 if (starts_with(line, ESPHOME_PSTR("$DFHPD,"))) {
238 const char presence = line[7];
239 if (presence != '0' && presence != '1') {
240 this->log_bad_frame_(LOG_STR("Malformed presence frame"), line);
241 return;
242 }
243 this->last_frame_ms_ = App.get_loop_component_start_time();
244#ifdef USE_BINARY_SENSOR
245 PUBLISH_STATE(this->has_target_binary_sensor_, presence == '1');
246#endif
247 return;
248 }
249 // $DFDMD,<targets>,<reserved>,<distance m>,<speed m/s>,<energy>,...*
250 if (!starts_with(line, ESPHOME_PSTR("$DFDMD,"))) {
251 this->log_bad_frame_(LOG_STR("Unknown frame"), line);
252 return;
253 }
254 char *fields[FRAME_FIELDS];
255 if (split_fields(line + 7, fields, FRAME_FIELDS) < FRAME_FIELDS) {
256 this->log_bad_frame_(LOG_STR("Malformed target frame"), line);
257 return;
258 }
259 const optional<uint8_t> targets = parse_number<uint8_t>(fields[0]);
260 if (!targets.has_value()) {
261 this->log_bad_frame_(LOG_STR("Malformed target frame"), line);
262 return;
263 }
264 if (*targets == 0) {
265#ifdef USE_BINARY_SENSOR
266 PUBLISH_STATE(this->has_target_binary_sensor_, false);
267#endif
268#ifdef USE_SENSOR
269 this->publish_target_(NAN, NAN, NAN);
270#endif
271 return;
272 }
273 const optional<float> distance = parse_number<float>(fields[2]);
274 const optional<float> speed = parse_number<float>(fields[3]);
275 const optional<float> energy = parse_number<float>(fields[4]);
276 if (!distance.has_value() || !speed.has_value() || !energy.has_value()) {
277 this->log_bad_frame_(LOG_STR("Malformed target frame"), line);
278 return;
279 }
280#ifdef USE_BINARY_SENSOR
281 PUBLISH_STATE(this->has_target_binary_sensor_, true);
282#endif
283#ifdef USE_SENSOR
284 this->publish_target_(*distance, *speed, *energy);
285#endif
286}
287
288void DFRobotSEN0609Component::log_bad_frame_(const LogString *problem, const char *line) {
289 // The module sends frames several times a second, so only the first bad one is logged
290 if (this->bad_frame_logged_)
291 return;
292 this->bad_frame_logged_ = true;
293 ESP_LOGW(TAG, "%s: %s", LOG_STR_ARG(problem), line);
294}
295
296#ifdef USE_SENSOR
297static void publish_deduplicated(sensor::SensorWithDedup<float> &sens, float value) {
298 if (std::isnan(value)) {
300 } else {
302 }
303}
304
305void DFRobotSEN0609Component::publish_target_(float distance, float speed, float energy) {
306 publish_deduplicated(this->target_distance_sensor_, distance);
307 publish_deduplicated(this->target_speed_sensor_, speed);
308 publish_deduplicated(this->target_energy_sensor_, energy);
309}
310#endif
311
312void DFRobotSEN0609Component::parse_response_(const char *args) {
313 this->response_count_ = 0;
314 while (this->response_count_ < MAX_RESPONSE_VALUES) {
315 char *end;
316 const float value = strtof(args, &end);
317 // strtof also takes "nan" and "inf", which no setting can hold
318 if (end == args || !std::isfinite(value))
319 break;
320 this->response_[this->response_count_++] = value;
321 args = end;
322 }
323}
324
325void DFRobotSEN0609Component::queue_configuration_() {
326 // The mode, the UART output and the LEDs are applied at every boot instead of being saved
327 uint16_t writes = param_bit(PARAM_RUN_APP);
328 if (this->mode_ == RunMode::RUN_MODE_PRESENCE)
329 writes |= param_bit(PARAM_UART_OUTPUT);
330#ifdef USE_SWITCH
331 if (this->switches_[SWITCH_RUN_LED] != nullptr)
332 writes |= param_bit(PARAM_RUN_LED);
333 if (this->switches_[SWITCH_OUT_LED] != nullptr)
334 writes |= param_bit(PARAM_OUT_LED);
335#endif
336 this->pending_writes_ |= writes;
337 this->pending_reads_ |= this->wanted_reads_();
338}
339
340uint16_t DFRobotSEN0609Component::wanted_reads_() const {
341 uint16_t reads = 0;
342#ifdef USE_TEXT_SENSOR
343 if (this->version_text_sensor_ != nullptr)
344 reads |= param_bit(PARAM_SW_VERSION);
345 if (this->hardware_version_text_sensor_ != nullptr)
346 reads |= param_bit(PARAM_HW_VERSION);
347#endif
348#ifdef USE_NUMBER
349 for (uint8_t i = 0; i < NUMBER_COUNT; i++) {
350 if (this->numbers_[i] != nullptr)
351 reads |= param_bit(static_cast<Param>(progmem_read_byte(&NUMBER_PARAMS[i])));
352 }
353#endif
354#ifdef USE_SWITCH
355 if (this->switches_[SWITCH_MICRO_MOTION] != nullptr)
356 reads |= param_bit(PARAM_MICRO_MOTION);
357#endif
358#ifdef USE_SELECT
359 if (this->out_pin_level_select_ != nullptr)
360 reads |= param_bit(PARAM_GPIO_MODE);
361#endif
362 return reads;
363}
364
365void DFRobotSEN0609Component::check_frames_(uint32_t now) {
366 // Speed mode frames are not watched: whether the module sends them without a target is not known
367 if (this->mode_ != RunMode::RUN_MODE_PRESENCE || now - this->last_frame_ms_ < FRAME_TIMEOUT_MS)
368 return;
369 // The module most likely restarted on its own and lost the configuration applied at boot
370 ESP_LOGW(TAG, "No presence frames, applying the configuration again");
371 this->status_set_warning();
372#ifdef USE_BINARY_SENSOR
373 if (this->has_target_binary_sensor_ != nullptr)
374 this->has_target_binary_sensor_->invalidate_state();
375#endif
376 this->last_frame_ms_ = now;
377 this->queue_configuration_();
378}
379
380void DFRobotSEN0609Component::request_write_(Param param) {
382 this->pending_writes_ |= param_bit(param);
383 this->last_change_ms_ = now;
384 if (this->operation_ != Operation::OPERATION_NONE || this->stopped_)
385 return;
386 // Start a new sequence a little later, so changes made together end in one flash write.
387 // A longer hold, such as the back-off from a module that does not answer, is not cut short.
388 const uint32_t elapsed = now - this->hold_start_ms_;
389 if (elapsed >= this->hold_ms_ || this->hold_ms_ - elapsed < COALESCE_MS)
390 this->hold_(COALESCE_MS);
391}
392
393void DFRobotSEN0609Component::restart() {
394 this->restart_pending_ = true;
395 this->hold_(COMMAND_GAP_MS);
396}
397
398void DFRobotSEN0609Component::factory_reset() {
399 this->factory_reset_pending_ = true;
400 this->hold_(COMMAND_GAP_MS);
401}
402
403void DFRobotSEN0609Component::query_params() {
404 this->pending_reads_ |= this->wanted_reads_();
405 this->hold_(COMMAND_GAP_MS);
406}
407
408#ifdef USE_NUMBER
409void DFRobotSEN0609Component::control_number(NumberSetting setting, float value) {
410 // The module needs min_range <= trigger_range <= max_range; a value not read yet is NAN and passes
411 const auto &values = this->number_values_;
412 const float min_range = setting == NUMBER_MIN_RANGE ? value : values[NUMBER_MIN_RANGE];
413 const float max_range = setting == NUMBER_MAX_RANGE ? value : values[NUMBER_MAX_RANGE];
414 const float trigger_range = setting == NUMBER_TRIGGER_RANGE ? value : values[NUMBER_TRIGGER_RANGE];
415 if (setting <= NUMBER_TRIGGER_RANGE &&
416 (min_range > max_range || trigger_range < min_range || trigger_range > max_range)) {
417 ESP_LOGW(TAG, "Ranges must keep minimum <= trigger <= maximum, not written");
418 if (!std::isnan(this->number_values_[setting]))
419 this->publish_number_(setting, this->number_values_[setting]);
420 return;
421 }
422 this->changed_numbers_ |= 1U << setting;
423 this->publish_number_(setting, value);
424 this->request_write_(static_cast<Param>(progmem_read_byte(&NUMBER_PARAMS[setting])));
425}
426
427void DFRobotSEN0609Component::control_number(number::Number *number, float value) {
428 for (uint8_t i = 0; i < NUMBER_COUNT; i++) {
429 if (this->numbers_[i] == number) {
430 this->control_number(static_cast<NumberSetting>(i), value);
431 return;
432 }
433 }
434}
435
436void DFRobotSEN0609Component::forget_number_changes_(Param param, bool unknown) {
437 for (uint8_t i = 0; i < NUMBER_COUNT; i++) {
438 if (progmem_read_byte(&NUMBER_PARAMS[i]) != param)
439 continue;
440 this->changed_numbers_ &= ~(1U << i);
441 if (unknown)
442 this->publish_number_(static_cast<NumberSetting>(i), NAN);
443 }
444}
445
446void DFRobotSEN0609Component::publish_number_(NumberSetting setting, float value) {
447 this->number_values_[setting] = value;
448 PUBLISH_STATE(this->numbers_[setting], value);
449}
450#endif
451
452#ifdef USE_SWITCH
453void DFRobotSEN0609Component::control_switch(SwitchSetting setting, bool state) {
454 this->publish_switch_(setting, state);
455 switch (setting) {
457 this->request_write_(PARAM_MICRO_MOTION);
458 break;
459 case SWITCH_RUN_LED:
460 this->request_write_(PARAM_RUN_LED);
461 break;
462 default:
463 this->request_write_(PARAM_OUT_LED);
464 break;
465 }
466}
467
468void DFRobotSEN0609Component::publish_switch_(SwitchSetting setting, bool state) {
469 this->switch_states_[setting] = state;
470 PUBLISH_STATE(this->switches_[setting], state);
471}
472#endif
473
474#ifdef USE_SELECT
475void DFRobotSEN0609Component::control_out_pin_level(size_t index) {
476 this->out_pin_level_ = static_cast<uint8_t>(index);
477 this->out_pin_level_select_->publish_state(index);
478 this->request_write_(PARAM_GPIO_MODE);
479}
480#endif
481
482void DFRobotSEN0609Component::hold_(uint32_t duration_ms) {
483 this->hold_start_ms_ = App.get_loop_component_start_time();
484 this->hold_ms_ = duration_ms;
485}
486
487void DFRobotSEN0609Component::run_sequencer_() {
489 if (this->operation_ != Operation::OPERATION_NONE) {
490 uint32_t timeout = DEFAULT_TIMEOUT_MS;
491 switch (this->operation_) {
492 case Operation::OPERATION_RESTART:
493 timeout = RESTART_MS;
494 break;
495 case Operation::OPERATION_FACTORY_RESET:
496 timeout = FACTORY_RESET_TIMEOUT_MS;
497 break;
498 case Operation::OPERATION_STOP:
499 case Operation::OPERATION_SAVE:
500 timeout = LONG_TIMEOUT_MS;
501 break;
502 default:
503 break;
504 }
505 if (now - this->sent_ms_ < timeout)
506 return;
507 if (this->operation_ == Operation::OPERATION_RESTART) {
508 this->finish_operation_();
509 } else {
510 ESP_LOGD(TAG, "No answer to '%s'", this->command_);
511 this->fail_operation_();
512 }
513 return;
514 }
515 if (now - this->hold_start_ms_ < this->hold_ms_)
516 return;
517
518 const bool work_pending =
519 this->factory_reset_pending_ || this->save_pending_ || this->pending_writes_ != 0 || this->pending_reads_ != 0;
520 Operation operation;
521 Param param = PARAM_COUNT;
522 if (this->restart_pending_) {
523 // The reboot drops a write the module took but did not save; writes not sent yet are kept for after it
524 operation = this->stopped_ && this->save_pending_ ? Operation::OPERATION_SAVE : Operation::OPERATION_RESTART;
525 } else if (!work_pending) {
526 if (!this->stopped_) {
527 this->check_frames_(now);
528 // Work given up on is tried again in a later sequence, so the sensor runs in between
529 if ((this->deferred_writes_ != 0 || this->deferred_save_) && now - this->deferred_ms_ >= GIVE_UP_BACKOFF_MS) {
530 this->pending_writes_ |= this->deferred_writes_;
531 this->save_pending_ = this->save_pending_ || this->deferred_save_;
532 this->deferred_writes_ = 0;
533 this->deferred_save_ = false;
534 }
535 return;
536 }
537 operation = Operation::OPERATION_START;
538 } else if (!this->stopped_) {
539 operation = Operation::OPERATION_STOP;
540 } else if (this->factory_reset_pending_) {
541 operation = Operation::OPERATION_FACTORY_RESET;
542 } else if (this->pending_writes_ != 0) {
543 operation = Operation::OPERATION_WRITE;
544 param = static_cast<Param>(__builtin_ctz(this->pending_writes_));
545 } else if (this->save_pending_) {
546 // Changes made within a second of each other share one flash write, also while a sequence runs
547 if (now - this->last_change_ms_ < COALESCE_MS)
548 return;
549 operation = Operation::OPERATION_SAVE;
550 } else {
551 operation = Operation::OPERATION_READ;
552 param = static_cast<Param>(__builtin_ctz(this->pending_reads_));
553 }
554
555 const uint16_t bit = param_bit(param);
556 bool built = this->build_command_(operation, param);
557 if (!built && operation == Operation::OPERATION_WRITE) {
558 // The value this write is paired with is unknown: read it first, once, and keep the write pending
559 if ((this->paired_reads_ & bit) == 0)
560 this->pending_reads_ |= this->wanted_reads_() & bit;
561 if ((this->pending_reads_ & bit) != 0) {
562 this->paired_reads_ |= bit;
563 operation = Operation::OPERATION_READ;
564 built = this->build_command_(operation, param);
565 }
566 }
567 if (!built) {
568 if (operation == Operation::OPERATION_WRITE) {
569 ESP_LOGW(TAG, "Setting not written: the value it is paired with could not be read");
570 this->pending_writes_ &= ~bit;
571 this->paired_reads_ &= ~bit;
572#ifdef USE_NUMBER
573 // Both values come from the read that failed, so what the module holds is unknown
574 this->forget_number_changes_(param, true);
575#endif
576 } else {
577 ESP_LOGE(TAG, "No command for %s of parameter %u", LOG_STR_ARG(operation_to_str(operation)),
578 static_cast<unsigned>(param));
579 this->pending_reads_ &= ~bit;
580 }
581 this->sequence_failed_ = true;
582 this->status_set_warning();
583 return;
584 }
585 // Cleared now, so a change made while the write is on its way is written again
586 if (operation == Operation::OPERATION_WRITE) {
587 this->pending_writes_ &= ~bit;
588 this->paired_reads_ &= ~bit;
589#ifdef USE_NUMBER
590 this->forget_number_changes_(param, false);
591#endif
592 }
593 this->operation_ = operation;
594 this->param_ = param;
595 this->response_count_ = 0;
596 this->echo_seen_ = false;
597 this->version_received_ = false;
598 this->sent_ms_ = now;
599 ESP_LOGV(TAG, "TX: %s", this->command_);
600 this->write_str(this->command_);
601 this->write_array(LINE_END, sizeof(LINE_END));
602}
603
604bool DFRobotSEN0609Component::build_command_(Operation operation, Param param) {
605 char *buf = this->command_;
606 constexpr size_t len = MAX_COMMAND_LENGTH;
607 switch (operation) {
608 case Operation::OPERATION_STOP:
609 ESPHOME_strncpy_P(buf, ESPHOME_PSTR("sensorStop"), len);
610 return true;
611 case Operation::OPERATION_START:
612 ESPHOME_strncpy_P(buf, ESPHOME_PSTR("sensorStart"), len);
613 return true;
614 case Operation::OPERATION_RESTART:
615 ESPHOME_strncpy_P(buf, ESPHOME_PSTR("resetSystem"), len);
616 return true;
617 case Operation::OPERATION_FACTORY_RESET:
618 ESPHOME_strncpy_P(buf, ESPHOME_PSTR("resetCfg"), len);
619 return true;
620 case Operation::OPERATION_SAVE:
621 ESPHOME_strncpy_P(buf, ESPHOME_PSTR("saveConfig"), len);
622 return true;
623 case Operation::OPERATION_READ:
624 ESPHOME_strncpy_P(buf, reinterpret_cast<ESPHOME_PGM_P>(ReadCommands::get_progmem_str(param, 0)), len);
625 return buf[0] != '\0';
626 default:
627 break;
628 }
629
630 switch (param) {
631 case PARAM_RUN_APP:
632 ESPHOME_snprintf_P(buf, len, ESPHOME_PSTR("setRunApp %u"), static_cast<unsigned>(this->mode_));
633 return true;
635 ESPHOME_strncpy_P(buf, ESPHOME_PSTR("setUartOutput 1 1 1 1.0"), len);
636 return true;
637#ifdef USE_SWITCH
639 ESPHOME_snprintf_P(buf, len, ESPHOME_PSTR("setMicroMotion %u"),
640 static_cast<unsigned>(this->switch_states_[SWITCH_MICRO_MOTION]));
641 return true;
642 case PARAM_RUN_LED:
643 case PARAM_OUT_LED: {
644 // 0 turns the LED on
645 const bool on = this->switch_states_[led_switch(param)];
646 this->sent_led_on_ = on;
647 ESPHOME_snprintf_P(buf, len, ESPHOME_PSTR("setLedMode %u %u"), param == PARAM_RUN_LED ? 1U : 2U, on ? 0U : 1U);
648 return true;
649 }
650#endif
651#ifdef USE_SELECT
652 case PARAM_GPIO_MODE:
653 ESPHOME_snprintf_P(buf, len, ESPHOME_PSTR("setGpioMode 1 %u"), static_cast<unsigned>(this->out_pin_level_));
654 return true;
655#endif
656 default:
657 break;
658 }
659
660#ifdef USE_NUMBER
661 const auto &values = this->number_values_;
662 float first = NAN;
663 float second = 0.0f;
664 ESPHOME_PGM_P format = nullptr;
665 switch (param) {
666 case PARAM_RANGE:
667 first = values[NUMBER_MIN_RANGE];
668 second = values[NUMBER_MAX_RANGE];
669 format = ESPHOME_PSTR("setRange %.2f %.2f");
670 break;
671 case PARAM_TRIG_RANGE:
672 first = values[NUMBER_TRIGGER_RANGE];
673 format = ESPHOME_PSTR("setTrigRange %.2f");
674 break;
676 first = values[NUMBER_HOLD_SENSITIVITY];
678 format = ESPHOME_PSTR("setSensitivity %.0f %.0f");
679 break;
680 case PARAM_LATENCY:
681 first = values[NUMBER_ON_LATENCY];
682 second = values[NUMBER_OFF_LATENCY];
683 format = ESPHOME_PSTR("setLatency %.2f %.1f");
684 break;
685 case PARAM_INHIBIT:
686 first = values[NUMBER_INHIBIT_TIME];
687 format = ESPHOME_PSTR("setInhibit %.2f");
688 break;
689 case PARAM_THR_FACTOR:
690 first = values[NUMBER_THRESHOLD_FACTOR];
691 format = ESPHOME_PSTR("setThrFactor %.0f");
692 break;
693 default:
694 return false;
695 }
696 // Commands that take two values need both read from the module first
697 if (std::isnan(first) || std::isnan(second))
698 return false;
699 ESPHOME_snprintf_P(buf, len, format, first, second);
700 return true;
701#else
702 return false;
703#endif
704}
705
706bool DFRobotSEN0609Component::apply_read_(Param param) {
707 const float *r = this->response_;
708 const uint8_t count = this->response_count_;
709 // A change still waiting to be written is newer than what the module holds
710 const bool write_pending = (this->pending_writes_ & param_bit(param)) != 0;
711#ifdef USE_NUMBER
712 // Checked for each number: publishing runs automations, which may change the next one
713 auto read_number = [this](NumberSetting setting, float value) {
714 if ((this->changed_numbers_ & (1U << setting)) == 0)
715 this->publish_number_(setting, value);
716 };
717#endif
718 switch (param) {
719#ifdef USE_NUMBER
720 case PARAM_RANGE:
721 if (count < 2)
722 return false;
723 read_number(NUMBER_MIN_RANGE, r[0]);
724 read_number(NUMBER_MAX_RANGE, r[1]);
725 return true;
726 case PARAM_TRIG_RANGE:
727 if (count < 1)
728 return false;
729 read_number(NUMBER_TRIGGER_RANGE, r[0]);
730 return true;
732 if (count < 2)
733 return false;
734 read_number(NUMBER_HOLD_SENSITIVITY, r[0]);
735 read_number(NUMBER_TRIGGER_SENSITIVITY, r[1]);
736 return true;
737 case PARAM_LATENCY:
738 if (count < 2)
739 return false;
740 read_number(NUMBER_ON_LATENCY, r[0]);
741 read_number(NUMBER_OFF_LATENCY, r[1]);
742 return true;
743 case PARAM_INHIBIT:
744 if (count < 1)
745 return false;
746 read_number(NUMBER_INHIBIT_TIME, r[0]);
747 return true;
748 case PARAM_THR_FACTOR:
749 if (count < 1)
750 return false;
751 read_number(NUMBER_THRESHOLD_FACTOR, r[0]);
752 return true;
753#endif
754#ifdef USE_SWITCH
756 if (count < 1)
757 return false;
758 if (!write_pending)
759 this->publish_switch_(SWITCH_MICRO_MOTION, r[0] != 0.0f);
760 return true;
761#endif
762#ifdef USE_SELECT
763 case PARAM_GPIO_MODE:
764 // Response <pin> <level>
765 if (count < 2 || (r[1] != 0.0f && r[1] != 1.0f))
766 return false;
767 if (!write_pending) {
768 this->out_pin_level_ = static_cast<uint8_t>(r[1]);
769 this->out_pin_level_select_->publish_state(this->out_pin_level_);
770 }
771 return true;
772#endif
773 case PARAM_SW_VERSION:
774 case PARAM_HW_VERSION:
775 // The versions are published as their lines arrive
776 return this->version_received_;
777 default:
778 return true;
779 }
780}
781
782void DFRobotSEN0609Component::finish_operation_() {
783 switch (this->operation_) {
784 case Operation::OPERATION_STOP:
785 this->stopped_ = true;
786 break;
787 case Operation::OPERATION_START:
788 this->stopped_ = false;
789 this->last_frame_ms_ = App.get_loop_component_start_time();
790 if (!this->sequence_failed_)
791 this->status_clear_warning();
792 this->sequence_failed_ = false;
793 break;
794 case Operation::OPERATION_RESTART:
795 // The module starts sensing on its own after a reboot
796 this->restart_pending_ = false;
797 this->stopped_ = false;
798 this->queue_configuration_();
799 break;
800 case Operation::OPERATION_FACTORY_RESET:
801 this->factory_reset_pending_ = false;
802 this->queue_configuration_();
803 break;
804 case Operation::OPERATION_WRITE:
805 this->deferred_writes_ &= ~param_bit(this->param_);
806 if (PERSISTENT_PARAMS & param_bit(this->param_))
807 this->save_pending_ = true;
808#ifdef USE_SWITCH
809 if (is_led(this->param_)) {
810 const uint8_t bit = 1U << led_switch(this->param_);
811 this->led_known_ |= bit;
812 this->led_on_ = this->sent_led_on_ ? (this->led_on_ | bit) : (this->led_on_ & ~bit);
813 }
814#endif
815 break;
816 case Operation::OPERATION_SAVE:
817 this->save_pending_ = false;
818 this->deferred_save_ = false;
819 break;
820 case Operation::OPERATION_READ:
821 if (!this->apply_read_(this->param_)) {
822 ESP_LOGW(TAG, "Malformed answer to '%s'", this->command_);
823 this->fail_operation_();
824 return;
825 }
826 this->pending_reads_ &= ~param_bit(this->param_);
827 this->paired_reads_ &= ~param_bit(this->param_);
828 break;
829 default:
830 return;
831 }
832 if (this->is_aux_operation_()) {
833 this->aux_attempts_ = 0;
834 } else {
835 this->attempts_ = 0;
836 }
837 this->operation_ = Operation::OPERATION_NONE;
838 this->hold_(COMMAND_GAP_MS);
839}
840
841void DFRobotSEN0609Component::fail_operation_() {
842 const bool aux = this->is_aux_operation_();
843 uint8_t &attempts = aux ? this->aux_attempts_ : this->attempts_;
844 const Operation operation = this->operation_;
845 this->operation_ = Operation::OPERATION_NONE;
846 this->hold_(COMMAND_GAP_MS);
847 const bool keep_write = operation == Operation::OPERATION_WRITE && (FRAME_PARAMS & param_bit(this->param_)) != 0;
848 const bool retry = ++attempts < MAX_ATTEMPTS;
849 if (operation == Operation::OPERATION_WRITE && (retry || keep_write))
850 this->pending_writes_ |= param_bit(this->param_);
851 if (retry)
852 return;
853
854 attempts = 0;
855 this->status_set_warning();
856 if (aux || keep_write) {
857 // Without stop, start or the configuration the sensor cannot run as set up; try again later
858 ESP_LOGW(TAG, "Command '%s' failed, trying again later", this->command_);
859 this->hold_ms_ = GIVE_UP_BACKOFF_MS;
860 return;
861 }
862 ESP_LOGW(TAG, "Giving up on %s '%s'", LOG_STR_ARG(operation_to_str(operation)), this->command_);
863 this->sequence_failed_ = true;
864 switch (operation) {
865 case Operation::OPERATION_RESTART:
866 this->restart_pending_ = false;
867 break;
868 case Operation::OPERATION_FACTORY_RESET:
869 this->factory_reset_pending_ = false;
870 break;
871 case Operation::OPERATION_WRITE:
872#ifdef USE_SWITCH
873 if (is_led(this->param_)) {
874 // A newer change is written anyway
875 if ((this->pending_writes_ & param_bit(this->param_)) != 0)
876 break;
877 // The LEDs cannot be read: show the state the module last accepted, or write this one again later
878 const uint8_t bit = 1U << led_switch(this->param_);
879 if ((this->led_known_ & bit) != 0) {
880 this->publish_switch_(led_switch(this->param_), (this->led_on_ & bit) != 0);
881 } else {
882 this->deferred_writes_ |= param_bit(this->param_);
883 this->deferred_ms_ = App.get_loop_component_start_time();
884 }
885 break;
886 }
887#endif
888 // The entity shows a value the module never got; show the module's value again
889 this->pending_reads_ |= this->wanted_reads_() & param_bit(this->param_);
890 break;
891 case Operation::OPERATION_SAVE:
892 // The entities show the changes as kept, but unsaved they are lost at power off: save in a later sequence
893 this->save_pending_ = false;
894 this->deferred_save_ = true;
895 this->deferred_ms_ = App.get_loop_component_start_time();
896 break;
897 case Operation::OPERATION_READ:
898 this->pending_reads_ &= ~param_bit(this->param_);
899 break;
900 default:
901 break;
902 }
903}
904
905} // namespace esphome::dfrobot_sen0609
BedjetMode mode
BedJet operating mode.
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
A sensor pointer that may be null plus the last value it published, stored inline.
uint8_t second
int speed
Definition fan.h:3
bool state
Definition fan.h:2
unsigned count
Definition gif.cpp:51
const uint8_t STORE_YAML_DATA[] PROGMEM
The zstd YAML envelope generated by store_yaml, STORE_YAML_DATA_SIZE bytes in flash.
NumberSetting
Settings shown as number entities.
Param
Module parameters; a write or read of each is one command. Pending work runs in this order.
ESPHOME_LOG_TAG(TAG, "dfrobot_sen0609")
SwitchSetting
Settings shown as switch entities.
PROGMEM_STRING_TABLE(ReadCommands, "", "", "getRange", "getTrigRange", "getSensitivity", "getLatency", "getInhibit", "getThrFactor", "getMicroMotion", "getGpioMode 1", "", "", "getSWV", "getHWV")
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
void const char int line
Definition log.h:110
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1657
void const char int const char * format
Definition log.h:110
Application App
Global storage of Application pointer - only one Application can exist.
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51
static void uint32_t
uint8_t end[39]
Definition sun_gtil2.cpp:17