ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
uart_component_esp8266.cpp
Go to the documentation of this file.
1#ifdef USE_ESP8266
3#include <esp8266_peri.h>
4#include <optional>
8#include "esphome/core/log.h"
9#ifdef USE_UART_WAKE_LOOP_ON_RX
10#include "esphome/core/wake.h"
11#endif
12
13#ifdef USE_LOGGER
15#endif
16
17namespace esphome::uart {
18
19ESPHOME_LOG_TAG(TAG, "uart");
20// Edge decoder up to this baud rate; at 38400 WiFi interrupt latency corrupts bytes.
21static constexpr uint32_t SW_SERIAL_EDGE_MODE_MAX_BAUD = 19200;
22// TX locks interrupts per bit up to this baud rate and per byte above it. At 38400 byte locks still trip the Wi-Fi
23// watchdog when every byte is below 0x80, while an interrupt between bits leaves the bytes intact; at 115200 it
24// stretches bits enough to corrupt them.
25static constexpr uint32_t SW_SERIAL_TX_BIT_LOCK_MAX_BAUD = 38400;
26// Edge decoder time base: 1/16 us from the 1 MHz system timer, which keeps its rate during a
27// CpuFrequencyBoost; the cycle counter does not.
28static constexpr uint32_t RX_TICKS_PER_SECOND = 16000000;
29// A byte lock lets pending interrupts run right after an edge when the next edge is at least this far away, so their
30// delay lands inside a run of equal bits. Locks longer than about 6 bits at 57600 trip the Wi-Fi watchdog.
31static constexpr uint32_t TX_UNLOCK_MIN_RUN_CYCLES = F_CPU / 1000000 * 30;
32// Longest per-bit TX interrupt lock; the Wi-Fi interrupt handler asserts (hardware WDT) when held off about 1 ms
33static constexpr uint32_t MAX_TX_LOCK_CYCLES = F_CPU / 1000000 * 200;
34__attribute__((always_inline)) static inline uint32_t rx_now() { return micros() << 4; }
35bool ESP8266UartComponent::serial0_in_use = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
36
37bool ESP8266UartComponent::serial0_swapped = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
38
40 uint32_t config = 0;
41
42 if (this->parity_ == UART_CONFIG_PARITY_NONE) {
43 config |= UART_PARITY_NONE;
44 } else if (this->parity_ == UART_CONFIG_PARITY_EVEN) {
45 config |= UART_PARITY_EVEN;
46 } else if (this->parity_ == UART_CONFIG_PARITY_ODD) {
47 config |= UART_PARITY_ODD;
48 }
49
50 switch (this->data_bits_) {
51 case 5:
52 config |= UART_NB_BIT_5;
53 break;
54 case 6:
55 config |= UART_NB_BIT_6;
56 break;
57 case 7:
58 config |= UART_NB_BIT_7;
59 break;
60 case 8:
61 config |= UART_NB_BIT_8;
62 break;
63 }
64
65 if (this->stop_bits_ == 1) {
66 config |= UART_NB_STOP_BIT_1;
67 } else {
68 config |= UART_NB_STOP_BIT_2;
69 }
70
71 if (this->tx_pin_ != nullptr && this->tx_pin_->is_inverted())
72 config |= BIT(22);
73 if (this->rx_pin_ != nullptr && this->rx_pin_->is_inverted())
74 config |= BIT(19);
75
76 return config;
77}
78
80 auto setup_pin_if_needed = [](InternalGPIOPin *pin) {
81 if (!pin) {
82 return;
83 }
85 if ((pin->get_flags() & mask) != gpio::Flags::FLAG_NONE) {
86 pin->setup();
87 }
88 };
89
90 setup_pin_if_needed(this->rx_pin_);
91 if (this->rx_pin_ != this->tx_pin_) {
92 setup_pin_if_needed(this->tx_pin_);
93 }
94
95 // Use Arduino HardwareSerial UARTs if all used pins match the ones
96 // preconfigured by the platform. For example if RX disabled but TX pin
97 // is 1 we still want to use Serial.
98 SerialConfig config = static_cast<SerialConfig>(get_config());
99
100#ifdef USE_ESP8266_UART_SERIAL
101 if (!ESP8266UartComponent::serial0_in_use && (tx_pin_ == nullptr || tx_pin_->get_pin() == 1) &&
102 (rx_pin_ == nullptr || rx_pin_->get_pin() == 3)
103#ifdef USE_LOGGER
104 // we will use UART0 if logger isn't using it in swapped mode
105 && (logger::global_logger->get_hw_serial() == nullptr ||
107#endif
108 ) {
109 this->hw_serial_ = &Serial;
110 this->hw_serial_->begin(this->baud_rate_, config);
111 this->hw_serial_->setRxBufferSize(this->rx_buffer_size_);
112 ESP8266UartComponent::serial0_in_use = true;
113 } else if (!ESP8266UartComponent::serial0_in_use && (tx_pin_ == nullptr || tx_pin_->get_pin() == 15) &&
114 (rx_pin_ == nullptr || rx_pin_->get_pin() == 13)
115#ifdef USE_LOGGER
116 // we will use UART0 swapped if logger isn't using it in regular mode
117 && (logger::global_logger->get_hw_serial() == nullptr ||
119#endif
120 ) {
121 this->hw_serial_ = &Serial;
122 this->hw_serial_->begin(this->baud_rate_, config);
123 this->hw_serial_->setRxBufferSize(this->rx_buffer_size_);
124 this->hw_serial_->swap();
125 ESP8266UartComponent::serial0_in_use = true;
126 ESP8266UartComponent::serial0_swapped = true;
127 } else
128#endif // USE_ESP8266_UART_SERIAL
129#ifdef USE_ESP8266_UART_SERIAL1
130 if ((tx_pin_ == nullptr || tx_pin_->get_pin() == 2) && (rx_pin_ == nullptr || rx_pin_->get_pin() == 8)) {
131 this->hw_serial_ = &Serial1;
132 this->hw_serial_->begin(this->baud_rate_, config);
133 this->hw_serial_->setRxBufferSize(this->rx_buffer_size_);
134 } else
135#endif // USE_ESP8266_UART_SERIAL1
136 {
137 this->sw_serial_ = new ESP8266SoftwareSerial(); // NOLINT
138 this->sw_serial_->setup(tx_pin_, rx_pin_, this->baud_rate_, this->stop_bits_, this->data_bits_, this->parity_,
139 this->rx_buffer_size_);
140 }
141}
142
144 ESP_LOGCONFIG(TAG, "Loading UART bus settings");
145 if (this->hw_serial_ != nullptr) {
146 SerialConfig config = static_cast<SerialConfig>(get_config());
147 this->hw_serial_->begin(this->baud_rate_, config);
148 this->hw_serial_->setRxBufferSize(this->rx_buffer_size_);
149#ifdef USE_ESP8266_UART_SERIAL
150 // begin() puts UART0 back on GPIO1/GPIO3, so swap it again like setup() did for GPIO15/GPIO13
151 if (this->hw_serial_ == &Serial && ESP8266UartComponent::serial0_swapped)
152 this->hw_serial_->swap();
153#endif // USE_ESP8266_UART_SERIAL
154 } else {
155 this->sw_serial_->setup(this->tx_pin_, this->rx_pin_, this->baud_rate_, this->stop_bits_, this->data_bits_,
156 this->parity_, this->rx_buffer_size_);
157 }
158 if (dump_config) {
159 ESP_LOGCONFIG(TAG, "UART bus was reloaded.");
160 this->dump_config();
161 }
162}
163
165 ESP_LOGCONFIG(TAG, "UART Bus:");
166 LOG_PIN(" TX Pin: ", this->tx_pin_);
167 LOG_PIN(" RX Pin: ", this->rx_pin_);
168 if (this->rx_pin_ != nullptr) {
169 ESP_LOGCONFIG(TAG, " RX Buffer Size: %u", this->rx_buffer_size_); // NOLINT
170 }
171 ESP_LOGCONFIG(TAG,
172 " Baud Rate: %u baud\n"
173 " Data Bits: %u\n"
174 " Parity: %s\n"
175 " Stop bits: %u",
176 this->baud_rate_, this->data_bits_, LOG_STR_ARG(parity_to_str(this->parity_)), this->stop_bits_);
177 if (this->hw_serial_ != nullptr) {
178 ESP_LOGCONFIG(TAG, " Using hardware serial interface.");
179 } else {
180 ESP_LOGCONFIG(TAG, " Using software serial"
181#ifdef USE_UART_WAKE_LOOP_ON_RX
182 "\n Wake on data RX: ENABLED"
183#endif
184 );
185 if (this->rx_pin_ != nullptr) {
186 ESP_LOGCONFIG(TAG, " RX decoder: %s",
187 this->baud_rate_ <= SW_SERIAL_EDGE_MODE_MAX_BAUD ? LOG_STR_LITERAL("edge")
188 : LOG_STR_LITERAL("start bit sampler"));
189 }
190 if (this->tx_pin_ != nullptr && this->baud_rate_ <= SW_SERIAL_TX_BIT_LOCK_MAX_BAUD &&
191 this->sw_serial_->locks_whole_frame()) {
192 ESP_LOGW(TAG,
193 " TX locks interrupts for whole bytes because a software UART receives above %u baud; Wi-Fi "
194 "watchdog resets are possible under load",
195 (unsigned) SW_SERIAL_EDGE_MODE_MAX_BAUD);
196 }
197 }
198 this->check_logger_conflict();
199}
200
202#ifdef USE_LOGGER
203 if (this->hw_serial_ == nullptr || logger::global_logger->get_baud_rate() == 0) {
204 return;
205 }
206
207 if (this->hw_serial_ == logger::global_logger->get_hw_serial()) {
208 ESP_LOGW(TAG, " You're using the same serial port for logging and the UART component. Please "
209 "disable logging over the serial port by setting logger->baud_rate to 0.");
210 }
211#endif
212}
213
214void ESP8266UartComponent::write_array(const uint8_t *data, size_t len) {
215 if (this->hw_serial_ != nullptr) {
216 this->hw_serial_->write(data, len);
217 } else {
218 for (size_t i = 0; i < len; i++)
219 this->sw_serial_->write_byte(data[i]);
220 }
221#ifdef USE_UART_DEBUGGER
222 for (size_t i = 0; i < len; i++) {
223 this->debug_callback_.call(UART_DIRECTION_TX, data[i]);
224 }
225#endif
226}
228 if (!this->check_read_timeout_())
229 return false;
230 if (this->hw_serial_ != nullptr) {
231 *data = this->hw_serial_->peek();
232 } else {
233 *data = this->sw_serial_->peek_byte();
234 }
235 return true;
236}
237bool ESP8266UartComponent::read_array(uint8_t *data, size_t len) {
238 if (!this->check_read_timeout_(len))
239 return false;
240 if (this->hw_serial_ != nullptr) {
241 this->hw_serial_->readBytes(data, len);
242 } else {
243 for (size_t i = 0; i < len; i++)
244 data[i] = this->sw_serial_->read_byte();
245 }
246#ifdef USE_UART_DEBUGGER
247 for (size_t i = 0; i < len; i++) {
248 this->debug_callback_.call(UART_DIRECTION_RX, data[i]);
249 }
250#endif
251 return true;
252}
254 if (this->hw_serial_ != nullptr) {
255 return this->hw_serial_->available();
256 } else {
257 return this->sw_serial_->available();
258 }
259}
261 if (this->hw_serial_ != nullptr) {
262 return this->hw_serial_->availableForWrite();
263 }
264 return SIZE_MAX; // software serial bit-bangs each byte synchronously; there is no buffer to fill
265}
267 ESP_LOGVV(TAG, " Flushing");
268 if (this->hw_serial_ != nullptr) {
269 this->hw_serial_->flush();
270 } else {
271 this->sw_serial_->flush();
272 }
274}
276 uint8_t stop_bits, uint32_t data_bits, UARTParityOptions parity,
277 size_t rx_buffer_size) {
278 // load_settings() re-enters here
279 if (this->gpio_rx_pin_ != nullptr)
281 // This instance counted itself if its RX ran the whole-byte interrupt
282 if (this->blocking_rx_ && this->gpio_rx_pin_ != nullptr)
284 // RX disabled: forget the old pin, so a later reload does not remove this instance from the count again
285 if (rx_pin == nullptr)
286 this->gpio_rx_pin_ = nullptr;
287 this->bit_time_ = F_CPU / baud_rate;
288 this->stop_bits_ = stop_bits;
289 this->data_bits_ = data_bits;
290 this->parity_ = parity;
291 const bool edge_mode = baud_rate <= SW_SERIAL_EDGE_MODE_MAX_BAUD;
292 this->blocking_rx_ = !edge_mode;
293 this->lock_frame_ = baud_rate > SW_SERIAL_TX_BIT_LOCK_MAX_BAUD;
294 // to_isr() allocates, so call it only for a new or changed pin
295 if (tx_pin != nullptr) {
296 if (tx_pin != this->gpio_tx_pin_)
297 this->tx_pin_ = tx_pin->to_isr();
298 gpio_tx_pin_ = tx_pin;
301 }
302 if (rx_pin != nullptr) {
303 if (rx_pin != this->gpio_rx_pin_)
304 this->rx_pin_ = rx_pin->to_isr();
305 gpio_rx_pin_ = rx_pin;
307 uint8_t *buffer = this->rx_.buffer();
308 if (this->rx_.buffer_size() != rx_buffer_size) {
309 delete[] buffer; // NOLINT
310 buffer = new uint8_t[rx_buffer_size]; // NOLINT
311 }
312 this->rx_.setup((RX_TICKS_PER_SECOND + baud_rate / 2) / baud_rate, data_bits, parity != UART_CONFIG_PARITY_NONE,
313 stop_bits, buffer, rx_buffer_size);
314 this->rx_.reset(rx_now(), this->rx_pin_.digital_read());
315 if (edge_mode) {
317 } else {
320 }
321 }
322}
323// A byte can arrive while a CpuFrequencyBoost has an 80 MHz build at 160 MHz; the clock select bit doubles
324// the bit time then. The whole byte is read inside the ISR, so the clock cannot change partway through.
325__attribute__((always_inline)) static inline uint32_t rx_bit_time(uint32_t bit_time) {
326#if F_CPU != 160000000L
327 // NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- CPU2X is MMIO at a fixed address
328 return bit_time << (CPU2X & 1);
329#else
330 return bit_time;
331#endif
332}
333
335 const uint32_t bit_time = rx_bit_time(arg->bit_time_);
336 uint32_t wait = bit_time + bit_time / 3 - 500;
337 const uint32_t start = arch_get_cpu_cycle_count();
338 uint8_t rec = 0;
339 // Manually unroll the loop
340 for (int i = 0; i < arg->data_bits_; i++)
341 rec |= arg->read_bit_(&wait, start, bit_time) << i;
342
343 /* If parity is enabled, just read it and ignore it. */
344 /* TODO: Should we check parity? Or is it too slow for nothing added..*/
346 arg->read_bit_(&wait, start, bit_time);
347
348 // Stop bit
349 arg->wait_(&wait, start, bit_time);
350 if (arg->stop_bits_ == 2)
351 arg->wait_(&wait, start, bit_time);
352
353 arg->rx_.push_byte(rec);
354 // Clear RX pin so that the interrupt doesn't re-trigger right away again.
356#ifdef USE_UART_WAKE_LOOP_ON_RX
357 // Wake the main loop so the consuming component drains the byte promptly
358 // instead of waiting for the next loop_interval_ tick. Important for timing
359 // sensitive setups that poll read() in a tight loop (e.g. fingerprint_grow).
361#endif
362}
364 const uint32_t now = rx_now();
365 const bool level = arg->rx_pin_.digital_read();
366 [[maybe_unused]] const bool wake = arg->rx_.on_edge(now, level);
367#ifdef USE_UART_WAKE_LOOP_ON_RX
368 if (wake)
370#endif
371}
373 if (!this->rx_.finalize_due(rx_now())) {
374#ifdef USE_UART_WAKE_LOOP_ON_RX
375 // Tail not elapsed; wake again only once drained
376 if (this->rx_.available() == 0)
378#endif
379 return;
380 }
382 this->rx_.finalize(rx_now());
383}
384void IRAM_ATTR HOT ESP8266SoftwareSerial::write_byte(uint8_t data) {
385 if (this->gpio_tx_pin_ == nullptr) {
386 ESP_LOGE(TAG, "UART doesn't have TX pins set!");
387 return;
388 }
389 bool parity_bit = false;
390 bool need_parity_bit = true;
391 if (this->parity_ == UART_CONFIG_PARITY_EVEN) {
392 parity_bit = false;
393 } else if (this->parity_ == UART_CONFIG_PARITY_ODD) {
394 parity_bit = true;
395 } else {
396 need_parity_bit = false;
397 }
398
399 // Transmit runs from the main loop and never overlaps a CpuFrequencyBoost
400 const uint32_t bit_time = this->bit_time_;
401 // Data bits LSB first, then the parity bit
402 uint32_t frame = data & ((1u << this->data_bits_) - 1);
403 uint32_t num_bits = this->data_bits_;
404 if (need_parity_bit) {
405 parity_bit ^= __builtin_parity(frame);
406 frame |= uint32_t(parity_bit) << num_bits++;
407 }
408 // Decided before the start bit so the timed loop only tests a bit
409 const SoftwareSerialTxFrame tx = software_serial_tx_frame(frame, num_bits, bit_time, TX_UNLOCK_MIN_RUN_CYCLES,
410 this->lock_frame_ && blocking_rx_count == 0);
411 const uint32_t line = tx.line;
412 const uint32_t high_from = tx.high_from;
413 const uint32_t unlock_at = tx.unlock_at;
414 std::optional<InterruptLock> frame_lock;
415 if (this->locks_whole_frame())
416 frame_lock.emplace();
417 uint32_t start;
418 {
420 // Start bit
421 this->tx_pin_.digital_write(false);
422 start = arch_get_cpu_cycle_count();
423 }
424 uint32_t wait = bit_time;
425 for (uint32_t pos = 0; pos <= high_from; pos++) {
426 if (pos != 0)
427 this->write_bit_((line >> pos) & 1, &wait, start, bit_time);
428 if ((unlock_at >> pos) & 1)
429 frame_lock.emplace(); // drops the held lock first, so pending interrupts run
430 }
431 this->write_bit_(true, &wait, start, bit_time);
432 // Hold that high run with interrupts on: one that runs past it only delays the next start bit, and back-to-back
433 // byte locks with no gap between them trip the Wi-Fi watchdog
434 frame_lock.reset();
435 for (uint32_t i = high_from; i < num_bits + this->stop_bits_; i++)
436 this->wait_(&wait, start, bit_time);
437}
438void IRAM_ATTR ESP8266SoftwareSerial::wait_(uint32_t *wait, const uint32_t &start, uint32_t bit_time) {
439 while (arch_get_cpu_cycle_count() - start < *wait)
440 ;
441 *wait += bit_time;
442}
443bool IRAM_ATTR ESP8266SoftwareSerial::read_bit_(uint32_t *wait, const uint32_t &start, uint32_t bit_time) {
444 this->wait_(wait, start, bit_time);
445 return this->rx_pin_.digital_read();
446}
447// Locks only from MAX_TX_LOCK_CYCLES before the edge to the edge, so a pending interrupt runs right after it; a bit
448// longer than that (below about 5000 baud) spins with interrupts on first. Nests inside a frame lock.
449void IRAM_ATTR ESP8266SoftwareSerial::write_bit_(bool bit, uint32_t *wait, const uint32_t &start, uint32_t bit_time) {
450 while (arch_get_cpu_cycle_count() - start + MAX_TX_LOCK_CYCLES < *wait)
451 ;
453 this->wait_(wait, start, bit_time);
454 this->tx_pin_.digital_write(bit);
455}
457 this->rx_sync_();
458 return this->rx_.read_byte();
459}
461 this->rx_sync_();
462 return this->rx_.peek_byte();
463}
465 // Flush is a NO-OP with software serial, all bytes are written immediately.
466}
468 this->rx_sync_();
469 return this->rx_.available();
470}
471
472} // namespace esphome::uart
473#endif // USE_ESP8266
void digital_write(bool value)
Definition gpio.cpp:234
Helper class to disable interrupts.
Definition helpers.h:2251
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition gpio.h:29
ISRInternalGPIOPin to_isr() const
Definition gpio.cpp:96
Stream * get_hw_serial() const
Definition logger.h:162
UARTSelection get_uart() const
Get the UART used by the logger.
Definition logger.h:174
void write_bit_(bool bit, uint32_t *wait, const uint32_t &start, uint32_t bit_time)
static void gpio_intr_edge(ESP8266SoftwareSerial *arg)
bool read_bit_(uint32_t *wait, const uint32_t &start, uint32_t bit_time)
void wait_(uint32_t *wait, const uint32_t &start, uint32_t bit_time)
void setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_pin, uint32_t baud_rate, uint8_t stop_bits, uint32_t data_bits, UARTParityOptions parity, size_t rx_buffer_size)
bool locks_whole_frame() const
TX holds interrupts off for each byte up to the edge into its trailing run of 1 bits,...
static void gpio_intr(ESP8266SoftwareSerial *arg)
Above SW_SERIAL_EDGE_MODE_MAX_BAUD; reads the whole byte in the ISR.
void load_settings()
Load the UART settings.
bool read_array(uint8_t *data, size_t len) override
void write_array(const uint8_t *data, size_t len) override
void finalize(uint32_t now)
Call with the ISR masked.
void setup(uint32_t bit_ticks, uint8_t data_bits, bool parity, uint8_t stop_bits, uint8_t *buffer, size_t buffer_size)
Configure framing and buffer; drops all state. Follow with reset().
bool ESPHOME_ALWAYS_INLINE on_edge(uint32_t now, bool level)
ISR.
void reset(uint32_t now, bool level)
Forget any partial frame; level is the current line level.
bool ESPHOME_ALWAYS_INLINE push_byte(uint8_t data)
Drops the byte when full; holds buffer_size - 1 bytes.
bool check_read_timeout_(size_t len=1)
CallbackManager< void(UARTDirection, uint8_t)> debug_callback_
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
uint32_t buffer
Definition gif.cpp:50
@ INTERRUPT_FALLING_EDGE
Definition gpio_pin.h:53
@ INTERRUPT_ANY_EDGE
Definition gpio_pin.h:54
@ UART_SELECTION_UART0_SWAP
Definition logger.h:127
@ UART_SELECTION_UART0
Definition logger.h:112
Logger * global_logger
Definition logger.cpp:396
ESPHOME_ALWAYS_INLINE SoftwareSerialTxFrame software_serial_tx_frame(uint32_t frame, uint32_t num_bits, uint32_t bit_time, uint32_t min_run_cycles, bool find_unlocks)
frame holds num_bits data and parity bits, LSB first. unlock_at stays 0 unless find_unlocks.
ESPHOME_LOG_TAG(TAG, "uart.binary_sensor")
const LogString * parity_to_str(UARTParityOptions parity)
Definition uart.cpp:43
UARTFlushResult
Result of a flush() call.
@ UART_FLUSH_RESULT_ASSUMED_SUCCESS
Platform cannot report result; success is assumed.
uint32_t arch_get_cpu_cycle_count()
Definition hal.cpp:71
void wake_loop_threadsafe()
Non-ISR: always inline.
const void size_t len
Definition hal.h:68
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
size_t size_t pos
Definition helpers.h:1333
void ESPHOME_ALWAYS_INLINE wake_loop_isrsafe()
ISR-safe: no task_woken arg because ESP8266 has no FreeRTOS. Caller must be IRAM_ATTR.
static void uint32_t
One software serial TX byte as line levels, one bit per slot.
uint32_t unlock_at
Slots right after an edge into a run of equal bits lasting at least min_run_cycles,...
uint32_t line
The start bit at slot 0, then the frame, then a stop bit that ends the last run.
uint32_t high_from
Slot of the last 0; from the edge after it the line stays high through the stop bits.
SemaphoreHandle_t lock
Platform-specific main loop wake primitives.