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"));
97static const LogString *operation_to_str(
Operation 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");
114 return LOG_STR(
"none");
118DFRobotSEN0609Component::DFRobotSEN0609Component(
RunMode mode) : mode_(
mode) {
120 this->number_values_.fill(NAN);
124void DFRobotSEN0609Component::dump_config() {
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_);
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_);
138#ifdef USE_TEXT_SENSOR
139 LOG_TEXT_SENSOR(
" ",
"Version", this->version_text_sensor_);
140 LOG_TEXT_SENSOR(
" ",
"HardwareVersion", this->hardware_version_text_sensor_);
143 for (number::Number *n : this->numbers_) {
144 LOG_NUMBER(
" ",
"Number", n);
148 for (switch_::Switch *s : this->switches_) {
149 LOG_SWITCH(
" ",
"Switch", s);
153 LOG_SELECT(
" ",
"OutPinLevel", this->out_pin_level_select_);
156 LOG_BUTTON(
" ",
"FactoryReset", this->factory_reset_button_);
157 LOG_BUTTON(
" ",
"Query", this->query_button_);
158 LOG_BUTTON(
" ",
"Restart", this->restart_button_);
162void DFRobotSEN0609Component::setup() {
166 switch_::Switch *sw = this->switches_[i];
170 this->publish_switch_(
static_cast<SwitchSetting>(i), sw->get_initial_write_state().value_or(!sw->is_inverted()));
173 this->queue_configuration_();
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;
183 this->run_sequencer_();
186void DFRobotSEN0609Component::readline_(uint8_t c) {
187 char *line = this->line_reader_.feed(c);
188 if (line !=
nullptr) {
189 this->handle_line_(line);
192 this->line_reader_.log_if_overflowed(TAG);
194 if (c ==
'>' && ESPHOME_strcmp_P(this->line_reader_.partial(), ESPHOME_PSTR(
"DFRobot:/>")) == 0) {
195 this->line_reader_.reset();
199void DFRobotSEN0609Component::handle_line_(
char *line) {
202 ESP_LOGV(TAG,
"RX: %s", line);
203 if (line[0] ==
'$') {
204 this->handle_frame_(line);
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 &&
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);
218 if (this->operation_ == Operation::OPERATION_NONE) {
219 ESP_LOGD(TAG,
"Ignored line, no command pending: %s", line);
222 if (strcmp(line, this->command_) == 0) {
223 this->echo_seen_ =
true;
227 if (!this->echo_seen_) {
228 ESP_LOGD(TAG,
"Ignored line from an earlier command: %s", line);
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) {
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_();
245 ESP_LOGD(TAG,
"Unexpected answer to '%s': %s", this->command_, line);
249void DFRobotSEN0609Component::handle_frame_(
char *line) {
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);
258#ifdef USE_BINARY_SENSOR
259 PUBLISH_STATE(this->has_target_binary_sensor_, presence ==
'1');
264 if (!starts_with(line, ESPHOME_PSTR(
"$DFDMD,"))) {
265 this->log_bad_frame_(LOG_STR(
"Unknown frame"), line);
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);
274 if (!targets.has_value()) {
275 this->log_bad_frame_(LOG_STR(
"Malformed target frame"), line);
279#ifdef USE_BINARY_SENSOR
280 PUBLISH_STATE(this->has_target_binary_sensor_,
false);
283 this->publish_target_(NAN, NAN, NAN);
290 if (!distance.has_value() || !
speed.has_value() || !energy.has_value()) {
291 this->log_bad_frame_(LOG_STR(
"Malformed target frame"), line);
294#ifdef USE_BINARY_SENSOR
295 PUBLISH_STATE(this->has_target_binary_sensor_,
true);
298 this->publish_target_(*distance, *
speed, *energy);
302void DFRobotSEN0609Component::log_bad_frame_(
const LogString *problem,
const char *line) {
304 if (this->bad_frame_logged_)
306 this->bad_frame_logged_ =
true;
307 ESP_LOGW(TAG,
"%s: %s", LOG_STR_ARG(problem), line);
312 if (std::isnan(
value)) {
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);
326void DFRobotSEN0609Component::parse_response_(
const char *args) {
327 this->response_count_ = 0;
328 while (this->response_count_ < MAX_RESPONSE_VALUES) {
330 const float value = strtof(args, &
end);
332 if (
end == args || !std::isfinite(
value))
334 this->response_[this->response_count_++] =
value;
339void DFRobotSEN0609Component::queue_configuration_() {
342 if (this->mode_ == RunMode::RUN_MODE_PRESENCE)
350 this->pending_writes_ |= writes;
351 this->pending_reads_ |= this->wanted_reads_();
354uint16_t DFRobotSEN0609Component::wanted_reads_()
const {
356#ifdef USE_TEXT_SENSOR
357 if (this->version_text_sensor_ !=
nullptr)
359 if (this->hardware_version_text_sensor_ !=
nullptr)
364 if (this->numbers_[i] !=
nullptr)
373 if (this->out_pin_level_select_ !=
nullptr)
379void DFRobotSEN0609Component::check_frames_(
uint32_t now) {
381 if (this->mode_ != RunMode::RUN_MODE_PRESENCE || now - this->last_frame_ms_ < FRAME_TIMEOUT_MS)
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();
390 this->last_frame_ms_ = now;
391 this->queue_configuration_();
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_)
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);
407void DFRobotSEN0609Component::restart() {
408 this->restart_pending_ =
true;
409 this->hold_(COMMAND_GAP_MS);
412void DFRobotSEN0609Component::factory_reset() {
413 this->factory_reset_pending_ =
true;
414 this->hold_(COMMAND_GAP_MS);
417void DFRobotSEN0609Component::query_params() {
418 this->pending_reads_ |= this->wanted_reads_();
419 this->hold_(COMMAND_GAP_MS);
423void DFRobotSEN0609Component::control_number(NumberSetting setting,
float value) {
425 const auto &values = this->number_values_;
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]);
436 this->changed_numbers_ |= 1U << setting;
437 this->publish_number_(setting,
value);
441void DFRobotSEN0609Component::control_number(number::Number *number,
float value) {
443 if (this->numbers_[i] == number) {
450void DFRobotSEN0609Component::forget_number_changes_(
Param param,
bool unknown) {
454 this->changed_numbers_ &= ~(1U << i);
461 this->number_values_[setting] =
value;
462 PUBLISH_STATE(this->numbers_[setting],
value);
468 this->publish_switch_(setting,
state);
471 this->request_write_(PARAM_MICRO_MOTION);
474 this->request_write_(PARAM_RUN_LED);
477 this->request_write_(PARAM_OUT_LED);
483 this->switch_states_[setting] =
state;
484 PUBLISH_STATE(this->switches_[setting],
state);
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);
496void DFRobotSEN0609Component::hold_(
uint32_t duration_ms) {
498 this->hold_ms_ = duration_ms;
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;
509 case Operation::OPERATION_FACTORY_RESET:
510 timeout = FACTORY_RESET_TIMEOUT_MS;
512 case Operation::OPERATION_STOP:
513 case Operation::OPERATION_SAVE:
514 timeout = LONG_TIMEOUT_MS;
519 if (now - this->sent_ms_ < timeout)
521 if (this->operation_ == Operation::OPERATION_RESTART) {
522 this->finish_operation_();
524 ESP_LOGD(TAG,
"No answer to '%s'", this->command_);
525 this->fail_operation_();
529 if (now - this->hold_start_ms_ < this->hold_ms_)
532 const bool work_pending =
533 this->factory_reset_pending_ || this->save_pending_ || this->pending_writes_ != 0 || this->pending_reads_ != 0;
536 if (this->restart_pending_) {
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);
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;
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_) {
561 if (now - this->last_change_ms_ < COALESCE_MS)
563 operation = Operation::OPERATION_SAVE;
565 operation = Operation::OPERATION_READ;
566 param =
static_cast<Param>(__builtin_ctz(this->pending_reads_));
569 const uint16_t bit = param_bit(param);
570 bool built = this->build_command_(operation, param);
571 if (!built && operation == Operation::OPERATION_WRITE) {
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);
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;
588 this->forget_number_changes_(param,
true);
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;
595 this->sequence_failed_ =
true;
596 this->status_set_warning();
600 if (operation == Operation::OPERATION_WRITE) {
601 this->pending_writes_ &= ~bit;
602 this->paired_reads_ &= ~bit;
604 this->forget_number_changes_(param,
false);
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));
619 char *buf = this->command_;
620 constexpr size_t len = MAX_COMMAND_LENGTH;
622 case Operation::OPERATION_STOP:
623 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"sensorStop"),
len);
625 case Operation::OPERATION_START:
626 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"sensorStart"),
len);
628 case Operation::OPERATION_RESTART:
629 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"resetSystem"),
len);
631 case Operation::OPERATION_FACTORY_RESET:
632 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"resetCfg"),
len);
634 case Operation::OPERATION_SAVE:
635 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"saveConfig"),
len);
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';
646 ESPHOME_snprintf_P(buf,
len, ESPHOME_PSTR(
"setRunApp %u"),
static_cast<unsigned>(this->mode_));
649 ESPHOME_strncpy_P(buf, ESPHOME_PSTR(
"setUartOutput 1 1 1 1.0"),
len);
653 ESPHOME_snprintf_P(buf,
len, ESPHOME_PSTR(
"setMicroMotion %u"),
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);
667 ESPHOME_snprintf_P(buf,
len, ESPHOME_PSTR(
"setGpioMode 1 %u"),
static_cast<unsigned>(this->out_pin_level_));
675 const auto &values = this->number_values_;
678 ESPHOME_PGM_P
format =
nullptr;
683 format = ESPHOME_PSTR(
"setRange %.2f %.2f");
687 format = ESPHOME_PSTR(
"setTrigRange %.2f");
692 format = ESPHOME_PSTR(
"setSensitivity %.0f %.0f");
697 format = ESPHOME_PSTR(
"setLatency %.2f %.1f");
701 format = ESPHOME_PSTR(
"setInhibit %.2f");
705 format = ESPHOME_PSTR(
"setThrFactor %.0f");
711 if (std::isnan(first) || std::isnan(
second))
720bool DFRobotSEN0609Component::apply_read_(
Param param) {
721 const float *r = this->response_;
722 const uint8_t
count = this->response_count_;
724 const bool write_pending = (this->pending_writes_ & param_bit(param)) != 0;
728 if ((this->changed_numbers_ & (1U << setting)) == 0)
729 this->publish_number_(setting,
value);
779 if (
count < 2 || (r[1] != 0.0f && r[1] != 1.0f))
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_);
790 return this->version_received_;
796void DFRobotSEN0609Component::finish_operation_() {
797 switch (this->operation_) {
798 case Operation::OPERATION_STOP:
799 this->stopped_ =
true;
801 case Operation::OPERATION_START:
802 this->stopped_ =
false;
804 if (!this->sequence_failed_)
805 this->status_clear_warning();
806 this->sequence_failed_ =
false;
808 case Operation::OPERATION_RESTART:
810 this->restart_pending_ =
false;
811 this->stopped_ =
false;
812 this->queue_configuration_();
814 case Operation::OPERATION_FACTORY_RESET:
815 this->factory_reset_pending_ =
false;
816 this->queue_configuration_();
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;
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);
830 case Operation::OPERATION_SAVE:
831 this->save_pending_ =
false;
832 this->deferred_save_ =
false;
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_();
840 this->pending_reads_ &= ~param_bit(this->param_);
841 this->paired_reads_ &= ~param_bit(this->param_);
846 if (this->is_aux_operation_()) {
847 this->aux_attempts_ = 0;
851 this->operation_ = Operation::OPERATION_NONE;
852 this->hold_(COMMAND_GAP_MS);
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_);
869 this->status_set_warning();
870 if (aux || keep_write) {
872 ESP_LOGW(TAG,
"Command '%s' failed, trying again later", this->command_);
873 this->hold_ms_ = GIVE_UP_BACKOFF_MS;
876 ESP_LOGW(TAG,
"Giving up on %s '%s'", LOG_STR_ARG(operation_to_str(operation)), this->command_);
877 this->sequence_failed_ =
true;
879 case Operation::OPERATION_RESTART:
880 this->restart_pending_ =
false;
882 case Operation::OPERATION_FACTORY_RESET:
883 this->factory_reset_pending_ =
false;
885 case Operation::OPERATION_WRITE:
887 if (is_led(this->param_)) {
889 if ((this->pending_writes_ & param_bit(this->param_)) != 0)
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);
896 this->deferred_writes_ |= param_bit(this->param_);
903 this->pending_reads_ |= this->wanted_reads_() & param_bit(this->param_);
905 case Operation::OPERATION_SAVE:
907 this->save_pending_ =
false;
908 this->deferred_save_ =
true;
911 case Operation::OPERATION_READ:
912 this->pending_reads_ &= ~param_bit(this->param_);
PROGMEM_STRING_TABLE(ReadCommands, "", "", "getRange", "getTrigRange", "getSensitivity", "getLatency", "getInhibit", "getThrFactor", "getMicroMotion", "getGpioMode 1", "", "", "getSWV", "getHWV")