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)
20static optional<CdcEps> get_cdc(
const usb_config_desc_t *config_desc, uint8_t intf_idx) {
21 int conf_offset, ep_offset;
24 eps.bulk_interface_number = 0xFF;
25 eps.interrupt_interface_number = 0xFF;
27 const auto *intf_desc = usb_parse_interface_descriptor(config_desc, intf_idx++, 0, &conf_offset);
29 ESP_LOGE(TAG,
"usb_parse_interface_descriptor failed");
32 ESP_LOGD(TAG,
"intf_desc: bInterfaceClass=%02X, bInterfaceSubClass=%02X, bInterfaceProtocol=%02X, bNumEndpoints=%d",
33 intf_desc->bInterfaceClass, intf_desc->bInterfaceSubClass, intf_desc->bInterfaceProtocol,
34 intf_desc->bNumEndpoints);
35 for (uint8_t i = 0; i != intf_desc->bNumEndpoints; i++) {
36 ep_offset = conf_offset;
37 const auto *ep = usb_parse_endpoint_descriptor_by_index(intf_desc, i, config_desc->wTotalLength, &ep_offset);
39 ESP_LOGE(TAG,
"Ran out of interfaces at %d before finding all endpoints", i);
42 ESP_LOGD(TAG,
"ep: bEndpointAddress=%02X, bmAttributes=%02X", ep->bEndpointAddress, ep->bmAttributes);
43 if (ep->bmAttributes == USB_BM_ATTRIBUTES_XFER_INT) {
45 eps.interrupt_interface_number = intf_desc->bInterfaceNumber;
46 }
else if (ep->bmAttributes == USB_BM_ATTRIBUTES_XFER_BULK && ep->bEndpointAddress & usb_host::USB_DIR_IN &&
47 (eps.bulk_interface_number == 0xFF || eps.bulk_interface_number == intf_desc->bInterfaceNumber)) {
49 eps.bulk_interface_number = intf_desc->bInterfaceNumber;
50 }
else if (ep->bmAttributes == USB_BM_ATTRIBUTES_XFER_BULK && !(ep->bEndpointAddress & usb_host::USB_DIR_IN) &&
51 (eps.bulk_interface_number == 0xFF || eps.bulk_interface_number == intf_desc->bInterfaceNumber)) {
53 eps.bulk_interface_number = intf_desc->bInterfaceNumber;
55 ESP_LOGE(TAG,
"Unexpected endpoint attributes: %02X", ep->bmAttributes);
59 if (eps.in_ep !=
nullptr && eps.out_ep !=
nullptr && eps.notify_ep !=
nullptr)
65 const usb_config_desc_t *config_desc;
66 const usb_device_desc_t *device_desc;
68 std::vector<CdcEps> cdc_devs{};
71 if (usb_host_get_device_descriptor(dev_hdl, &device_desc) != ESP_OK) {
72 ESP_LOGE(TAG,
"get_device_descriptor failed");
75 if (usb_host_get_active_config_descriptor(dev_hdl, &config_desc) != ESP_OK) {
76 ESP_LOGE(TAG,
"get_active_config_descriptor failed");
79 if (device_desc->bDeviceClass == USB_CLASS_COMM || device_desc->bDeviceClass == USB_CLASS_VENDOR_SPEC) {
81 if (
auto eps = get_cdc(config_desc, 0)) {
82 ESP_LOGV(TAG,
"Found CDC-ACM device");
83 cdc_devs.push_back(*eps);
87 if (((device_desc->bDeviceClass == USB_CLASS_MISC) && (device_desc->bDeviceSubClass == USB_SUBCLASS_COMMON) &&
88 (device_desc->bDeviceProtocol == USB_DEVICE_PROTOCOL_IAD)) ||
89 ((device_desc->bDeviceClass == USB_CLASS_PER_INTERFACE) && (device_desc->bDeviceSubClass == USB_SUBCLASS_NULL) &&
90 (device_desc->bDeviceProtocol == USB_PROTOCOL_NULL))) {
92 const auto *this_desc =
reinterpret_cast<const usb_standard_desc_t *
>(config_desc);
94 this_desc = usb_parse_next_descriptor_of_type(this_desc, config_desc->wTotalLength,
95 USB_B_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION, &desc_offset);
98 const auto *iad_desc =
reinterpret_cast<const usb_iad_desc_t *
>(this_desc);
100 if (iad_desc->bFunctionClass == USB_CLASS_COMM && iad_desc->bFunctionSubClass == USB_CDC_SUBCLASS_ACM) {
101 ESP_LOGV(TAG,
"Found CDC-ACM device in composite device");
102 if (
auto eps = get_cdc(config_desc, iad_desc->bFirstInterface))
103 cdc_devs.push_back(*eps);
120 for (
size_t i = 0; i !=
len; i++) {
133 for (
size_t i = 0; i !=
len; i++) {
141 ESP_LOGD(TAG,
"Channel not initialised - write ignored");
144#ifdef USE_UART_DEBUGGER
146 constexpr size_t batch = 16;
148 for (
size_t off = 0; off <
len; off += batch) {
149 size_t n = std::min(
len - off, batch);
157 if (chunk ==
nullptr) {
158 ESP_LOGE(TAG,
"Output pool full - lost %zu bytes",
len);
162 memcpy(chunk->
data, data, chunk_len);
163 chunk->
length = chunk_len;
170 this->
parent_->start_output(
this);
181 this->
parent_->start_output(
this);
184 if (!this->
output_queue_.empty() || this->output_started_.load())
198 ESP_LOGV(TAG,
"Channel not initialised - read ignored");
204 ESP_LOGV(TAG,
"underflow: requested %zu but returned %d, bytes",
len,
available);
208 for (
size_t i = 0; i !=
len; i++) {
211 this->
parent_->start_input(
this);
223 auto *channel = chunk->
channel;
225#ifdef USE_UART_DEBUGGER
226 if (channel->debug_) {
229 ESP_LOGD(TAG,
"%s<<< %s", channel->debug_prefix_.c_str(), buf);
235 if (channel->input_buffer_.get_free_space() < chunk->
length) {
247 if (channel->rx_callback_) {
248 channel->rx_callback_();
253 uint16_t dropped = this->
usb_data_queue_.get_and_reset_dropped_count();
255 ESP_LOGW(TAG,
"Dropped %u USB data chunks due to buffer overflow", dropped);
264 USBClient::dump_config();
268 " Baud Rate: %" PRIu32
" baud\n"
272 " Flush Timeout: %" PRIu32
" ms\n"
274 " Dummy receiver: %s",
275 channel->index_, channel->baud_rate_, channel->data_bits_, PARITY_NAMES[channel->parity_],
276 STOP_BITS_NAMES[channel->stop_bits_], channel->flush_timeout_ms_, YESNO(channel->debug_),
277 YESNO(channel->dummy_receiver_));
296 auto started =
false;
297 if (!channel->
input_started_.compare_exchange_strong(started,
true))
302 ESP_LOGV(TAG,
"Transfer result: length: %u; status %X",
status.data_len,
status.error_code);
304 ESP_LOGE(TAG,
"Input transfer failed, status=%s", esp_err_to_name(
status.error_code));
313 if (chunk ==
nullptr) {
343 if (!this->
transfer_in(ep->bEndpointAddress, callback, ep->wMaxPacketSize)) {
344 ESP_LOGE(TAG,
"IN transfer submission failed for ep=0x%02X", ep->bEndpointAddress);
357 bool expected =
false;
358 if (!channel->
output_started_.compare_exchange_strong(expected,
true, std::memory_order_acq_rel)) {
363 if (chunk ==
nullptr) {
375 ESP_LOGW(TAG,
"Output transfer failed: status %X",
status.error_code);
377 ESP_LOGV(TAG,
"Output Transfer result: length: %u; status %X",
status.data_len,
status.error_code);
393 ESP_LOGV(TAG,
"Output %u bytes started",
len);
400static void fix_mps(
const usb_ep_desc_t *ep) {
402 auto *ep_mutable =
const_cast<usb_ep_desc_t *
>(ep);
403 if (ep->wMaxPacketSize > usb_host::USB_MAX_PACKET_SIZE) {
404 ESP_LOGW(TAG,
"Corrected MPS of EP 0x%02X from %u to %u",
static_cast<uint8_t
>(ep->bEndpointAddress & 0xFF),
405 ep->wMaxPacketSize, usb_host::USB_MAX_PACKET_SIZE);
406 ep_mutable->wMaxPacketSize = usb_host::USB_MAX_PACKET_SIZE;
412 if (cdc_devs.empty()) {
417 ESP_LOGD(TAG,
"Found %zu CDC-ACM devices", cdc_devs.size());
420 if (i == cdc_devs.size()) {
421 ESP_LOGE(TAG,
"No configuration found for channel %d", channel->index_);
425 channel->cdc_dev_ = cdc_devs[i++];
426 fix_mps(channel->cdc_dev_.in_ep);
427 fix_mps(channel->cdc_dev_.out_ep);
428 channel->initialised_.store(
true);
432 if (channel->cdc_dev_.interrupt_interface_number != 0xFF &&
433 channel->cdc_dev_.interrupt_interface_number != channel->cdc_dev_.bulk_interface_number) {
435 channel->cdc_dev_.interrupt_interface_number, 0);
436 if (err_comm != ESP_OK) {
437 ESP_LOGW(TAG,
"Could not claim comm interface %d: %s", channel->cdc_dev_.interrupt_interface_number,
438 esp_err_to_name(err_comm));
439 channel->cdc_dev_.interrupt_interface_number = 0xFF;
441 ESP_LOGD(TAG,
"Claimed comm interface %d", channel->cdc_dev_.interrupt_interface_number);
445 usb_host_interface_claim(this->
handle_, this->
device_handle_, channel->cdc_dev_.bulk_interface_number, 0);
447 ESP_LOGE(TAG,
"usb_host_interface_claim failed: %s, channel=%d, intf=%d", esp_err_to_name(err), channel->index_,
448 channel->cdc_dev_.bulk_interface_number);
460 if (channel->cdc_dev_.in_ep !=
nullptr) {
461 usb_host_endpoint_halt(this->
device_handle_, channel->cdc_dev_.in_ep->bEndpointAddress);
462 usb_host_endpoint_flush(this->
device_handle_, channel->cdc_dev_.in_ep->bEndpointAddress);
464 if (channel->cdc_dev_.out_ep !=
nullptr) {
465 usb_host_endpoint_halt(this->
device_handle_, channel->cdc_dev_.out_ep->bEndpointAddress);
466 usb_host_endpoint_flush(this->
device_handle_, channel->cdc_dev_.out_ep->bEndpointAddress);
468 if (channel->cdc_dev_.notify_ep !=
nullptr) {
469 usb_host_endpoint_halt(this->
device_handle_, channel->cdc_dev_.notify_ep->bEndpointAddress);
470 usb_host_endpoint_flush(this->
device_handle_, channel->cdc_dev_.notify_ep->bEndpointAddress);
472 if (channel->cdc_dev_.interrupt_interface_number != 0xFF &&
473 channel->cdc_dev_.interrupt_interface_number != channel->cdc_dev_.bulk_interface_number) {
474 usb_host_interface_release(this->
handle_, this->
device_handle_, channel->cdc_dev_.interrupt_interface_number);
475 channel->cdc_dev_.interrupt_interface_number = 0xFF;
477 usb_host_interface_release(this->
handle_, this->
device_handle_, channel->cdc_dev_.bulk_interface_number);
479 channel->input_started_.store(
true);
480 channel->output_started_.store(
true);
481 channel->input_buffer_.clear();
485 while ((chunk = channel->output_queue_.pop()) !=
nullptr) {
486 channel->output_pool_.release(chunk);
489 channel->initialised_.store(
false);
491 USBClient::on_disconnected();
495 const uint8_t *response) {
496 static constexpr uint8_t CDC_REQUEST_TYPE = usb_host::USB_TYPE_CLASS | usb_host::USB_RECIP_INTERFACE;
497 static constexpr uint8_t CDC_SET_LINE_CODING = 0x20;
498 static constexpr uint8_t CDC_SET_CONTROL_LINE_STATE = 0x22;
499 static constexpr uint16_t CDC_DTR_RTS = 0x0003;
508 std::vector<uint8_t> line_coding = {
509 static_cast<uint8_t
>(baud & 0xFF),
static_cast<uint8_t
>((baud >> 8) & 0xFF),
510 static_cast<uint8_t
>((baud >> 16) & 0xFF),
static_cast<uint8_t
>((baud >> 24) & 0xFF),
512 static_cast<uint8_t
>(channel->
parity_),
515 ESP_LOGD(TAG,
"SET_LINE_CODING: baud=%u stop=%u parity=%u data=%u", (
unsigned) baud, channel->
stop_bits_,
525 this->
config_transfer_(CDC_REQUEST_TYPE, CDC_SET_CONTROL_LINE_STATE, CDC_DTR_RTS,
566 const std::vector<uint8_t> &data) {
571 type, request, value, index,
575 ESP_LOGW(TAG,
"Config control transfer failed: %s", esp_err_to_name(
status.error_code));
576 }
else if (
status.data_len > 0) {
580 this->
cfg_done_.store(
true, std::memory_order_release);
588 ESP_LOGW(TAG,
"Config control transfer submit failed");
590 this->
cfg_done_.store(
true, std::memory_order_release);
600 if (!this->
cfg_done_.load(std::memory_order_acquire))
609 ESP_LOGV(TAG,
"Config machine: device_phase=%d channel_idx=%d step=%d reload=%d ok=%d", this->
cfg_device_phase_,
628 if (channel !=
nullptr && channel->
initialised_.load()) {
654 }
else if (++this->cfg_channel_idx_ >= this->
channels_.size()) {
669 this->
parent_->apply_channel_settings(
this);
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
void status_set_warning()
void status_clear_error()
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void enable_loop()
Enable this component's loop.
void disable_loop()
Disable this component's loop.
USBUartComponent * parent_
constexpr const char * c_str() const
void load_settings()
Load the UART settings.
usb_host_client_handle_t handle_
bool transfer_out(uint8_t ep_address, const transfer_cb_t &callback, const uint8_t *data, uint16_t length)
Performs an output transfer operation.
virtual void disconnect()
bool process_usb_events_()
bool control_transfer(uint8_t type, uint8_t request, uint16_t value, uint16_t index, const transfer_cb_t &callback, const std::vector< uint8_t > &data={})
bool transfer_in(uint8_t ep_address, const transfer_cb_t &callback, uint16_t length)
Performs a transfer input operation.
usb_device_handle_t device_handle_
size_t get_free_space() const
size_t get_available() const
EventPool< UsbOutputChunk, USB_OUTPUT_CHUNK_COUNT - 1 > output_pool_
std::atomic< bool > input_started_
std::atomic< bool > initialised_
LockFreeQueue< UsbOutputChunk, USB_OUTPUT_CHUNK_COUNT > output_queue_
size_t available() override
bool peek_byte(uint8_t *data) override
UARTParityOptions parity_
void write_array(const uint8_t *data, size_t len) override
uart::UARTFlushResult flush() override
bool read_array(uint8_t *data, size_t len) override
uint32_t flush_timeout_ms_
std::atomic< bool > output_started_
void start_config_(bool reload)
void config_transfer_(uint8_t type, uint8_t request, uint16_t value, uint16_t index, const std::vector< uint8_t > &data={})
USBUartChannel * cfg_pending_reload_
virtual bool config_step(USBUartChannel *channel, uint8_t step, bool reload, bool ok, const uint8_t *response)=0
USBUartChannel * cfg_single_
std::atomic< bool > cfg_done_
std::vector< USBUartChannel * > channels_
LockFreeQueue< UsbDataChunk, USB_DATA_QUEUE_SIZE > usb_data_queue_
virtual void on_rx_overflow(USBUartChannel *channel)
void start_output(USBUartChannel *channel)
bool run_config_machine_()
virtual bool config_device_step(uint8_t step, bool ok, const uint8_t *response)
void dump_config() override
virtual void start_input(USBUartChannel *channel)
void apply_channel_settings(USBUartChannel *channel)
EventPool< UsbDataChunk, USB_DATA_QUEUE_SIZE - 1 > chunk_pool_
void on_disconnected() override
void on_connected() override
virtual std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl)
bool config_step(USBUartChannel *channel, uint8_t step, bool reload, bool ok, const uint8_t *response) override
UARTFlushResult
Result of a flush() call.
@ UART_FLUSH_RESULT_SUCCESS
Confirmed: all bytes left the TX FIFO.
@ UART_FLUSH_RESULT_TIMEOUT
Confirmed: timed out before TX completed.
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
uint32_t IRAM_ATTR HOT millis()
Application App
Global storage of Application pointer - only one Application can exist.
const usb_ep_desc_t * out_ep
const usb_ep_desc_t * in_ep
uint8_t interrupt_interface_number
uint8_t data[usb_host::USB_MAX_PACKET_SIZE]
uint8_t data[MAX_CHUNK_SIZE]
static constexpr size_t MAX_CHUNK_SIZE