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