16static constexpr uint8_t MAX_ATTEMPTS = 3;
18static constexpr uint32_t COMMAND_GAP_MS = 100;
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;
25static constexpr uint32_t RESTART_MS = 1500;
26static constexpr uint32_t GIVE_UP_BACKOFF_MS = 30000;
28static constexpr uint32_t FRAME_TIMEOUT_MS = 10000;
29static constexpr uint8_t FRAME_FIELDS = 5;
31static constexpr uint8_t LINE_END[] = {
'\r',
'\n'};
34PROGMEM_STRING_TABLE(ReadCommands,
"",
"",
"getRange",
"getTrigRange",
"getSensitivity",
"getLatency",
"getInhibit",
35 "getThrFactor",
"getMicroMotion",
"getGpioMode 1",
"",
"",
"getSWV",
"getHWV");
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); }
41static constexpr uint16_t PERSISTENT_PARAMS =
55static_assert(
NUMBER_COUNT <= 16,
"changed_numbers_ holds one bit per number");
62static bool starts_with(
const char *str, ESPHOME_PGM_P prefix) {
63 return ESPHOME_strncmp_P(str, prefix, ESPHOME_strlen_P(prefix)) == 0;
67static uint8_t split_fields(
char *str,
char **fields, uint8_t max_fields) {
71 if (*str !=
',' && *str !=
'*' && *str !=
'\0')
73 const bool last = *str !=
',';
75 if (
count < max_fields)
76 fields[
count++] = start;
84static bool answer_means_done(
Operation operation,
const char *
line) {
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"));
98PROGMEM_STRING_TABLE(OperationStrings,
"none",
"stop",
"start",
"restart",
"factory reset",
"write",
"save",
"read");
100static const LogString *operation_to_str(
Operation operation) {
104DFRobotSEN0609Component::DFRobotSEN0609Component(
RunMode mode) : mode_(
mode) {
106 this->number_values_.fill(NAN);
110void DFRobotSEN0609Component::dump_config() {
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_);
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_);
124#ifdef USE_TEXT_SENSOR
125 LOG_TEXT_SENSOR(
" ",
"Version", this->version_text_sensor_);
126 LOG_TEXT_SENSOR(
" ",
"HardwareVersion", this->hardware_version_text_sensor_);
129 for (number::Number *n : this->numbers_) {
130 LOG_NUMBER(
" ",
"Number", n);
134 for (switch_::Switch *s : this->switches_) {
135 LOG_SWITCH(
" ",
"Switch", s);
139 LOG_SELECT(
" ",
"OutPinLevel", this->out_pin_level_select_);
142 LOG_BUTTON(
" ",
"FactoryReset", this->factory_reset_button_);
143 LOG_BUTTON(
" ",
"Query", this->query_button_);
144 LOG_BUTTON(
" ",
"Restart", this->restart_button_);
148void DFRobotSEN0609Component::setup() {
152 switch_::Switch *sw = this->switches_[i];
156 this->publish_switch_(
static_cast<SwitchSetting>(i), sw->get_initial_write_state().value_or(!sw->is_inverted()));
159 this->queue_configuration_();
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;
169 this->run_sequencer_();
172void DFRobotSEN0609Component::readline_(uint8_t c) {
173 char *
line = this->line_reader_.feed(c);
174 if (
line !=
nullptr) {
175 this->handle_line_(
line);
178 this->line_reader_.log_if_overflowed(TAG);
180 if (c ==
'>' && ESPHOME_strcmp_P(this->line_reader_.partial(), ESPHOME_PSTR(
"DFRobot:/>")) == 0) {
181 this->line_reader_.reset();
185void DFRobotSEN0609Component::handle_line_(
char *
line) {
188 ESP_LOGV(TAG,
"RX: %s",
line);
189 if (
line[0] ==
'$') {
190 this->handle_frame_(
line);
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 &&
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);
204 if (this->operation_ == Operation::OPERATION_NONE) {
205 ESP_LOGD(TAG,
"Ignored line, no command pending: %s",
line);
208 if (strcmp(
line, this->command_) == 0) {
209 this->echo_seen_ =
true;
213 if (!this->echo_seen_) {
214 ESP_LOGD(TAG,
"Ignored line from an earlier command: %s",
line);
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) {
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_();
231 ESP_LOGD(TAG,
"Unexpected answer to '%s': %s", this->command_,
line);
235void DFRobotSEN0609Component::handle_frame_(
char *
line) {
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);
244#ifdef USE_BINARY_SENSOR
245 PUBLISH_STATE(this->has_target_binary_sensor_, presence ==
'1');
250 if (!starts_with(
line, ESPHOME_PSTR(
"$DFDMD,"))) {
251 this->log_bad_frame_(LOG_STR(
"Unknown frame"),
line);
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);
260 if (!targets.has_value()) {
261 this->log_bad_frame_(LOG_STR(
"Malformed target frame"),
line);
265#ifdef USE_BINARY_SENSOR
266 PUBLISH_STATE(this->has_target_binary_sensor_,
false);
269 this->publish_target_(NAN, NAN, NAN);
276 if (!distance.has_value() || !
speed.has_value() || !energy.has_value()) {
277 this->log_bad_frame_(LOG_STR(
"Malformed target frame"),
line);
280#ifdef USE_BINARY_SENSOR
281 PUBLISH_STATE(this->has_target_binary_sensor_,
true);
284 this->publish_target_(*distance, *
speed, *energy);
288void DFRobotSEN0609Component::log_bad_frame_(
const LogString *problem,
const char *
line) {
290 if (this->bad_frame_logged_)
292 this->bad_frame_logged_ =
true;
293 ESP_LOGW(TAG,
"%s: %s", LOG_STR_ARG(problem),
line);
298 if (std::isnan(
value)) {
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);
312void DFRobotSEN0609Component::parse_response_(
const char *args) {
313 this->response_count_ = 0;
314 while (this->response_count_ < MAX_RESPONSE_VALUES) {
316 const float value = strtof(args, &
end);
318 if (
end == args || !std::isfinite(
value))
320 this->response_[this->response_count_++] =
value;
325void DFRobotSEN0609Component::queue_configuration_() {
328 if (this->mode_ == RunMode::RUN_MODE_PRESENCE)
336 this->pending_writes_ |= writes;
337 this->pending_reads_ |= this->wanted_reads_();
340uint16_t DFRobotSEN0609Component::wanted_reads_()
const {
342#ifdef USE_TEXT_SENSOR
343 if (this->version_text_sensor_ !=
nullptr)
345 if (this->hardware_version_text_sensor_ !=
nullptr)
350 if (this->numbers_[i] !=
nullptr)
359 if (this->out_pin_level_select_ !=
nullptr)
365void DFRobotSEN0609Component::check_frames_(
uint32_t now) {
367 if (this->mode_ != RunMode::RUN_MODE_PRESENCE || now - this->last_frame_ms_ < FRAME_TIMEOUT_MS)
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();
376 this->last_frame_ms_ = now;
377 this->queue_configuration_();
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_)
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);
393void DFRobotSEN0609Component::restart() {
394 this->restart_pending_ =
true;
395 this->hold_(COMMAND_GAP_MS);
398void DFRobotSEN0609Component::factory_reset() {
399 this->factory_reset_pending_ =
true;
400 this->hold_(COMMAND_GAP_MS);
403void DFRobotSEN0609Component::query_params() {
404 this->pending_reads_ |= this->wanted_reads_();
405 this->hold_(COMMAND_GAP_MS);
409void DFRobotSEN0609Component::control_number(NumberSetting setting,
float value) {
411 const auto &values = this->number_values_;
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]);
422 this->changed_numbers_ |= 1U << setting;
423 this->publish_number_(setting,
value);
427void DFRobotSEN0609Component::control_number(number::Number *number,
float value) {
429 if (this->numbers_[i] == number) {
436void DFRobotSEN0609Component::forget_number_changes_(
Param param,
bool unknown) {
440 this->changed_numbers_ &= ~(1U << i);
447 this->number_values_[setting] =
value;
448 PUBLISH_STATE(this->numbers_[setting],
value);
454 this->publish_switch_(setting,
state);
457 this->request_write_(PARAM_MICRO_MOTION);
460 this->request_write_(PARAM_RUN_LED);
463 this->request_write_(PARAM_OUT_LED);
469 this->switch_states_[setting] =
state;
470 PUBLISH_STATE(this->switches_[setting],
state);
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);
482void DFRobotSEN0609Component::hold_(
uint32_t duration_ms) {
484 this->hold_ms_ = duration_ms;
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;
495 case Operation::OPERATION_FACTORY_RESET:
496 timeout = FACTORY_RESET_TIMEOUT_MS;
498 case Operation::OPERATION_STOP:
499 case Operation::OPERATION_SAVE:
500 timeout = LONG_TIMEOUT_MS;
505 if (now - this->sent_ms_ < timeout)
507 if (this->operation_ == Operation::OPERATION_RESTART) {
508 this->finish_operation_();
510 ESP_LOGD(TAG,
"No answer to '%s'", this->command_);
511 this->fail_operation_();
515 if (now - this->hold_start_ms_ < this->hold_ms_)
518 const bool work_pending =
519 this->factory_reset_pending_ || this->save_pending_ || this->pending_writes_ != 0 || this->pending_reads_ != 0;
522 if (this->restart_pending_) {
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);
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;
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_) {
547 if (now - this->last_change_ms_ < COALESCE_MS)
549 operation = Operation::OPERATION_SAVE;
551 operation = Operation::OPERATION_READ;
552 param =
static_cast<Param>(__builtin_ctz(this->pending_reads_));
555 const uint16_t bit = param_bit(param);
556 bool built = this->build_command_(operation, param);
557 if (!built && operation == Operation::OPERATION_WRITE) {
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);
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;
574 this->forget_number_changes_(param,
true);
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;
581 this->sequence_failed_ =
true;
582 this->status_set_warning();
586 if (operation == Operation::OPERATION_WRITE) {
587 this->pending_writes_ &= ~bit;
588 this->paired_reads_ &= ~bit;
590 this->forget_number_changes_(param,
false);
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));
605 char *buf = this->command_;
606 constexpr size_t len = MAX_COMMAND_LENGTH;
608 case Operation::OPERATION_STOP:
609 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"sensorStop"),
len);
611 case Operation::OPERATION_START:
612 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"sensorStart"),
len);
614 case Operation::OPERATION_RESTART:
615 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"resetSystem"),
len);
617 case Operation::OPERATION_FACTORY_RESET:
618 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"resetCfg"),
len);
620 case Operation::OPERATION_SAVE:
621 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"saveConfig"),
len);
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';
632 ESPHOME_snprintf_P(buf,
len, ESPHOME_PSTR(
"setRunApp %u"),
static_cast<unsigned>(this->mode_));
635 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"setUartOutput 1 1 1 1.0"),
len);
639 ESPHOME_snprintf_P(buf,
len, ESPHOME_PSTR(
"setMicroMotion %u"),
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);
653 ESPHOME_snprintf_P(buf,
len, ESPHOME_PSTR(
"setGpioMode 1 %u"),
static_cast<unsigned>(this->out_pin_level_));
661 const auto &values = this->number_values_;
664 ESPHOME_PGM_P
format =
nullptr;
669 format = ESPHOME_PSTR(
"setRange %.2f %.2f");
673 format = ESPHOME_PSTR(
"setTrigRange %.2f");
678 format = ESPHOME_PSTR(
"setSensitivity %.0f %.0f");
683 format = ESPHOME_PSTR(
"setLatency %.2f %.1f");
687 format = ESPHOME_PSTR(
"setInhibit %.2f");
691 format = ESPHOME_PSTR(
"setThrFactor %.0f");
697 if (std::isnan(first) || std::isnan(
second))
706bool DFRobotSEN0609Component::apply_read_(
Param param) {
707 const float *r = this->response_;
708 const uint8_t
count = this->response_count_;
710 const bool write_pending = (this->pending_writes_ & param_bit(param)) != 0;
714 if ((this->changed_numbers_ & (1U << setting)) == 0)
715 this->publish_number_(setting,
value);
765 if (
count < 2 || (r[1] != 0.0f && r[1] != 1.0f))
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_);
776 return this->version_received_;
782void DFRobotSEN0609Component::finish_operation_() {
783 switch (this->operation_) {
784 case Operation::OPERATION_STOP:
785 this->stopped_ =
true;
787 case Operation::OPERATION_START:
788 this->stopped_ =
false;
790 if (!this->sequence_failed_)
791 this->status_clear_warning();
792 this->sequence_failed_ =
false;
794 case Operation::OPERATION_RESTART:
796 this->restart_pending_ =
false;
797 this->stopped_ =
false;
798 this->queue_configuration_();
800 case Operation::OPERATION_FACTORY_RESET:
801 this->factory_reset_pending_ =
false;
802 this->queue_configuration_();
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;
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);
816 case Operation::OPERATION_SAVE:
817 this->save_pending_ =
false;
818 this->deferred_save_ =
false;
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_();
826 this->pending_reads_ &= ~param_bit(this->param_);
827 this->paired_reads_ &= ~param_bit(this->param_);
832 if (this->is_aux_operation_()) {
833 this->aux_attempts_ = 0;
837 this->operation_ = Operation::OPERATION_NONE;
838 this->hold_(COMMAND_GAP_MS);
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_);
855 this->status_set_warning();
856 if (aux || keep_write) {
858 ESP_LOGW(TAG,
"Command '%s' failed, trying again later", this->command_);
859 this->hold_ms_ = GIVE_UP_BACKOFF_MS;
862 ESP_LOGW(TAG,
"Giving up on %s '%s'", LOG_STR_ARG(operation_to_str(operation)), this->command_);
863 this->sequence_failed_ =
true;
865 case Operation::OPERATION_RESTART:
866 this->restart_pending_ =
false;
868 case Operation::OPERATION_FACTORY_RESET:
869 this->factory_reset_pending_ =
false;
871 case Operation::OPERATION_WRITE:
873 if (is_led(this->param_)) {
875 if ((this->pending_writes_ & param_bit(this->param_)) != 0)
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);
882 this->deferred_writes_ |= param_bit(this->param_);
889 this->pending_reads_ |= this->wanted_reads_() & param_bit(this->param_);
891 case Operation::OPERATION_SAVE:
893 this->save_pending_ =
false;
894 this->deferred_save_ =
true;
897 case Operation::OPERATION_READ:
898 this->pending_reads_ &= ~param_bit(this->param_);
PROGMEM_STRING_TABLE(ReadCommands, "", "", "getRange", "getTrigRange", "getSensitivity", "getLatency", "getInhibit", "getThrFactor", "getMicroMotion", "getGpioMode 1", "", "", "getSWV", "getHWV")