ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
usb_cdc_acm.h
Go to the documentation of this file.
1#pragma once
2#if defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || \
3 defined(USE_ESP32_VARIANT_ESP32S31) || defined(USE_ESP32_VARIANT_ESP32H4) || defined(USE_ZEPHYR)
4
9
10#include <array>
11#include <atomic>
12#include <cstring>
13#include <functional>
14#ifdef USE_ZEPHYR
15#include <zephyr/device.h>
16#include <zephyr/sys/ring_buffer.h>
17#else
18#include "freertos/ringbuf.h"
19#include "esp_err.h"
20#include "tinyusb_cdc_acm.h"
21#endif
22
23namespace esphome::usb_cdc_acm {
24
25static const uint8_t EVENT_QUEUE_SIZE = 12;
26// Minimum interval between repeated warnings while a host stall persists
27static constexpr uint32_t LOG_THROTTLE_MS = 1000;
28
29#ifndef USE_ZEPHYR
30// Drain up to out_buf_sz bytes from a byte ring buffer, handling FreeRTOS's wrapped
31// case with a second read. Shared with the cdc_acm_uart bridge platform, whose worker
32// tasks drain the same ring buffers.
33inline esp_err_t ringbuf_read_bytes(RingbufHandle_t ring_buf, uint8_t *out_buf, size_t out_buf_sz, size_t *rx_data_size,
34 TickType_t x_ticks_to_wait) {
35 size_t read_sz;
36 uint8_t *buf = static_cast<uint8_t *>(xRingbufferReceiveUpTo(ring_buf, &read_sz, x_ticks_to_wait, out_buf_sz));
37
38 if (buf == nullptr) {
39 return ESP_FAIL;
40 }
41
42 memcpy(out_buf, buf, read_sz);
43 vRingbufferReturnItem(ring_buf, (void *) buf);
44 *rx_data_size = read_sz;
45
46 // Buffer's data can be wrapped, in which case we should perform another read
47 if (*rx_data_size < out_buf_sz) {
48 buf = static_cast<uint8_t *>(xRingbufferReceiveUpTo(ring_buf, &read_sz, 0, out_buf_sz - *rx_data_size));
49 if (buf != nullptr) {
50 memcpy(out_buf + *rx_data_size, buf, read_sz);
51 vRingbufferReturnItem(ring_buf, (void *) buf);
52 *rx_data_size += read_sz;
53 }
54 }
55
56 return ESP_OK;
57}
58#endif
59
60// Callback types for line coding and line state changes
61using LineCodingCallback = std::function<void(uint32_t bit_rate, uint8_t stop_bits, uint8_t parity, uint8_t data_bits)>;
62using LineStateCallback = std::function<void(bool dtr, bool rts)>;
63
64// Event types
69
70// Event structure for the queue
71struct CDCEvent {
73 union {
74 struct {
75 bool dtr;
76 bool rts;
78 struct {
80 uint8_t stop_bits;
81 uint8_t parity;
82 uint8_t data_bits;
85
86 // Required by EventPool - called before returning to pool
87 void release() {
88 // No dynamic memory to clean up, data is stored inline
89 }
90};
91
92// Forward declaration
93class USBCDCACMComponent;
94
96class USBCDCACMInstance final : public uart::UARTComponent, public Parented<USBCDCACMComponent> {
97 public:
98 void setup();
99 void loop();
100 void dump_config();
101
102 void set_interface_number(uint8_t itf) { this->itf_ = itf; }
103 // Get the CDC port number for this instance
104 uint8_t get_itf() const { return this->itf_; }
105#ifdef USE_ZEPHYR
106 explicit USBCDCACMInstance(const device *uart_dev) : uart_dev_(uart_dev) {}
107#else
108 static void usb_tx_task_fn(void *arg);
109 void usb_tx_task();
110
111 // Ring buffer accessors for bridge components
112 RingbufHandle_t get_tx_ringbuf() const { return this->usb_tx_ringbuf_; }
113 RingbufHandle_t get_rx_ringbuf() const { return this->usb_rx_ringbuf_; }
114
115 // Task handle accessor for notifying TX task
116 TaskHandle_t get_tx_task_handle() const { return this->usb_tx_task_handle_; }
117#endif
118
119 // Callback registration for line coding and line state changes
120 void set_line_coding_callback(LineCodingCallback callback) { this->line_coding_callback_ = std::move(callback); }
121 void set_line_state_callback(LineStateCallback callback) { this->line_state_callback_ = std::move(callback); }
122
123 // Called from USB core task context queues event for processing in main loop
124 void queue_line_coding_event(uint32_t bit_rate, uint8_t stop_bits, uint8_t parity, uint8_t data_bits);
125 void queue_line_state_event(bool dtr, bool rts);
126
127 // UARTComponent interface implementation
128 void write_array(const uint8_t *data, size_t len) override;
129 bool peek_byte(uint8_t *data) override;
130 bool read_array(uint8_t *data, size_t len) override;
131 size_t available() override;
132 uart::UARTFlushResult flush() override;
133#if defined(USE_ESP8266) || defined(USE_ESP32)
134 // No-op: in CDC ACM device mode the host dictates the line coding, so there are no
135 // local UART settings to (re)apply.
136 void load_settings(bool dump_config) override {}
137 using UARTComponent::load_settings; // also bring in the no-arg overload for convenience
138#endif
139
140 protected:
141 // A logger on the same port is rejected at validation by the Zephyr claim registry
142 void check_logger_conflict() override {}
143
144 // Process queued events and invoke callbacks (called from main loop)
145 void process_events_();
146 // Count dropped TX bytes and log a throttled warning
147 void record_tx_drop_(size_t dropped);
148 // Hand a pending peeked byte to read_array(); true when nothing remains to read
149 bool consume_peek_(uint8_t *&data, size_t &len);
150 // Report bytes to the UART debugger; no-ops without USE_UART_DEBUGGER
151 void report_rx_debug_(const uint8_t *data, size_t len) {
152#ifdef USE_UART_DEBUGGER
153 for (size_t i = 0; i < len; i++) {
154 this->debug_callback_.call(uart::UART_DIRECTION_RX, data[i]);
155 }
156#endif
157 }
158 void report_tx_debug_(const uint8_t *data, size_t len) {
159#ifdef USE_UART_DEBUGGER
160 for (size_t i = 0; i < len; i++) {
161 this->debug_callback_.call(uart::UART_DIRECTION_TX, data[i]);
162 }
163#endif
164 }
165#ifdef USE_ZEPHYR
166 static void uart_irq_handler(const device *dev, void *instance);
167 void uart_rx_process_();
168 void uart_tx_process_();
169
170 const device *uart_dev_;
172 ring_buf rx_ringbuf_;
173 ring_buf tx_ringbuf_;
174 std::atomic<bool> rx_irq_disabled_{false};
175 std::atomic<bool> tx_irq_disabled_{false};
176 // Set by the IRQ handler when our TX ring buffer and the driver's are both empty
177 std::atomic<bool> tx_drained_{false};
178 bool dtr_{false};
179 bool rts_{false};
180 uint8_t rx_ringbuf_data_[ESPHOME_CDC_RX_RING_BUFFER_SIZE];
181 uint8_t tx_ringbuf_data_[ESPHOME_CDC_TX_RING_BUFFER_SIZE];
182#else
183 // True while TX bytes are still in the ring buffer or held by the TX task
184 bool tx_pending_();
185 TaskHandle_t usb_tx_task_handle_{nullptr};
186
187 RingbufHandle_t usb_tx_ringbuf_{nullptr};
188 RingbufHandle_t usb_rx_ringbuf_{nullptr};
189 // TX task staging; a member rather than a stack array so it does not size the task stack.
190 std::array<uint8_t, CONFIG_TINYUSB_CDC_TX_BUFSIZE> usb_tx_staging_{};
191 // Non-zero while the TX task holds bytes it has pulled from the ring buffer but not
192 // yet handed to TinyUSB; lets flush() account for data that is in neither the ring
193 // buffer nor TinyUSB's FIFO.
194 // Threading: written only by usb_tx_task(); read by flush()'s bounded wait on the
195 // caller's task (typically the main loop).
196 // std::atomic<uint8_t> rather than std::atomic<bool> because GCC on Xtensa
197 // generates an indirect function call for atomic<bool> ops instead of inlining
198 // them; atomic<uint8_t> inlines correctly on all platforms.
199 std::atomic<uint8_t> usb_tx_busy_{0};
200#endif
201 // Running total of bytes dropped by write_array() (never reset), and the timestamp
202 // of the last "buffer full" log line (throttled so a sustained host stall doesn't
203 // flood the log).
206 // User-registered callbacks (called from main loop)
209 // RX buffer for peek functionality
210 uint8_t peek_buffer_{0};
211 bool has_peek_{false};
212 uint8_t itf_{0};
213
214 // Lock-free queue and event pool for cross-task event passing
215 // Pool sized to queue capacity (SIZE-1) because LockFreeQueue<T,N> is a ring
216 // buffer that holds N-1 elements. This guarantees allocate() returns nullptr
217 // before push() can fail, preventing both a pool slot leak and an SPSC
218 // violation on the pool's internal free list.
219 EventPool<CDCEvent, EVENT_QUEUE_SIZE - 1> event_pool_;
221};
222
224class USBCDCACMComponent final : public Component {
225 public:
227
228 void setup() override;
229 void loop() override;
230 void dump_config() override;
231 float get_setup_priority() const override { return setup_priority::IO; }
232
233 // Interface management
234 void add_interface(USBCDCACMInstance *interface);
236
237 protected:
238 std::array<USBCDCACMInstance *, ESPHOME_MAX_USB_CDC_INSTANCES> interfaces_{};
239};
240
241extern USBCDCACMComponent *global_usb_cdc_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
242
243} // namespace esphome::usb_cdc_acm
244#endif
Helper class to easily give an object a parent of type T.
Definition helpers.h:2160
CallbackManager< void(UARTDirection, uint8_t)> debug_callback_
Main USB CDC ACM component that manages the USB device and all CDC interfaces.
void add_interface(USBCDCACMInstance *interface)
std::array< USBCDCACMInstance *, ESPHOME_MAX_USB_CDC_INSTANCES > interfaces_
USBCDCACMInstance * get_interface_by_number(uint8_t itf)
float get_setup_priority() const override
Represents a single CDC ACM interface instance.
Definition usb_cdc_acm.h:96
void report_tx_debug_(const uint8_t *data, size_t len)
RingbufHandle_t get_rx_ringbuf() const
std::array< uint8_t, CONFIG_TINYUSB_CDC_TX_BUFSIZE > usb_tx_staging_
EventPool< CDCEvent, EVENT_QUEUE_SIZE - 1 > event_pool_
uint8_t rx_ringbuf_data_[ESPHOME_CDC_RX_RING_BUFFER_SIZE]
bool read_array(uint8_t *data, size_t len) override
bool peek_byte(uint8_t *data) override
static void uart_irq_handler(const device *dev, void *instance)
RingbufHandle_t get_tx_ringbuf() const
void set_line_state_callback(LineStateCallback callback)
uart::UARTFlushResult flush() override
uint8_t tx_ringbuf_data_[ESPHOME_CDC_TX_RING_BUFFER_SIZE]
LockFreeQueue< CDCEvent, EVENT_QUEUE_SIZE > event_queue_
void queue_line_coding_event(uint32_t bit_rate, uint8_t stop_bits, uint8_t parity, uint8_t data_bits)
void set_line_coding_callback(LineCodingCallback callback)
bool consume_peek_(uint8_t *&data, size_t &len)
void load_settings(bool dump_config) override
void report_rx_debug_(const uint8_t *data, size_t len)
void write_array(const uint8_t *data, size_t len) override
void queue_line_state_event(bool dtr, bool rts)
USBCDCACMInstance(const device *uart_dev)
constexpr float IO
For components that represent GPIO pins like PCF8573.
Definition component.h:41
UARTFlushResult
Result of a flush() call.
std::function< void(uint32_t bit_rate, uint8_t stop_bits, uint8_t parity, uint8_t data_bits)> LineCodingCallback
Definition usb_cdc_acm.h:61
esp_err_t ringbuf_read_bytes(RingbufHandle_t ring_buf, uint8_t *out_buf, size_t out_buf_sz, size_t *rx_data_size, TickType_t x_ticks_to_wait)
Definition usb_cdc_acm.h:33
USBCDCACMComponent * global_usb_cdc_component
std::function< void(bool dtr, bool rts)> LineStateCallback
Definition usb_cdc_acm.h:62
const void size_t len
Definition hal.h:68
static void uint32_t
union esphome::usb_cdc_acm::CDCEvent::@183 data
struct esphome::usb_cdc_acm::CDCEvent::@183::@185 line_coding
struct esphome::usb_cdc_acm::CDCEvent::@183::@184 line_state