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