ESPHome 2025.5.0
Loading...
Searching...
No Matches
uart_transport.cpp
Go to the documentation of this file.
1#include "esphome/core/log.h"
3#include "uart_transport.h"
4
5namespace esphome {
6namespace uart {
7
8static const char *const TAG = "uart_transport";
9
11 PacketTransport::loop();
12
13 while (this->parent_->available()) {
14 uint8_t byte;
15 if (!this->parent_->read_byte(&byte)) {
16 ESP_LOGW(TAG, "Failed to read byte from UART");
17 return;
18 }
19 if (byte == FLAG_BYTE) {
20 if (this->rx_started_ && this->receive_buffer_.size() > 6) {
21 auto len = this->receive_buffer_.size();
22 auto crc = crc16(this->receive_buffer_.data(), len - 2);
23 if (crc != (this->receive_buffer_[len - 2] | (this->receive_buffer_[len - 1] << 8))) {
24 ESP_LOGD(TAG, "CRC mismatch, discarding packet");
25 this->rx_started_ = false;
26 this->receive_buffer_.clear();
27 continue;
28 }
29 this->receive_buffer_.resize(len - 2);
30 this->process_(this->receive_buffer_);
31 this->rx_started_ = false;
32 } else {
33 this->rx_started_ = true;
34 }
35 this->receive_buffer_.clear();
36 this->rx_control_ = false;
37 continue;
38 }
39 if (!this->rx_started_)
40 continue;
41 if (byte == CONTROL_BYTE) {
42 this->rx_control_ = true;
43 continue;
44 }
45 if (this->rx_control_) {
46 byte ^= 0x20;
47 this->rx_control_ = false;
48 }
49 if (this->receive_buffer_.size() == MAX_PACKET_SIZE) {
50 ESP_LOGD(TAG, "Packet too large, discarding");
51 this->rx_started_ = false;
52 this->receive_buffer_.clear();
53 continue;
54 }
55 this->receive_buffer_.push_back(byte);
56 }
57}
58
60 this->updated_ = true;
61 this->resend_data_ = true;
62 PacketTransport::update();
63}
64
69void UARTTransport::write_byte_(uint8_t byte) const {
70 if (byte == FLAG_BYTE || byte == CONTROL_BYTE) {
71 this->parent_->write_byte(CONTROL_BYTE);
72 byte ^= 0x20;
73 }
74 this->parent_->write_byte(byte);
75}
76
77void UARTTransport::send_packet(const std::vector<uint8_t> &buf) const {
78 this->parent_->write_byte(FLAG_BYTE);
79 for (uint8_t byte : buf) {
80 this->write_byte_(byte);
81 }
82 auto crc = crc16(buf.data(), buf.size());
83 this->write_byte_(crc & 0xFF);
84 this->write_byte_(crc >> 8);
85 this->parent_->write_byte(FLAG_BYTE);
86}
87} // namespace uart
88} // namespace esphome
void process_(const std::vector< uint8_t > &data)
Process a received packet.
void write_byte(uint8_t data)
bool read_byte(uint8_t *data)
UARTComponent * parent_
Definition uart.h:68
std::vector< uint8_t > receive_buffer_
void send_packet(const std::vector< uint8_t > &buf) const override
void write_byte_(uint8_t byte) const
Write a byte to the UART bus.
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition helpers.cpp:112
std::string size_t len
Definition helpers.h:301