ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
virtual_uart.h
Go to the documentation of this file.
1#pragma once
2
5#include "esphome/core/hal.h"
7
8#include <span>
9#include <utility>
10
11namespace esphome::virtual_uart {
12
13// Not templated, so the log strings exist once for all RX sizes
15void log_inject_dropped(size_t len);
16void dump_virtual_uart_config(uart::UARTComponent *component);
17
19template<size_t RX_BUFFER_SIZE>
20class VirtualUART final : public uart::VirtualUARTComponent<RX_BUFFER_SIZE>, public Component {
21 public:
22 template<typename F> void add_on_tx_callback(F &&callback) { this->tx_callback_.add(std::forward<F>(callback)); }
23
24 void write_array(const uint8_t *data, size_t len) override {
25 // An on_tx that writes to this UART again would recurse until the stack runs out
26 if (this->in_tx_) {
28 return;
29 }
30 this->in_tx_ = true;
31 this->debug_tx_(data, len);
32 this->tx_callback_.call(std::span<const uint8_t>(data, len));
33 this->in_tx_ = false;
34 }
36 void dump_config() override { dump_virtual_uart_config(this); }
37
39 void inject(const uint8_t *data, size_t len) {
40 if (!this->inject_rx(data, len)) {
42 }
43 }
45 void inject_progmem(const uint8_t *data, size_t len) {
46 if (len > this->rx_.free_space()) {
48 return;
49 }
50 for (size_t i = 0; i < len; i++)
51 this->rx_.push(progmem_read_byte(data + i));
52 }
53
54 protected:
55 CallbackManager<void(std::span<const uint8_t>)> tx_callback_;
56 bool in_tx_{false};
57};
58
59} // namespace esphome::virtual_uart
index_type free_space() const
Definition helpers.h:563
bool push(const T &value)
Definition helpers.h:502
UART without a wire: the derived class writes and feeds reads with inject_rx().
StaticRingBuffer< uint8_t, RX_BUFFER_SIZE > rx_
void debug_tx_(const uint8_t *data, size_t len)
For write_array() of the derived class: hands the written bytes to a configured UART debugger.
bool inject_rx(const uint8_t *data, size_t len)
Adds one whole block to the RX ring; false, and nothing kept, when it does not fit.
A UART configured in YAML: what its reader writes goes to on_tx, and inject_rx hands it bytes to read...
void inject(const uint8_t *data, size_t len)
Logs a block that does not fit the RX ring.
void inject_progmem(const uint8_t *data, size_t len)
inject() for a constant payload in flash on ESP8266, read without a heap copy.
void add_on_tx_callback(F &&callback)
uart::UARTFlushResult flush() override
CallbackManager< void(std::span< const uint8_t >)> tx_callback_
void write_array(const uint8_t *data, size_t len) override
const Component * component
Definition component.cpp:34
UARTFlushResult
Result of a flush() call.
@ UART_FLUSH_RESULT_SUCCESS
Confirmed: all bytes left the TX FIFO.
void log_inject_dropped(size_t len)
void dump_virtual_uart_config(uart::UARTComponent *component)
const void size_t len
Definition hal.h:68
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51