ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
cdc_acm_uart_bridge.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)
4#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6
7#include <algorithm>
8#include "freertos/FreeRTOS.h"
9#include "freertos/task.h"
10#include "freertos/ringbuf.h"
11#include "driver/uart.h"
12#include "soc/soc_caps.h"
13
15
16ESPHOME_LOG_TAG(TAG, "cdc_acm_uart");
17
18static constexpr size_t UART_TASK_STACK_SIZE = 4096;
19static constexpr size_t RINGBUF_RETRY_CHUNK_SIZE = 64;
20static constexpr uint32_t LOG_THROTTLE_MS = 1000;
21static constexpr uint32_t UART_RELOAD_SETTLE_MS = 20;
22// Above the default priority but below the USB/Wi-Fi system tasks.
23static constexpr UBaseType_t TASK_PRIORITY = 4;
24
25static bool should_log_now(uint32_t *last_ms, uint32_t interval_ms) {
26 uint32_t now = millis();
27 if ((now - *last_ms) >= interval_ms) {
28 *last_ms = now;
29 return true;
30 }
31 return false;
32}
33
34static bool ringbuf_send_with_retry(RingbufHandle_t ringbuf, const uint8_t *data, size_t len, uint32_t *log_ms) {
35 if (len == 0) {
36 return true;
37 }
38
39 if (xRingbufferSend(ringbuf, data, len, pdMS_TO_TICKS(1)) == pdTRUE) {
40 return true;
41 }
42
43 size_t offset = 0;
44 while (offset < len) {
45 size_t chunk = std::min(RINGBUF_RETRY_CHUNK_SIZE, len - offset);
46 if (xRingbufferSend(ringbuf, data + offset, chunk, pdMS_TO_TICKS(1)) != pdTRUE) {
47 if (should_log_now(log_ms, LOG_THROTTLE_MS)) {
48 ESP_LOGW(TAG, "USB TX buffer full; some data is lost");
49 }
50 return false;
51 }
52 offset += chunk;
53 }
54 return true;
55}
56
58 // Line state starts deasserted (no host yet); active-low DTR#/RTS# wiring is
59 // handled by configuring the pins inverted, so deasserted idles HIGH.
60 setup_output_pin(this->dtr_pin_, false);
61
62 setup_output_pin(this->rts_pin_, false);
63
64 // A failed UART never assigned its port number, so the worker tasks would run
65 // against an indeterminate port.
66 if (this->uart_parent_->is_failed()) {
67 ESP_LOGE(TAG, "UART parent failed; aborting");
68 this->mark_failed();
69 return;
70 }
71
76
77 // usb_cdc_acm sets up first (priority IO > HARDWARE). Any interface failing marks
78 // the hub failed, and a failed hub no longer runs loop(), so line coding and line
79 // state events would never reach this bridge even if its own interface is healthy.
80 if (this->usb_cdc_parent_->get_parent()->is_failed()) {
81 ESP_LOGE(TAG, "USB CDC ACM failed; aborting");
82 this->mark_failed();
83 return;
84 }
85
86 // Per-instance task names (keyed on the CDC interface number) keep task dumps
87 // unambiguous with multiple bridges.
88 char tx_task_name[] = "cdc_uart_tx_0";
89 char rx_task_name[] = "cdc_uart_rx_0";
90 const char itf_char = format_hex_char(this->usb_cdc_parent_->get_itf());
91 tx_task_name[sizeof(tx_task_name) - 2] = itf_char;
92 rx_task_name[sizeof(rx_task_name) - 2] = itf_char;
93
94 xTaskCreate(uart_tx_task_fn, tx_task_name, UART_TASK_STACK_SIZE, this, TASK_PRIORITY, &this->uart_tx_task_handle_);
95 if (this->uart_tx_task_handle_ == nullptr) {
96 ESP_LOGE(TAG, "Failed to create UART TX task");
97 this->mark_failed();
98 return;
99 }
100
101 xTaskCreate(uart_rx_task_fn, rx_task_name, UART_TASK_STACK_SIZE, this, TASK_PRIORITY, &this->uart_rx_task_handle_);
102 if (this->uart_rx_task_handle_ == nullptr) {
103 ESP_LOGE(TAG, "Failed to create UART RX task");
104 vTaskDelete(this->uart_tx_task_handle_);
105 this->uart_tx_task_handle_ = nullptr;
106 this->mark_failed();
107 return;
108 }
109
110 // Only register callbacks once both tasks exist, so a failed setup never drives
111 // DTR/RTS from a dead bridge.
112 this->usb_cdc_parent_->set_line_state_callback([this](bool dtr, bool rts) { this->set_line_state(dtr, rts); });
113 this->usb_cdc_parent_->set_line_coding_callback([this](uint32_t, uint8_t, uint8_t, uint8_t) {
114 this->host_coding_seen_ = true;
115 // Another component owns the UART's framing while paused; resume() re-syncs.
116 if (this->paused_ == 0) {
117 this->set_line_coding();
118 }
119 });
120
121 // Release the workers only now: until here a failed setup may still delete the TX
122 // task, which is safe only while it is parked and owns nothing in the driver.
123 xTaskNotifyGive(this->uart_tx_task_handle_);
124 xTaskNotifyGive(this->uart_rx_task_handle_);
125
126 // loop() only services line-coding reloads; stay off the main loop until one is
127 // scheduled.
128 this->disable_loop();
129}
130
132 ESP_LOGCONFIG(TAG,
133 "CDC-ACM UART Bridge:\n"
134 " UART Bus: %u\n"
135 " USB CDC Interface: %u",
136 this->uart_parent_->get_hw_serial_number(), this->usb_cdc_parent_->get_itf());
137 LOG_PIN(" DTR Pin: ", this->dtr_pin_);
138 LOG_PIN(" RTS Pin: ", this->rts_pin_);
139}
140
142 // The UART (BUS) shuts down after this component (HARDWARE) and deletes its driver,
143 // freeing the ring buffer and mutexes the worker tasks block on. Suspending the
144 // tasks unlinks them from those objects first.
145 if (this->uart_rx_task_handle_ != nullptr) {
146 vTaskSuspend(this->uart_rx_task_handle_);
147 }
148 if (this->uart_tx_task_handle_ != nullptr) {
149 vTaskSuspend(this->uart_tx_task_handle_);
150 }
151}
152
154 switch (this->state_) {
156 if ((App.get_loop_component_start_time() - this->reload_requested_at_) < UART_RELOAD_SETTLE_MS) {
157 return;
158 }
159 // Deliberately not gated on tx_idle_(): a host that re-codes the line mid-stream
160 // wants the new framing now, and its own in-flight bytes are its concern.
161 // apply_settings_live() rewrites the framing registers without reinstalling the
162 // driver, so the worker tasks blocked inside it are undisturbed.
165 break;
168 // Let a host write that was in flight drain, FIFO included, before a reload
169 // flushes the FIFOs and truncates it.
170 if (!this->tx_idle_()) {
171 return;
172 }
176 } else {
177 this->finish_resume_();
178 }
179 break;
180 default:
181 break;
182 }
183 this->disable_loop();
184}
185
187 if (!this->sync_host_framing_()) {
188 return;
189 }
190 // Coalesce rapid line-coding updates from the host.
193 // Main-loop context (via USBCDCACMInstance::process_events_).
194 this->enable_loop();
195}
196
198 // usb_cdc_acm has already translated the wire coding onto the CDC instance (main
199 // loop); mirror it here so the framing translation has a single source of truth.
200 bool changed = false;
201
202 // Reject 0 (the CDC B0/hang-up encoding; older IDF revisions divide by the rate)
203 // and rates above the SoC ceiling. Anything in between is the driver's call,
204 // matching what a YAML-configured UART accepts.
205 const uint32_t baud = this->usb_cdc_parent_->get_baud_rate();
206 if (baud == 0 || baud > SOC_UART_BITRATE_MAX) {
207 ESP_LOGW(TAG, "Ignoring unsupported baud rate %" PRIu32 " from host; keeping %" PRIu32, baud,
208 this->uart_parent_->get_baud_rate());
209 } else if (this->uart_parent_->get_baud_rate() != baud) {
210 this->uart_parent_->set_baud_rate(baud);
211 changed = true;
212 }
213
214 const uint8_t stop_bits = this->usb_cdc_parent_->get_stop_bits();
215 if (this->uart_parent_->get_stop_bits() != stop_bits) {
216 this->uart_parent_->set_stop_bits(stop_bits);
217 changed = true;
218 }
219
220 const auto parity = this->usb_cdc_parent_->get_parity();
221 if (this->uart_parent_->get_parity() != parity) {
222 this->uart_parent_->set_parity(parity);
223 changed = true;
224 }
225
226 // USB CDC permits data-bit counts the UART cannot represent (up to 16).
227 const uint8_t data_bits = this->usb_cdc_parent_->get_data_bits();
228 if (data_bits < 5 || data_bits > 8) {
229 ESP_LOGW(TAG, "Ignoring unsupported data bits %u from host; keeping %u", data_bits,
230 this->uart_parent_->get_data_bits());
231 } else if (this->uart_parent_->get_data_bits() != data_bits) {
232 this->uart_parent_->set_data_bits(data_bits);
233 changed = true;
234 }
235
236 if (changed) {
237 ESP_LOGV(TAG, "Line coding: baud=%" PRIu32 ", data_bits=%u, stop_bits=%u, parity=%u",
238 this->uart_parent_->get_baud_rate(), this->uart_parent_->get_data_bits(),
239 this->uart_parent_->get_stop_bits(), static_cast<uint8_t>(this->uart_parent_->get_parity()));
240 }
241 return changed;
242}
243
246 return;
247 }
248 this->paused_ = 1;
249 // A null RX task means setup() has not completed (or failed): nothing to stop, and
250 // the framing snapshot does not exist yet. Should setup() run later, the RX task
251 // starts parked.
252 if (this->uart_rx_task_handle_ == nullptr) {
254 return;
255 }
256 // Drops a coalesced host reload or a pending resume; loop() restores the framing
257 // once any host write in flight has drained.
259 this->enable_loop();
260}
261
264 return;
265 }
266 if (this->uart_rx_task_handle_ == nullptr) {
267 this->paused_ = 0;
269 return;
270 }
271 // A restore still waiting on the TX side is moot: the host's framing is kept.
272 if (!this->tx_idle_()) {
274 this->enable_loop();
275 return;
276 }
277 this->finish_resume_();
278 this->disable_loop();
279}
280
282 // Take the bus back at a known framing before either task runs again: the host's
283 // if it ever sent one, else the YAML framing (the other owner may have changed it).
284 if (this->host_coding_seen_) {
285 this->sync_host_framing_();
287 } else {
289 }
290 this->paused_ = 0;
292 this->drive_line_state_();
293 xTaskNotifyGive(this->uart_rx_task_handle_);
294}
295
297 const auto uart_num = static_cast<uart_port_t>(this->uart_parent_->get_hw_serial_number());
298 return this->tx_busy_ == 0 && uart_wait_tx_done(uart_num, 0) == ESP_OK;
299}
300
302 // Always applied: the cached settings can lead the hardware by a pending reload,
303 // so they are no proof of what is live.
309}
310
311void CDCACMUARTBridge::set_line_state(bool dtr, bool rts) {
312 ESP_LOGV(TAG, "Line state: DTR=%d, RTS=%d", dtr, rts);
313 this->host_dtr_ = dtr;
314 this->host_rts_ = rts;
315 // Frozen while paused: a host opening the port must not reset a peer that another
316 // component is talking to.
317 if (this->paused_ == 0) {
318 this->drive_line_state_();
319 }
320}
321
323 if (this->dtr_pin_ != nullptr) {
324 this->dtr_pin_->digital_write(this->host_dtr_);
325 }
326 if (this->rts_pin_ != nullptr) {
327 this->rts_pin_->digital_write(this->host_rts_);
328 }
329}
330
332 auto *bridge = static_cast<CDCACMUARTBridge *>(arg);
333 bridge->uart_rx_task_();
334}
335
337 auto *bridge = static_cast<CDCACMUARTBridge *>(arg);
338 bridge->uart_tx_task_();
339}
340
342 TaskHandle_t usb_tx_handle = this->usb_cdc_parent_->get_tx_task_handle();
343 RingbufHandle_t usb_tx_ringbuf = this->usb_cdc_parent_->get_tx_ringbuf();
344 uart_port_t uart_num = static_cast<uart_port_t>(this->uart_parent_->get_hw_serial_number());
345 // Back-dated so a problem within the first LOG_THROTTLE_MS of uptime still logs.
346 uint32_t tx_full_log_ms = millis() - LOG_THROTTLE_MS;
347 uint32_t err_log_ms = millis() - LOG_THROTTLE_MS;
348
349 uint8_t *data = this->uart_rx_buffer_.data();
350 const size_t buf_size = this->uart_rx_buffer_.size();
351
352 // Released by setup() once both tasks exist.
353 ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
354
355 while (true) {
356 if (this->paused_ != 0) {
357 // Parked until resume() notifies; nothing is read, so the other owner sees
358 // every byte.
359 this->rx_parked_ = 1;
360 ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
361 this->rx_parked_ = 0;
362 continue;
363 }
364
365 // Block until at least one byte is available from UART.
366 int total_rx_size = uart_read_bytes(uart_num, data, 1, pdMS_TO_TICKS(UART_RX_WAIT_MS));
367 if (total_rx_size < 0) {
368 if (should_log_now(&err_log_ms, LOG_THROTTLE_MS)) {
369 ESP_LOGE(TAG, "UART read failed: %d", total_rx_size);
370 }
371 vTaskDelay(pdMS_TO_TICKS(10));
372 continue;
373 }
374 if (total_rx_size == 0) {
375 continue;
376 }
377 // pause() landed during the read: don't forward a byte to a host that is gone.
378 if (this->paused_ != 0) {
379 continue;
380 }
381
382 // Drain the currently buffered burst without waiting.
383 while (true) {
384 int rx_data_size = uart_read_bytes(uart_num, data + total_rx_size, buf_size - total_rx_size, 0);
385 if (rx_data_size < 0) {
386 if (should_log_now(&err_log_ms, LOG_THROTTLE_MS)) {
387 ESP_LOGE(TAG, "UART read failed: %d", rx_data_size);
388 }
389 break;
390 }
391 if (rx_data_size == 0) {
392 break;
393 }
394 ESP_LOGV(TAG, "UART RX: %d bytes", rx_data_size);
395 total_rx_size += rx_data_size;
396 if (total_rx_size >= (int) buf_size) {
397 break;
398 }
399 }
400
401 ringbuf_send_with_retry(usb_tx_ringbuf, data, total_rx_size, &tx_full_log_ms);
402
403 ESP_LOGV(TAG, "UART RX: waking up USB TX task");
404 xTaskNotifyGive(usb_tx_handle);
405 }
406}
407
409 RingbufHandle_t usb_rx_ringbuf = this->usb_cdc_parent_->get_rx_ringbuf();
410 uart_port_t uart_num = static_cast<uart_port_t>(this->uart_parent_->get_hw_serial_number());
411 uint8_t *data_to_uart = this->uart_tx_buffer_.data();
412 const size_t buf_size = this->uart_tx_buffer_.size();
413 size_t rx_size;
414 // Back-dated so a problem within the first LOG_THROTTLE_MS of uptime still logs.
415 uint32_t err_log_ms = millis() - LOG_THROTTLE_MS;
416 uint32_t drop_log_ms = millis() - LOG_THROTTLE_MS;
417
418 // Released by setup() once both tasks exist.
419 ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
420
421 while (true) {
422 ESP_LOGV(TAG, "Waiting for data to send to UART");
423 esp_err_t ret = usb_cdc_acm::ringbuf_read_bytes(usb_rx_ringbuf, data_to_uart, buf_size, &rx_size, portMAX_DELAY);
424
425 if (ret != ESP_OK) {
426 if (should_log_now(&err_log_ms, LOG_THROTTLE_MS)) {
427 ESP_LOGE(TAG, "USB RX RingBuf read failed");
428 }
429 // Yield: this task runs above the main loop, so a persistent failure must not
430 // become a tight loop.
431 vTaskDelay(pdMS_TO_TICKS(10));
432 continue;
433 }
434
435 // Another component owns the UART; host bytes must not interleave with its traffic.
436 // tx_busy_ goes up before the check so is_paused() cannot miss a write in flight.
437 this->tx_busy_ = 1;
438 if (this->paused_ != 0) {
439 this->tx_busy_ = 0;
440 if (should_log_now(&drop_log_ms, LOG_THROTTLE_MS)) {
441 ESP_LOGW(TAG, "Paused; dropping %zu bytes from host", rx_size);
442 }
443 continue;
444 }
445
446 ESP_LOGV(TAG, "Sending %zu bytes to UART", rx_size);
447 // Signed: uart_write_bytes() returns -1 on error.
448 int xfer_size = uart_write_bytes(uart_num, data_to_uart, rx_size);
449 this->tx_busy_ = 0;
450
451 if (xfer_size < 0) {
452 if (should_log_now(&err_log_ms, LOG_THROTTLE_MS)) {
453 ESP_LOGE(TAG, "UART write failed: %d", xfer_size);
454 }
455 } else if (static_cast<size_t>(xfer_size) != rx_size) {
456 ESP_LOGW(TAG, "UART write incomplete (%d/%zu bytes)", xfer_size, rx_size);
457 }
458 }
459}
460
461} // namespace esphome::cdc_acm_uart
462#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.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:288
void enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
virtual void digital_write(bool value)=0
T * get_parent() const
Get the parent of this object.
Definition helpers.h:2438
std::array< uint8_t, CONFIG_TINYUSB_CDC_RX_BUFSIZE > uart_tx_buffer_
void resume()
Re-apply the host's line coding and line state, then resume forwarding.
usb_cdc_acm::USBCDCACMInstance * usb_cdc_parent_
void pause()
Stop forwarding in both directions and hand the UART back to its configured framing,...
std::array< uint8_t, CONFIG_TINYUSB_CDC_TX_BUFSIZE > uart_rx_buffer_
esp_err_t apply_settings_live()
Apply the current framing (baud rate, parity, data/stop bits) to the installed driver in place,...
UARTParityOptions get_parity() const
void set_baud_rate(uint32_t baud_rate)
void set_parity(UARTParityOptions parity)
void set_stop_bits(uint8_t stop_bits)
void set_data_bits(uint8_t data_bits)
RingbufHandle_t get_rx_ringbuf() const
RingbufHandle_t get_tx_ringbuf() const
void set_line_state_callback(LineStateCallback callback)
void set_line_coding_callback(LineCodingCallback callback)
int ret
ESPHOME_LOG_TAG(TAG, "cdc_acm_uart")
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
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:1761
const void size_t len
Definition hal.h:68
void setup_output_pin(GPIOPin *pin, bool level)
Set up pin and drive it to level. Does nothing when pin is null, so an optional pin needs no check.
Definition gpio.cpp:44
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