ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
usb_cdc_acm_zephyr.cpp
Go to the documentation of this file.
1#if defined(USE_ZEPHYR)
2#include "usb_cdc_acm.h"
4#include "esphome/core/log.h"
5#include <zephyr/drivers/uart.h>
8
9//==============================================================================
10// USBCDCACMInstance Implementation
11//==============================================================================
12namespace esphome::usb_cdc_acm {
13
14ESPHOME_LOG_TAG(TAG, "usb_cdc_acm");
15static constexpr uint32_t FLUSH_TIMEOUT_MS = 500;
16static constexpr uint32_t LINE_STATE_POLL_MS = 100;
17
18#ifdef CONFIG_USB_DEVICE_STACK_NEXT
19#define TX_FIFO_SIZE_IF_DEVICE(node_id) \
20 if (dev == DEVICE_DT_GET(node_id)) \
21 return DT_PROP(node_id, tx_fifo_size);
22
24static uint32_t driver_tx_buffer_size(const device *dev) {
25 DT_FOREACH_STATUS_OKAY(zephyr_cdc_acm_uart, TX_FIFO_SIZE_IF_DEVICE)
26 return 0;
27}
28#else
29static uint32_t driver_tx_buffer_size(const device * /*dev*/) { return CONFIG_USB_CDC_ACM_RINGBUF_SIZE; }
30#endif
31
33 uint8_t *data;
34 uint32_t send_len = ring_buf_get_claim(&this->tx_ringbuf_, &data, UINT32_MAX);
35 if (send_len == 0) {
36 // Our ring buffer is empty. Here (tx_ready set) cdc_acm reports the free space in its own
37 // TX ring buffer. On the legacy stack tx_ready is cleared before each USB transfer and set
38 // again when it completes, so a fully free driver buffer means the host has received
39 // everything. The new stack also calls this handler when a transfer completes, but a free
40 // buffer there only means the last packet has been handed to the USB controller.
41 if (static_cast<uint32_t>(uart_irq_tx_ready(this->uart_dev_)) == driver_tx_buffer_size(this->uart_dev_)) {
42 this->tx_drained_ = true;
43 }
44 uart_irq_tx_disable(this->uart_dev_);
45 return;
46 }
47 int sent = uart_fifo_fill(this->uart_dev_, data, send_len);
48 if (sent <= 0) {
49 // No progress: the USB device is suspended (host asleep, hub power save) or not configured.
50 // On the legacy stack fill() then returns 0 without clearing tx_ready, and irq_update() always
51 // returns 1 for cdc_acm, so the IRQ handler would loop forever on the cooperative USB work
52 // queue and block the main loop. Disabling TX ends that loop, because irq_is_pending() only
53 // reports TX while the TX IRQ is enabled. loop() turns it back on while data is waiting.
54 ring_buf_get_finish(&this->tx_ringbuf_, 0);
55 uart_irq_tx_disable(this->uart_dev_);
56 this->tx_irq_disabled_ = true;
57 return;
58 }
59 ring_buf_get_finish(&this->tx_ringbuf_, sent);
60}
61
63 uint8_t *data;
64 uint32_t recv_len = ring_buf_put_claim(&this->rx_ringbuf_, &data, UINT32_MAX);
65 if (recv_len == 0) {
66 // Ring buffer full: disable RX IRQ so the ISR stops firing. read_array() re-enables it
67 // once it has freed space.
68 uart_irq_rx_disable(this->uart_dev_);
69 this->rx_irq_disabled_ = true;
70 return;
71 }
72 int rx = uart_fifo_read(this->uart_dev_, data, recv_len);
73 if (rx < 0) {
74 ESP_LOGE(TAG, "Failed to read UART FIFO, err %d", rx);
75 }
76 ring_buf_put_finish(&this->rx_ringbuf_, rx > 0 ? rx : 0);
77}
78
79void USBCDCACMInstance::uart_irq_handler(const device *dev, void *instance) {
80 USBCDCACMInstance *thiz = static_cast<USBCDCACMInstance *>(instance);
81 while (uart_irq_update(dev) && uart_irq_is_pending(dev)) {
82 if (uart_irq_rx_ready(dev)) {
83 thiz->uart_rx_process_();
84 }
85
86 // No early exit here: pending RX data must still be read. The loop ends once neither
87 // RX nor TX is pending (both process functions disable their IRQ when they cannot progress).
88 if (uart_irq_tx_ready(dev)) {
89 thiz->uart_tx_process_();
90 }
91 }
92}
93
95 if (!device_is_ready(this->uart_dev_)) {
96 ESP_LOGE(TAG, "UART Bus %s: is not ready.", this->uart_dev_->name);
97 this->get_parent()->mark_failed();
98 return;
99 }
100 if (int err = zephyr::usb_device_enable(); err != 0) {
101 ESP_LOGE(TAG, "USB device setup failed: %d", err);
102 this->get_parent()->mark_failed();
103 return;
104 }
105 ring_buf_init(&this->rx_ringbuf_, ESPHOME_CDC_RX_RING_BUFFER_SIZE, this->rx_ringbuf_data_);
106 ring_buf_init(&this->tx_ringbuf_, ESPHOME_CDC_TX_RING_BUFFER_SIZE, this->tx_ringbuf_data_);
107 // The driver only reports the bit rate; the frame format is fixed on USB
108 this->data_bits_ = 8;
109 this->stop_bits_ = 1;
110#if defined(USE_ZEPHYR_CDC_ACM_RATE_CALLBACK)
111 zephyr::CdcAcm::add_on_rate_callback([this](const device *dev, uint32_t bit_rate) {
112 if (dev == this->uart_dev_) {
113 // Queue event for processing in main loop
114 this->queue_line_coding_event(bit_rate, this->stop_bits_, this->parity_, this->data_bits_);
115 }
116 });
117#endif
118 uart_irq_callback_user_data_set(this->uart_dev_, uart_irq_handler, this);
119
120 uart_irq_rx_enable(this->uart_dev_);
121}
122
124 // Retry TX stopped by uart_tx_process_() (e.g. after the host resumes from suspend)
125 if (this->tx_irq_disabled_ && !ring_buf_is_empty(&this->tx_ringbuf_)) {
126 this->tx_irq_disabled_ = false;
127 uart_irq_tx_enable(this->uart_dev_);
128 }
129 // Line state is polled here on the main loop, so it needs no event queue
131 if (now - this->last_line_poll_ms_ >= LINE_STATE_POLL_MS) {
132 this->last_line_poll_ms_ = now;
133 uint32_t dtr_val = 0;
134 uint32_t rts_val = 0;
135 uart_line_ctrl_get(this->uart_dev_, UART_LINE_CTRL_DTR, &dtr_val);
136 uart_line_ctrl_get(this->uart_dev_, UART_LINE_CTRL_RTS, &rts_val);
137 const bool dtr = dtr_val != 0;
138 const bool rts = rts_val != 0;
139 if (dtr != this->dtr_) {
140 ESP_LOGD(TAG, "UART Bus %s: %s", this->uart_dev_->name,
141 dtr ? LOG_STR_LITERAL("Opened") : LOG_STR_LITERAL("Closed"));
142 }
143 if (dtr != this->dtr_ || rts != this->rts_) {
144 ESP_LOGV(TAG, "Line state device %s: DTR=%d, RTS=%d", this->uart_dev_->name, dtr, rts);
145 this->dtr_ = dtr;
146 this->rts_ = rts;
147 if (this->line_state_callback_ != nullptr) {
148 this->line_state_callback_(dtr, rts);
149 }
150 }
151 }
152 // Line coding changes arrive from the USB thread through the event queue
153 this->process_events_();
154}
155
157 ESP_LOGCONFIG(TAG,
158 "UART Bus %s:\n"
159 " Opened: %s\n"
160 " Baud Rate: %" PRIu32 " baud\n"
161 " Data Bits: %u\n"
162 " Parity: %s\n"
163 " Stop bits: %u",
164 this->uart_dev_->name, YESNO(this->dtr_), this->baud_rate_, this->data_bits_,
165 LOG_STR_ARG(parity_to_str(this->parity_)), this->stop_bits_);
166}
167
169 uint32_t size = ring_buf_size_get(&this->rx_ringbuf_) + (this->has_peek_ ? 1 : 0);
170 ESP_LOGVV(TAG, "UART Bus %s: available %" PRIu32, this->uart_dev_->name, size);
171 return size;
172}
173
174bool USBCDCACMInstance::read_array(uint8_t *data, size_t len) {
175 if (len == 0) {
176 return true;
177 }
178 if (this->available() < len) {
179 return false;
180 }
181
182 if (this->consume_peek_(data, len)) {
183 return true;
184 }
185 const uint32_t got = ring_buf_get(&this->rx_ringbuf_, data, len);
186 // Space is free again: resume RX stopped by uart_rx_process_()
187 if (got > 0 && this->rx_irq_disabled_.exchange(false)) {
188 uart_irq_rx_enable(this->uart_dev_);
189 }
190 if (got != len) {
191 ESP_LOGE(TAG, "UART CDC unexpected size");
192 return false;
193 }
194 this->report_rx_debug_(data, len);
195 return true;
196}
197
199 // The driver only moves data while the host reads the port. With no host listening (DTR off)
200 // the data cannot drain, so do not stall the caller waiting for it.
201 if (!this->dtr_) {
203 }
204 // flush() and write_array() both run on the main loop, so nothing is added while we wait.
205 // The IRQ handler sets tx_drained_ once both our ring buffer and the driver are empty.
206 this->tx_drained_ = false;
207 // A stall may have left the flag set; clear it once so a handler run during the wait is not undone.
208 // The handler sets it again if the device is still suspended.
209 this->tx_irq_disabled_ = false;
210 uint32_t start = millis();
211 while (true) {
212 // Wakes the IRQ handler now if the driver is idle, or after the transfer in progress
213 uart_irq_tx_enable(this->uart_dev_);
214 // ring_buf_is_empty() is not enough: it is already true while the IRQ handler holds
215 // claimed bytes that it has not yet copied into the driver.
216 if (this->tx_drained_ && ring_buf_space_get(&this->tx_ringbuf_) == ESPHOME_CDC_TX_RING_BUFFER_SIZE) {
217#ifdef CONFIG_USB_DEVICE_STACK_NEXT
218 // The new stack reports an empty buffer while its last USB packet may still be in flight
220#else
222#endif
223 }
224 // USB device suspended or not configured (see uart_tx_process_()): nothing will drain
225 if (this->tx_irq_disabled_) {
227 }
228 if (millis() - start > FLUSH_TIMEOUT_MS) {
229 ESP_LOGW(TAG, "Flush timeout");
231 }
232 delay(1);
233 }
234}
235
236void USBCDCACMInstance::write_array(const uint8_t *data, size_t len) {
237 if (!device_is_ready(this->uart_dev_)) {
238 return;
239 }
240 uint32_t recv_len = ring_buf_put(&this->tx_ringbuf_, data, len);
241 if (recv_len < len) {
242 this->record_tx_drop_(len - recv_len);
243 }
244 uart_irq_tx_enable(this->uart_dev_);
245 // Only report the bytes that were queued, not the dropped ones
246 this->report_tx_debug_(data, recv_len);
247}
248
249} // namespace esphome::usb_cdc_acm
250#endif
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.
USBCDCACMComponent * get_parent() const
Definition helpers.h:2438
Represents a single CDC ACM interface instance.
Definition usb_cdc_acm.h:96
void report_tx_debug_(const uint8_t *data, size_t len)
uint8_t rx_ringbuf_data_[ESPHOME_CDC_RX_RING_BUFFER_SIZE]
bool read_array(uint8_t *data, size_t len) override
static void uart_irq_handler(const device *dev, void *instance)
uart::UARTFlushResult flush() override
uint8_t tx_ringbuf_data_[ESPHOME_CDC_TX_RING_BUFFER_SIZE]
void queue_line_coding_event(uint32_t bit_rate, uint8_t stop_bits, uint8_t parity, uint8_t data_bits)
bool consume_peek_(uint8_t *&data, size_t &len)
void report_rx_debug_(const uint8_t *data, size_t len)
void write_array(const uint8_t *data, size_t len) override
static void add_on_rate_callback(F &&callback)
Call from setup().
Definition cdc_acm.h:17
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.
@ UART_FLUSH_RESULT_SUCCESS
Confirmed: all bytes left the TX FIFO.
@ UART_FLUSH_RESULT_FAILED
Confirmed: driver or hardware error.
@ UART_FLUSH_RESULT_TIMEOUT
Confirmed: timed out before TX completed.
ESPHOME_LOG_TAG(TAG, "usb_cdc_acm")
int usb_device_enable()
Start the USB device on whichever Zephyr USB device stack the build uses (the legacy one or device_ne...
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:44
void HOT delay(uint32_t ms)
Definition hal.cpp:78
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t