ESPHome 2026.1.0-dev
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::uart {
6
7static const char *const TAG = "uart_transport";
8
10 PacketTransport::loop();
11
12 while (this->parent_->available()) {
13 uint8_t byte;
14 if (!this->parent_->read_byte(&byte)) {
15 ESP_LOGW(TAG, "Failed to read byte from UART");
16 return;
17 }
18 if (byte == FLAG_BYTE) {
19 if (this->rx_started_ && this->receive_buffer_.size() > 6) {
20 auto len = this->receive_buffer_.size();
21 auto crc = crc16(this->receive_buffer_.data(), len - 2);
22 if (crc != (this->receive_buffer_[len - 2] | (this->receive_buffer_[len - 1] << 8))) {
23 ESP_LOGD(TAG, "CRC mismatch, discarding packet");
24 this->rx_started_ = false;
25 this->receive_buffer_.clear();
26 continue;
27 }
28 this->receive_buffer_.resize(len - 2);
29 this->process_(this->receive_buffer_);
30 this->rx_started_ = false;
31 } else {
32 this->rx_started_ = true;
33 }
34 this->receive_buffer_.clear();
35 this->rx_control_ = false;
36 continue;
37 }
38 if (!this->rx_started_)
39 continue;
40 if (byte == CONTROL_BYTE) {
41 this->rx_control_ = true;
42 continue;
43 }
44 if (this->rx_control_) {
45 byte ^= 0x20;
46 this->rx_control_ = false;
47 }
48 if (this->receive_buffer_.size() == MAX_PACKET_SIZE) {
49 ESP_LOGD(TAG, "Packet too large, discarding");
50 this->rx_started_ = false;
51 this->receive_buffer_.clear();
52 continue;
53 }
54 this->receive_buffer_.push_back(byte);
55 }
56}
57
62void UARTTransport::write_byte_(uint8_t byte) const {
63 if (byte == FLAG_BYTE || byte == CONTROL_BYTE) {
64 this->parent_->write_byte(CONTROL_BYTE);
65 byte ^= 0x20;
66 }
67 this->parent_->write_byte(byte);
68}
69
70void UARTTransport::send_packet(const std::vector<uint8_t> &buf) const {
71 this->parent_->write_byte(FLAG_BYTE);
72 for (uint8_t byte : buf) {
73 this->write_byte_(byte);
74 }
75 auto crc = crc16(buf.data(), buf.size());
76 this->write_byte_(crc & 0xFF);
77 this->write_byte_(crc >> 8);
78 this->parent_->write_byte(FLAG_BYTE);
79}
80
81} // namespace esphome::uart
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:73
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: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:72
std::string size_t len
Definition helpers.h:533