ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
usb_cdc_acm_esp32.cpp
Go to the documentation of this file.
1#if defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || \
2 defined(USE_ESP32_VARIANT_ESP32S31) || defined(USE_ESP32_VARIANT_ESP32H4)
3#include "usb_cdc_acm.h"
5#include "esphome/core/hal.h"
6#include "esphome/core/log.h"
7
8#include <cstring>
9#include <sys/param.h>
10#include "freertos/FreeRTOS.h"
11#include "freertos/ringbuf.h"
12#include "freertos/task.h"
13#include "esp_log.h"
14
15#include "tusb.h"
16#include "tinyusb_cdc_acm.h"
17
18namespace esphome::usb_cdc_acm {
19
20ESPHOME_LOG_TAG(TAG, "usb_cdc_acm");
21
22// Maximum bytes to log in very verbose hex output (168 * 3 = 504, under TX buffer size of 512)
23static constexpr size_t USB_CDC_MAX_LOG_BYTES = 168;
24
25static constexpr size_t USB_TX_TASK_STACK_SIZE = 4096;
26static constexpr size_t USB_TX_TASK_STACK_SIZE_VV = 8192;
27
28// Upper bound on how long flush() may block in total: the TX ring buffer drain and
29// the final TinyUSB flush share this budget.
30static constexpr uint32_t FLUSH_TIMEOUT_MS = 100;
31
32static USBCDCACMInstance *get_instance_by_itf(int itf) {
33 if (global_usb_cdc_component == nullptr) {
34 return nullptr;
35 }
37}
38
39static void tinyusb_cdc_rx_callback(int itf, cdcacm_event_t *event) {
40 USBCDCACMInstance *instance = get_instance_by_itf(itf);
41 if (instance == nullptr) {
42 ESP_LOGE(TAG, "RX callback: invalid interface %d", itf);
43 return;
44 }
45
46 size_t rx_size = 0;
47 static uint8_t rx_buf[CONFIG_TINYUSB_CDC_RX_BUFSIZE] = {0};
48
49 // read from USB
51 tinyusb_cdcacm_read(static_cast<tinyusb_cdcacm_itf_t>(itf), rx_buf, CONFIG_TINYUSB_CDC_RX_BUFSIZE, &rx_size);
52 ESP_LOGV(TAG, "tinyusb_cdc_rx_callback itf=%d (size: %u)", itf, rx_size);
53 ESP_LOGVV_HEX(TAG, rx_buf, rx_size, USB_CDC_MAX_LOG_BYTES, "rx_buf = %s");
54
55 if (ret == ESP_OK && rx_size > 0) {
56 RingbufHandle_t rx_ringbuf = instance->get_rx_ringbuf();
57 if (rx_ringbuf != nullptr) {
58 BaseType_t send_res = xRingbufferSend(rx_ringbuf, rx_buf, rx_size, 0);
59 if (send_res != pdTRUE) {
60 ESP_LOGE(TAG, "USB RX itf=%d: buffer full, %u bytes lost", itf, rx_size);
61 } else {
62 ESP_LOGV(TAG, "USB RX itf=%d: queued %u bytes", itf, rx_size);
63 }
64 }
65 }
66}
67
68static void tinyusb_cdc_line_state_changed_callback(int itf, cdcacm_event_t *event) {
69 USBCDCACMInstance *instance = get_instance_by_itf(itf);
70 if (instance == nullptr) {
71 ESP_LOGE(TAG, "Line state callback: invalid interface %d", itf);
72 return;
73 }
74
75 int dtr = event->line_state_changed_data.dtr;
76 int rts = event->line_state_changed_data.rts;
77 ESP_LOGV(TAG, "Line state itf=%d: DTR=%d, RTS=%d", itf, dtr, rts);
78
79 // Queue event for processing in main loop
80 instance->queue_line_state_event(dtr != 0, rts != 0);
81}
82
83static void tinyusb_cdc_line_coding_changed_callback(int itf, cdcacm_event_t *event) {
84 USBCDCACMInstance *instance = get_instance_by_itf(itf);
85 if (instance == nullptr) {
86 ESP_LOGE(TAG, "Line coding callback: invalid interface %d", itf);
87 return;
88 }
89
90 uint32_t bit_rate = event->line_coding_changed_data.p_line_coding->bit_rate;
91 uint8_t stop_bits = event->line_coding_changed_data.p_line_coding->stop_bits;
92 uint8_t parity = event->line_coding_changed_data.p_line_coding->parity;
93 uint8_t data_bits = event->line_coding_changed_data.p_line_coding->data_bits;
94 ESP_LOGV(TAG, "Line coding itf=%d: bit_rate=%" PRIu32 " stop_bits=%u parity=%u data_bits=%u", itf, bit_rate,
95 stop_bits, parity, data_bits);
96
97 // Queue event for processing in main loop
98 instance->queue_line_coding_event(bit_rate, stop_bits, parity, data_bits);
99}
100
101//==============================================================================
102// USBCDCACMInstance Implementation
103//==============================================================================
104
106 this->usb_tx_ringbuf_ = xRingbufferCreate(CONFIG_TINYUSB_CDC_TX_BUFSIZE, RINGBUF_TYPE_BYTEBUF);
107 if (this->usb_tx_ringbuf_ == nullptr) {
108 ESP_LOGE(TAG, "USB TX buffer creation error for itf %d", this->itf_);
109 this->parent_->mark_failed();
110 return;
111 }
112
113 this->usb_rx_ringbuf_ = xRingbufferCreate(CONFIG_TINYUSB_CDC_RX_BUFSIZE, RINGBUF_TYPE_BYTEBUF);
114 if (this->usb_rx_ringbuf_ == nullptr) {
115 ESP_LOGE(TAG, "USB RX buffer creation error for itf %d", this->itf_);
116 this->parent_->mark_failed();
117 return;
118 }
119
120 // Configure this CDC interface
121 const tinyusb_config_cdcacm_t acm_cfg = {
122 .cdc_port = static_cast<tinyusb_cdcacm_itf_t>(this->itf_),
123 .callback_rx = &tinyusb_cdc_rx_callback,
124 .callback_rx_wanted_char = NULL,
125 .callback_line_state_changed = &tinyusb_cdc_line_state_changed_callback,
126 .callback_line_coding_changed = &tinyusb_cdc_line_coding_changed_callback,
127 };
128
129 esp_err_t result = tinyusb_cdcacm_init(&acm_cfg);
130 if (result != ESP_OK) {
131 ESP_LOGE(TAG, "tinyusb_cdcacm_init failed: %d", result);
132 this->parent_->mark_failed();
133 return;
134 }
135
136 // Use a larger stack size for very verbose logging
137 constexpr size_t stack_size =
138 ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE ? USB_TX_TASK_STACK_SIZE_VV : USB_TX_TASK_STACK_SIZE;
139
140 // Create a simple, unique task name per interface
141 char task_name[] = "usb_tx_0";
142 task_name[sizeof(task_name) - 2] = format_hex_char(static_cast<char>(this->itf_));
143 xTaskCreate(usb_tx_task_fn, task_name, stack_size, this, 4, &this->usb_tx_task_handle_);
144
145 if (this->usb_tx_task_handle_ == nullptr) {
146 ESP_LOGE(TAG, "Failed to create USB TX task for itf %d", this->itf_);
147 this->parent_->mark_failed();
148 return;
149 }
150}
151
153 // Process events from the lock-free queue
154 this->process_events_();
155}
156
158
160 auto *instance = static_cast<USBCDCACMInstance *>(arg);
161 instance->usb_tx_task();
162}
163
165 uint8_t *data = this->usb_tx_staging_.data();
166 size_t tx_data_size = 0;
167 // Back-dated so a stall within the first LOG_THROTTLE_MS of uptime still logs
168 // immediately (unsigned arithmetic keeps this wrap-safe).
169 uint32_t stall_log_ms = millis() - LOG_THROTTLE_MS;
170
171 while (true) {
172 // Not holding any data while blocked waiting for more.
173 this->usb_tx_busy_ = 0;
174
175 // Wait for a notification from the bridge component
176 ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
177
178 // Raise the busy flag before pulling data out of the ring buffer, so at every
179 // instant flush() sees pending bytes in the ring buffer count or in this flag.
180 this->usb_tx_busy_ = 1;
181
182 // When we do wake up, we can be sure there is data in the ring buffer
183 esp_err_t ret = ringbuf_read_bytes(this->usb_tx_ringbuf_, data, CONFIG_TINYUSB_CDC_TX_BUFSIZE, &tx_data_size, 0);
184
185 if (ret != ESP_OK) {
186 ESP_LOGE(TAG, "USB TX itf=%d: RingBuf read failed", this->itf_);
187 continue;
188 } else if (tx_data_size == 0) {
189 ESP_LOGD(TAG, "USB TX itf=%d: RingBuf empty, skipping", this->itf_);
190 continue;
191 }
192
193 ESP_LOGV(TAG, "USB TX itf=%d: Read %d bytes from buffer", this->itf_, tx_data_size);
194 ESP_LOGVV_HEX(TAG, data, tx_data_size, USB_CDC_MAX_LOG_BYTES, "data = %s");
195
196 // Serial data will be split up into 64 byte chunks to be sent over USB so this
197 // usually will take multiple iterations
198 uint8_t *data_head = &data[0];
199
200 while (tx_data_size > 0) {
201 size_t queued =
202 tinyusb_cdcacm_write_queue(static_cast<tinyusb_cdcacm_itf_t>(this->itf_), data_head, tx_data_size);
203 ESP_LOGV(TAG, "USB TX itf=%d: enqueued: size=%d, queued=%u", this->itf_, tx_data_size, queued);
204
205 tx_data_size -= queued;
206 data_head += queued;
207
208 ESP_LOGV(TAG, "USB TX itf=%d: waiting 10ms for flush", this->itf_);
209 esp_err_t flush_ret =
210 tinyusb_cdcacm_write_flush(static_cast<tinyusb_cdcacm_itf_t>(this->itf_), pdMS_TO_TICKS(10));
211
212 if (flush_ret == ESP_OK) {
213 continue;
214 }
215
216 // Bytes not yet handed to TinyUSB plus bytes still sitting in its transmit FIFO.
217 // tud_cdc_n_write_occupied() is not public API in the pinned TinyUSB release, so
218 // derive the occupancy from the FIFO depth TinyUSB itself is configured with.
219 const size_t pending = tx_data_size + (CFG_TUD_CDC_TX_BUFSIZE - tud_cdc_n_write_available(this->itf_));
220
221 // A flush timeout only means TinyUSB's transmit FIFO did not fully drain within
222 // the wait window; the queued bytes are untouched and TinyUSB keeps sending them
223 // from its transfer-complete callback once the host polls again. Clearing the
224 // FIFO here would discard the tail of a frame whose head is already on the wire,
225 // corrupting the stream mid-frame. Hold the data and retry instead; sustained
226 // backpressure then propagates to the ring buffer, which drops whole writes with
227 // a warning instead of splitting a frame.
228 //
229 // Gate the retry on DTR (tud_cdc_n_connected()) rather than tud_ready(): an
230 // enumerated-but-idle host (no application holding the port open) never polls
231 // the IN endpoint, so retrying on tud_ready() alone would wedge this task -- and
232 // stall every write_array()/flush() caller behind a full ring buffer -- for as
233 // long as the board sits plugged into an idle PC. DTR means an application has
234 // the port open and is expected to eventually read.
235 if (flush_ret == ESP_ERR_TIMEOUT && tud_cdc_n_connected(this->itf_)) {
236 const uint32_t now = millis();
237 if ((now - stall_log_ms) >= LOG_THROTTLE_MS) {
238 stall_log_ms = now;
239 ESP_LOGW(TAG, "USB TX itf=%d: host not reading; %zu bytes pending", this->itf_, pending);
240 }
241 continue;
242 }
243
244 if (flush_ret == ESP_ERR_TIMEOUT) {
245 // No application has the port open (DTR deasserted) or the device is detached,
246 // so the data cannot be delivered. TinyUSB does not clear its transmit FIFO on
247 // bus reset; drop the data here so a stale partial frame is not replayed when
248 // the port is (re)opened.
249 ESP_LOGW(TAG, "USB TX itf=%d: not connected; dropping %zu bytes", this->itf_, pending);
250 } else {
251 ESP_LOGE(TAG, "USB TX itf=%d: flush failed (%s); dropping %zu bytes", this->itf_, esp_err_to_name(flush_ret),
252 pending);
253 }
254 tud_cdc_n_write_clear(this->itf_);
255 break;
256 }
257 }
258}
259
260//==============================================================================
261// UARTComponent Interface Implementation
262//==============================================================================
263
264void USBCDCACMInstance::write_array(const uint8_t *data, size_t len) {
265 if (len == 0) {
266 return;
267 }
268
269 // Write data to TX ring buffer
270 BaseType_t send_res = xRingbufferSend(this->usb_tx_ringbuf_, data, len, 0);
271 if (send_res != pdTRUE) {
272 // A full ring buffer is the intended backpressure during a host stall
273 this->record_tx_drop_(len);
274 return;
275 }
276 // Notify TX task that data is available
277 if (this->usb_tx_task_handle_ != nullptr) {
278 xTaskNotifyGive(this->usb_tx_task_handle_);
279 }
280 this->report_tx_debug_(data, len);
281}
282
283bool USBCDCACMInstance::read_array(uint8_t *data, size_t len) {
284 if (len == 0) {
285 return true;
286 }
287
288 if (this->consume_peek_(data, len)) {
289 return true;
290 }
291 size_t original_len = len;
292 size_t bytes_read = 0;
293
294 // Read remaining bytes from RX ring buffer
295 size_t rx_size = 0;
296 uint8_t *buf = static_cast<uint8_t *>(xRingbufferReceiveUpTo(this->usb_rx_ringbuf_, &rx_size, 0, len));
297 if (buf == nullptr) {
298 return false;
299 }
300
301 memcpy(data, buf, rx_size);
302 vRingbufferReturnItem(this->usb_rx_ringbuf_, (void *) buf);
303 this->report_rx_debug_(data, rx_size);
304 bytes_read += rx_size;
305 data += rx_size;
306 len -= rx_size;
307 if (len == 0) {
308 return true; // No more to read
309 }
310
311 // Buffer's data may wrap around, in which case we should perform another read
312 buf = static_cast<uint8_t *>(xRingbufferReceiveUpTo(this->usb_rx_ringbuf_, &rx_size, 0, len));
313 if (buf == nullptr) {
314 return false;
315 }
316
317 memcpy(data, buf, rx_size);
318 vRingbufferReturnItem(this->usb_rx_ringbuf_, (void *) buf);
319 this->report_rx_debug_(data, rx_size);
320 bytes_read += rx_size;
321
322 return bytes_read == original_len;
323}
324
326 UBaseType_t waiting = 0;
327 if (this->usb_rx_ringbuf_ != nullptr) {
328 vRingbufferGetInfo(this->usb_rx_ringbuf_, nullptr, nullptr, nullptr, nullptr, &waiting);
329 }
330 return waiting + (this->has_peek_ ? 1 : 0);
331}
332
333// True while TX bytes have not yet reached TinyUSB's FIFO: still counted in the ring
334// buffer, or held by the TX task (usb_tx_busy_) between pulling them from the ring
335// buffer and handing them to TinyUSB -- there they are in neither the ring buffer
336// count nor TinyUSB's FIFO.
338 UBaseType_t waiting = 0;
339 vRingbufferGetInfo(this->usb_tx_ringbuf_, nullptr, nullptr, nullptr, nullptr, &waiting);
340 return waiting != 0 || this->usb_tx_busy_ != 0;
341}
342
344 if (this->usb_tx_ringbuf_ == nullptr) {
346 }
347
348 // Bound the wait: when the host stalls or disconnects, the TX task holds on to
349 // pending data rather than discarding it, so the ring buffer may not drain for as
350 // long as the host stays away. flush() runs on the caller's (typically the main
351 // loop) task and must not block indefinitely. Signed tick differences keep the
352 // deadline arithmetic wrap-safe.
353 TickType_t now = xTaskGetTickCount();
354 const TickType_t deadline = now + pdMS_TO_TICKS(FLUSH_TIMEOUT_MS);
355 while (this->tx_pending_()) {
356 if (static_cast<int32_t>(now - deadline) >= 0) {
358 }
359 vTaskDelay(pdMS_TO_TICKS(1));
360 now = xTaskGetTickCount();
361 }
362
363 // Also wait for USB to finish transmitting, within whatever remains of the budget.
364 // Floor at one tick: a zero-tick timeout takes esp_tinyusb's non-blocking branch,
365 // whose return contract is that library's internal detail and may differ between
366 // releases. One tick keeps the call on the blocking branch (ESP_OK/ESP_ERR_TIMEOUT)
367 // at the cost of at most one tick over budget.
368 const int32_t remaining = static_cast<int32_t>(deadline - now);
369 const TickType_t flush_ticks = remaining > 0 ? static_cast<TickType_t>(remaining) : 1;
370 switch (tinyusb_cdcacm_write_flush(static_cast<tinyusb_cdcacm_itf_t>(this->itf_), flush_ticks)) {
371 case ESP_OK:
373 case ESP_ERR_TIMEOUT:
374 // ESP_ERR_NOT_FINISHED is the non-blocking branch's "still draining" result;
375 // mapped like a timeout in case a future esp_tinyusb release returns it here.
376 case ESP_ERR_NOT_FINISHED:
378 default:
380 }
381}
382
383} // namespace esphome::usb_cdc_acm
384#endif
USBCDCACMInstance * get_interface_by_number(uint8_t itf)
Represents a single CDC ACM interface instance.
Definition usb_cdc_acm.h:96
void report_tx_debug_(const uint8_t *data, size_t len)
std::array< uint8_t, CONFIG_TINYUSB_CDC_TX_BUFSIZE > usb_tx_staging_
bool read_array(uint8_t *data, size_t len) override
uart::UARTFlushResult flush() override
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
int ret
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")
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
ESPHOME_ALWAYS_INLINE char format_hex_char(uint8_t v, char base)
Convert a nibble (0-15) to hex char with specified base ('a' for lowercase, 'A' for uppercase)
Definition helpers.h:1534
const void size_t len
Definition hal.h:68
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t