ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
dfrobot_sen0465_uart.cpp
Go to the documentation of this file.
2
3#include <algorithm>
4
6
7using dfrobot_sen0465_base::FRAME_HEAD;
8using dfrobot_sen0465_base::FRAME_SIZE;
9using dfrobot_sen0465_base::RESPONSE_TIMEOUT_ID;
10
11// The DFRobot library waits up to this long for an answer
12static constexpr uint32_t RESPONSE_TIMEOUT_MS = 3000;
13
15 // loop() only runs while an answer is expected
16 this->disable_loop();
17 DFRobotSEN0465Component::setup();
18}
19
21 // The tail of a reading the probe sent on its own may precede the answer; start at the next frame head.
22 uint8_t byte;
23 while (this->rx_count_ == 0 && this->peek_byte(&byte) && byte != FRAME_HEAD)
24 this->read_byte(&byte);
25 const size_t available = this->available();
26 if (available == 0)
27 return;
28 const size_t len = std::min<size_t>(available, FRAME_SIZE - this->rx_count_);
29 if (!this->read_array(this->rx_buffer_ + this->rx_count_, len))
30 return;
31 this->rx_count_ += len;
32 if (this->rx_count_ < FRAME_SIZE)
33 return;
34
35 this->rx_count_ = 0;
36 this->cancel_timeout(RESPONSE_TIMEOUT_ID);
37 this->disable_loop();
38 this->handle_response_(this->rx_buffer_);
39}
40
41bool DFRobotSEN0465UARTComponent::write_frame(const uint8_t *frame) {
42 // Drop anything left over, such as the answer to the mode change or readings sent before passive mode was set
43 this->discard_available();
44 this->rx_count_ = 0;
45 this->write_array(frame, FRAME_SIZE);
46 return true;
47}
48
50 this->enable_loop();
51 this->set_timeout(RESPONSE_TIMEOUT_ID, RESPONSE_TIMEOUT_MS, [this]() {
52 this->disable_loop();
53 this->rx_count_ = 0;
54 this->handle_no_response_();
55 });
56}
57
58} // namespace esphome::dfrobot_sen0465_uart
bool cancel_timeout(const char *name)
Cancel a timeout function.
void enable_loop()
Enable this component's loop.
Definition component.h:248
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void disable_loop()
Disable this component's loop.
optional< std::array< uint8_t, N > > read_array()
Definition uart.h:43
bool peek_byte(uint8_t *data)
Definition uart.h:40
void discard_available()
Read and drop every byte waiting in the receive buffer.
Definition uart.cpp:36
bool read_byte(uint8_t *data)
Definition uart.h:39
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
const void size_t len
Definition hal.h:68
static void uint32_t