ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
rs485_frame.cpp
Go to the documentation of this file.
1#include "rs485_frame.h"
2
4#include "esphome/core/log.h"
6
7#include <algorithm>
8#include <cinttypes>
9#include <cstring>
10
12
13ESPHOME_LOG_TAG(TAG, "rs485_frame");
14
15PROGMEM_STRING_TABLE(CrcTypeStrings, "none", "sum8", "sum16_big_endian", "sum16_little_endian", "xor8", "crc16_modbus");
16PROGMEM_STRING_TABLE(CrcVariantStrings, "header_inclusive", "payload_only");
17PROGMEM_STRING_TABLE(GateModeStrings, "frame_trigger", "idle_gap", "fixed_delay");
18PROGMEM_STRING_TABLE(QueuePolicyStrings, "replace_latest", "fifo");
19
21 // idle_gap waits min_silence from boot on a quiet bus; fixed_delay may send right away.
22 const uint32_t now = millis();
23 this->last_activity_time_ = now;
24 this->last_tx_time_ = now - this->tx_gate_interval_;
25}
26
29 // Checked before draining, since new bytes refresh last_rx_time_ and could complete the stale frame.
30 if (this->rx_state_ >= RX_STATE_FRAME && this->in_frame_timeout_ms_ > 0 &&
31 now - this->last_rx_time_ >= this->in_frame_timeout_ms_) {
32 ESP_LOGV(TAG, "Intra-frame timeout, resetting receive state");
33 this->reset_rx_();
34 }
35 this->read_available([this, now](uint8_t byte) { this->handle_rx_byte_(byte, now); });
36
37 // Transmits only after this pass's RX is drained, so frame_trigger sees any byte that followed the gate frame.
38 this->maybe_tx_(now);
39 if (this->flags_.tx_start_pending && now - this->tx_delay_start_ >= this->tx_gate_delay_ &&
40 this->gate_allows_send_(now)) {
41 this->flags_.tx_start_pending = false;
42 this->transmit_head_(now);
43 }
44}
45
47 uint8_t gate[MAX_FRAME_TYPE_LEN];
49 char gate_hex[format_hex_size(MAX_FRAME_TYPE_LEN)];
50 format_hex_to(gate_hex, gate, this->tx_gate_frame_type_len_);
51 ESP_LOGCONFIG(TAG,
52 "RS485 Frame:\n"
53 " Framing: DLE=0x%02x STX=0x%02x ETX=0x%02x, escape=0x%02x\n"
54 " CRC type: %s, TX CRC variant: %s, accept header CRC: %s, accept payload CRC: %s\n"
55 " TX gate: %s, gate frame: %s, gate delay: %ums\n"
56 " TX gate interval: %ums\n"
57 " Queue policy: %s, queue size: %u\n"
58 " Max frame length: %u, frame timeout: %ums\n"
59 " Sniffer only: %s, dump frames: %s",
60 this->dle_, this->stx_, this->etx_, this->escape_marker_,
61 LOG_STR_ARG(CrcTypeStrings::get_log_str(this->crc_type_, 0)),
62 LOG_STR_ARG(CrcVariantStrings::get_log_str(this->tx_crc_variant_, 0)),
63 YESNO(this->flags_.accept_header_crc), YESNO(this->flags_.accept_payload_crc),
64 LOG_STR_ARG(GateModeStrings::get_log_str(this->tx_gate_mode_, 0)), gate_hex, this->tx_gate_delay_,
65 this->tx_gate_interval_, LOG_STR_ARG(QueuePolicyStrings::get_log_str(this->queue_policy_, 0)),
67 YESNO(this->tx_queue_ == nullptr), YESNO(this->flags_.dump_frames));
68}
69
70bool RS485FrameHub::queue_raw_frame(std::span<const uint8_t> frame_type, std::span<const uint8_t> payload) {
71 if (this->tx_queue_ == nullptr) {
72 ESP_LOGW(TAG, "Ignoring frame because sniffer_only is enabled");
73 return false;
74 }
75 const size_t len = frame_type.size() + payload.size();
77 ESP_LOGW(TAG, "Frame length %zu is outside %zu..max_frame_length (%u); dropping", len, MIN_FRAME_LENGTH,
78 this->max_frame_length_);
79 return false;
80 }
81 size_t index = this->tx_queue_head_;
82 if (this->queue_policy_ == QUEUE_FIFO) {
83 if (this->tx_queue_count_ >= this->max_queue_size_) {
84 ESP_LOGW(TAG, "Frame queue full; dropping frame");
85 return false;
86 }
87 index += this->tx_queue_count_;
88 if (index >= this->max_queue_size_)
89 index -= this->max_queue_size_;
90 }
91 // A UART debug or log callback queued while that slot is being sent.
92 if (index == this->tx_sending_slot_) {
93 ESP_LOGW(TAG, "Frame queued while the previous frame was being sent; dropping frame");
94 return false;
95 }
97 if (this->tx_queue_count_ > 0) {
98 ESP_LOGV(TAG, "Replacing pending frame before it was transmitted");
99 }
100 this->tx_queue_count_ = 0;
101 }
102 uint8_t *slot = this->tx_slot_(index);
103 progmem_memcpy(slot, frame_type.data(), frame_type.size());
104 progmem_memcpy(slot + frame_type.size(), payload.data(), payload.size());
105 this->encode_crc_(slot, len, this->tx_crc_variant_ == CRC_HEADER_INCLUSIVE, slot + len);
106 this->tx_queue_len_[index] = len + this->crc_len_;
107 this->tx_queue_count_++;
108 return true;
109}
110
112
114 this->last_rx_time_ = now;
115 this->last_activity_time_ = now;
116 // frame_trigger answers in the gap right after the gate frame; a later byte means another node took it.
118 this->flags_.tx_start_pending = false;
119 // After a DLE: STX (re)starts a frame, ETX ends it, the escape marker is a literal DLE, anything else drops it.
120 const RxState after_other_dle = byte == this->dle_ ? RX_STATE_IDLE_DLE : RX_STATE_IDLE;
121 switch (this->rx_state_) {
122 case RX_STATE_IDLE:
123 this->rx_state_ = after_other_dle;
124 return;
125 case RX_STATE_FRAME:
126 if (byte == this->dle_) {
128 } else {
129 this->append_rx_(byte);
130 }
131 return;
133 if (byte == this->stx_) {
135 this->rx_payload_len_ = 0;
136 } else {
137 this->rx_state_ = after_other_dle;
138 }
139 return;
140 default: // RX_STATE_FRAME_DLE
141 if (byte == this->stx_) {
143 this->rx_payload_len_ = 0;
144 } else if (byte == this->etx_) {
145 this->reset_rx_();
146 this->process_frame_(now);
147 } else if (byte == this->escape_marker_) {
149 this->append_rx_(this->dle_);
150 } else {
151 this->rx_state_ = after_other_dle;
152 }
153 return;
154 }
155}
156
157void RS485FrameHub::append_rx_(uint8_t byte) {
158 if (this->rx_payload_len_ == this->max_frame_length_ + this->crc_len_) {
159 ESP_LOGW(TAG, "Frame exceeded max_frame_length; resetting");
160 this->reset_rx_();
161 return;
162 }
163 this->rx_payload_[this->rx_payload_len_++] = byte;
164}
165
168 return;
169 this->rx_payload_len_ -= this->crc_len_;
170 if (!this->check_crc_())
171 return;
172 if (this->flags_.dump_frames)
173 this->log_frame_(LOG_STR("RX"), this->rx_payload_, this->rx_payload_len_ + this->crc_len_);
174
175 const std::span<const uint8_t> payload(this->rx_payload_, this->rx_payload_len_);
176 // Released after the callbacks, so a reply they queue goes out in this gap.
177 this->frame_callback_.call(payload);
180 this->send_next_(now);
181}
182
184 return this->crc_len_ == 0 || (this->flags_.accept_header_crc && this->crc_matches_(true)) ||
185 (this->flags_.accept_payload_crc && this->crc_matches_(false));
186}
187
188bool RS485FrameHub::crc_matches_(bool include_header) const {
189 uint8_t crc[2]{};
190 this->encode_crc_(this->rx_payload_, this->rx_payload_len_, include_header, crc);
191 return memcmp(crc, this->rx_payload_ + this->rx_payload_len_, this->crc_len_) == 0;
192}
193
194void RS485FrameHub::encode_crc_(const uint8_t *data, size_t len, bool include_header, uint8_t *out) const {
195 const uint8_t header[2] = {this->dle_, this->stx_};
196 const size_t header_len = include_header ? sizeof(header) : 0;
197 switch (this->crc_type_) {
198 case CRC_TYPE_SUM8:
199 out[0] = sum_bytes(data, len, sum_bytes(header, header_len));
200 return;
201 case CRC_TYPE_XOR8:
202 out[0] = xor_bytes(data, len, xor_bytes(header, header_len));
203 return;
205 put_be16(out, sum16_bytes(data, len, sum16_bytes(header, header_len)));
206 return;
208 put_le16(out, sum16_bytes(data, len, sum16_bytes(header, header_len)));
209 return;
211 put_le16(out, crc16(data, static_cast<uint16_t>(len), crc16(header, static_cast<uint16_t>(header_len))));
212 return;
213 default:
214 return;
215 }
216}
217
219 if (this->tx_queue_count_ == 0 || this->flags_.tx_start_pending || this->tx_gate_mode_ == TX_GATE_FRAME_TRIGGER)
220 return;
222 return;
223 if (this->tx_gate_mode_ == TX_GATE_FIXED_DELAY || this->bus_silent_(now))
224 this->send_next_(now);
225}
226
228 if (this->flags_.tx_start_pending || this->tx_queue_count_ == 0)
229 return;
230 this->tx_delay_start_ = now;
231 this->flags_.tx_start_pending = true;
232}
233
235 const uint8_t slot = this->tx_queue_head_;
236 const uint8_t *frame = this->tx_slot_(slot);
237 const size_t len = this->tx_queue_len_[slot];
238 // Dequeued before any callback runs, so a frame they queue is kept; the slot stays reserved until sent and logged.
239 if (++this->tx_queue_head_ == this->max_queue_size_)
240 this->tx_queue_head_ = 0;
241 this->tx_queue_count_--;
242 this->tx_sending_slot_ = slot;
243 static constexpr size_t TX_CHUNK_SIZE = 32;
244 uint8_t chunk[TX_CHUNK_SIZE];
245 size_t pos = 0;
246 size_t wire_len = 0;
247 auto put = [&](uint8_t byte) {
248 chunk[pos++] = byte;
249 if (pos == TX_CHUNK_SIZE) {
250 this->write_array(chunk, pos);
251 wire_len += pos;
252 pos = 0;
253 }
254 };
255 this->encode_wire_(frame, len, put);
256 if (pos > 0)
257 this->write_array(chunk, pos);
258 wire_len += pos;
259#if defined(USE_ESP8266) || defined(USE_RP2)
260 // No hardware DE control here, so an auto-DE transceiver needs the bytes out before returning.
261 this->flush();
262#endif
263 if (this->flags_.dump_frames)
264 this->log_frame_(LOG_STR("TX"), frame, len);
265 this->tx_sending_slot_ = NO_SLOT;
266 this->last_tx_time_ = now;
267 this->last_tx_wire_ms_ = this->wire_time_ms_(wire_len);
268 this->last_activity_time_ = now;
269}
270
271uint16_t RS485FrameHub::wire_time_ms_(size_t len) const {
272 const uint32_t baud = this->parent_->get_baud_rate();
273 if (baud == 0)
274 return 0;
275 const uint32_t bits = 1 + this->parent_->get_data_bits() +
276 (this->parent_->get_parity() != uart::UART_CONFIG_PARITY_NONE ? 1 : 0) +
277 this->parent_->get_stop_bits();
278 return std::min<uint32_t>((len * bits * 1000 + baud - 1) / baud, UINT16_MAX);
279}
280
281void RS485FrameHub::log_frame_(const LogString *dir, const uint8_t *data, size_t len) {
282#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
283 static constexpr size_t BYTES_PER_LINE = 32;
284 uint8_t line[BYTES_PER_LINE];
285 char hex[format_hex_size(BYTES_PER_LINE)];
286 size_t pos = 0;
287 auto log_line = [&]() {
288 format_hex_to(hex, line, pos);
289 ESP_LOGD(TAG, "%s %s", LOG_STR_ARG(dir), hex);
290 pos = 0;
291 };
292 this->encode_wire_(data, len, [&](uint8_t byte) {
293 line[pos++] = byte;
294 if (pos == BYTES_PER_LINE)
295 log_line();
296 });
297 if (pos > 0)
298 log_line();
299#endif
300}
301
302} // namespace esphome::rs485_frame
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void handle_rx_byte_(uint8_t byte, uint32_t now)
void encode_crc_(const uint8_t *data, size_t len, bool include_header, uint8_t *out) const
bool queue_raw_frame(std::span< const uint8_t > frame_type, std::span< const uint8_t > payload)
Frame and queue frame_type followed by payload; both may live in PROGMEM.
uint8_t * tx_slot_(size_t index) const
bool crc_matches_(bool include_header) const
void log_frame_(const LogString *dir, const uint8_t *data, size_t len)
bool bus_silent_(uint32_t now) const
uint16_t wire_time_ms_(size_t len) const
LazyCallbackManager< void(std::span< const uint8_t >)> frame_callback_
void encode_wire_(const uint8_t *data, size_t len, F &&put) const
Passes the wire bytes of an unescaped frame to put: DLE STX, the escaped frame, DLE ETX.
UARTParityOptions get_parity() const
UARTFlushResult flush()
Definition uart.h:96
UARTComponent * parent_
Definition uart.h:134
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
std::vector< uint8_t > & out
Definition gif.cpp:49
bool frame_has_prefix(std::span< const uint8_t > payload, const uint8_t *prefix, size_t len)
True when payload starts with the len-byte prefix, which may live in PROGMEM.
Definition rs485_frame.h:36
RxState
The _DLE states mean the last byte was a DLE.
Definition rs485_frame.h:33
ESPHOME_LOG_TAG(TAG, "rs485_frame")
PROGMEM_STRING_TABLE(CrcTypeStrings, "none", "sum8", "sum16_big_endian", "sum16_little_endian", "xor8", "crc16_modbus")
constexpr uint8_t xor_bytes(const uint8_t *data, size_t len, uint8_t init=0)
XOR the bytes of data with size len, starting from init.
Definition helpers.h:1084
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:114
constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum=0)
Add up the bytes of data with size len, truncated to 8 bits: the checksum many serial and IR protocol...
Definition helpers.h:1074
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
const void size_t len
Definition hal.h:68
void const char int line
Definition log.h:110
size_t size_t pos
Definition helpers.h:1493
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
Definition helpers.h:1851
constexpr uint8_t * put_be16(uint8_t *dst, uint16_t value)
Write the low 16, 24 or 32 bits of value to dst, most significant byte first (be) or least significan...
Definition helpers.h:1268
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:459
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint16_t sum16_bytes(const uint8_t *data, size_t len, uint16_t sum=0)
Add up the bytes of data with size len, truncated to 16 bits.
Definition helpers.h:1079
constexpr uint8_t * put_le16(uint8_t *dst, uint16_t value)
Definition helpers.h:1286
static void uint32_t