ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
usb_uart.cpp
Go to the documentation of this file.
1// Should not be needed, but it's required to pass CI clang-tidy checks
2#if defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
3#include "usb_uart.h"
4#include "esphome/core/log.h"
6
7#include <cinttypes>
8
9namespace esphome {
10namespace usb_uart {
11
19static optional<CdcEps> get_cdc(const usb_config_desc_t *config_desc, uint8_t intf_idx) {
20 int conf_offset, ep_offset;
21 // look for an interface with an interrupt endpoint (notify), and one with two bulk endpoints (data in/out)
22 CdcEps eps{};
23 eps.bulk_interface_number = 0xFF;
24 for (;;) {
25 const auto *intf_desc = usb_parse_interface_descriptor(config_desc, intf_idx++, 0, &conf_offset);
26 if (!intf_desc) {
27 ESP_LOGE(TAG, "usb_parse_interface_descriptor failed");
28 return nullopt;
29 }
30 ESP_LOGD(TAG, "intf_desc: bInterfaceClass=%02X, bInterfaceSubClass=%02X, bInterfaceProtocol=%02X, bNumEndpoints=%d",
31 intf_desc->bInterfaceClass, intf_desc->bInterfaceSubClass, intf_desc->bInterfaceProtocol,
32 intf_desc->bNumEndpoints);
33 for (uint8_t i = 0; i != intf_desc->bNumEndpoints; i++) {
34 ep_offset = conf_offset;
35 const auto *ep = usb_parse_endpoint_descriptor_by_index(intf_desc, i, config_desc->wTotalLength, &ep_offset);
36 if (!ep) {
37 ESP_LOGE(TAG, "Ran out of interfaces at %d before finding all endpoints", i);
38 return nullopt;
39 }
40 ESP_LOGD(TAG, "ep: bEndpointAddress=%02X, bmAttributes=%02X", ep->bEndpointAddress, ep->bmAttributes);
41 if (ep->bmAttributes == USB_BM_ATTRIBUTES_XFER_INT) {
42 eps.notify_ep = ep;
43 eps.interrupt_interface_number = intf_desc->bInterfaceNumber;
44 } else if (ep->bmAttributes == USB_BM_ATTRIBUTES_XFER_BULK && ep->bEndpointAddress & usb_host::USB_DIR_IN &&
45 (eps.bulk_interface_number == 0xFF || eps.bulk_interface_number == intf_desc->bInterfaceNumber)) {
46 eps.in_ep = ep;
47 eps.bulk_interface_number = intf_desc->bInterfaceNumber;
48 } else if (ep->bmAttributes == USB_BM_ATTRIBUTES_XFER_BULK && !(ep->bEndpointAddress & usb_host::USB_DIR_IN) &&
49 (eps.bulk_interface_number == 0xFF || eps.bulk_interface_number == intf_desc->bInterfaceNumber)) {
50 eps.out_ep = ep;
51 eps.bulk_interface_number = intf_desc->bInterfaceNumber;
52 } else {
53 ESP_LOGE(TAG, "Unexpected endpoint attributes: %02X", ep->bmAttributes);
54 continue;
55 }
56 }
57 if (eps.in_ep != nullptr && eps.out_ep != nullptr && eps.notify_ep != nullptr)
58 return eps;
59 }
60}
61
62std::vector<CdcEps> USBUartTypeCdcAcm::parse_descriptors(usb_device_handle_t dev_hdl) {
63 const usb_config_desc_t *config_desc;
64 const usb_device_desc_t *device_desc;
65 int desc_offset = 0;
66 std::vector<CdcEps> cdc_devs{};
67
68 // Get required descriptors
69 if (usb_host_get_device_descriptor(dev_hdl, &device_desc) != ESP_OK) {
70 ESP_LOGE(TAG, "get_device_descriptor failed");
71 return {};
72 }
73 if (usb_host_get_active_config_descriptor(dev_hdl, &config_desc) != ESP_OK) {
74 ESP_LOGE(TAG, "get_active_config_descriptor failed");
75 return {};
76 }
77 if (device_desc->bDeviceClass == USB_CLASS_COMM || device_desc->bDeviceClass == USB_CLASS_VENDOR_SPEC) {
78 // single CDC-ACM device
79 if (auto eps = get_cdc(config_desc, 0)) {
80 ESP_LOGV(TAG, "Found CDC-ACM device");
81 cdc_devs.push_back(*eps);
82 }
83 return cdc_devs;
84 }
85 if (((device_desc->bDeviceClass == USB_CLASS_MISC) && (device_desc->bDeviceSubClass == USB_SUBCLASS_COMMON) &&
86 (device_desc->bDeviceProtocol == USB_DEVICE_PROTOCOL_IAD)) ||
87 ((device_desc->bDeviceClass == USB_CLASS_PER_INTERFACE) && (device_desc->bDeviceSubClass == USB_SUBCLASS_NULL) &&
88 (device_desc->bDeviceProtocol == USB_PROTOCOL_NULL))) {
89 // This is a composite device, that uses Interface Association Descriptor
90 const auto *this_desc = reinterpret_cast<const usb_standard_desc_t *>(config_desc);
91 for (;;) {
92 this_desc = usb_parse_next_descriptor_of_type(this_desc, config_desc->wTotalLength,
93 USB_B_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION, &desc_offset);
94 if (!this_desc)
95 break;
96 const auto *iad_desc = reinterpret_cast<const usb_iad_desc_t *>(this_desc);
97
98 if (iad_desc->bFunctionClass == USB_CLASS_COMM && iad_desc->bFunctionSubClass == USB_CDC_SUBCLASS_ACM) {
99 ESP_LOGV(TAG, "Found CDC-ACM device in composite device");
100 if (auto eps = get_cdc(config_desc, iad_desc->bFirstInterface))
101 cdc_devs.push_back(*eps);
102 }
103 }
104 }
105 return cdc_devs;
106}
107
108void RingBuffer::push(uint8_t item) {
109 this->buffer_[this->insert_pos_] = item;
110 this->insert_pos_ = (this->insert_pos_ + 1) % this->buffer_size_;
111}
112void RingBuffer::push(const uint8_t *data, size_t len) {
113 for (size_t i = 0; i != len; i++) {
114 this->buffer_[this->insert_pos_] = *data++;
115 this->insert_pos_ = (this->insert_pos_ + 1) % this->buffer_size_;
116 }
117}
118
120 uint8_t item = this->buffer_[this->read_pos_];
121 this->read_pos_ = (this->read_pos_ + 1) % this->buffer_size_;
122 return item;
123}
124size_t RingBuffer::pop(uint8_t *data, size_t len) {
125 len = std::min(len, this->get_available());
126 for (size_t i = 0; i != len; i++) {
127 *data++ = this->buffer_[this->read_pos_];
128 this->read_pos_ = (this->read_pos_ + 1) % this->buffer_size_;
129 }
130 return len;
131}
132void USBUartChannel::write_array(const uint8_t *data, size_t len) {
133 if (!this->initialised_) {
134 ESP_LOGV(TAG, "Channel not initialised - write ignored");
135 return;
136 }
137 while (this->output_buffer_.get_free_space() != 0 && len-- != 0) {
138 this->output_buffer_.push(*data++);
139 }
140 len++;
141 if (len > 0) {
142 ESP_LOGE(TAG, "Buffer full - failed to write %d bytes", len);
143 }
144 this->parent_->start_output(this);
145}
146
147bool USBUartChannel::peek_byte(uint8_t *data) {
148 if (this->input_buffer_.is_empty()) {
149 return false;
150 }
151 *data = this->input_buffer_.peek();
152 return true;
153}
154bool USBUartChannel::read_array(uint8_t *data, size_t len) {
155 if (!this->initialised_) {
156 ESP_LOGV(TAG, "Channel not initialised - read ignored");
157 return false;
158 }
159 auto available = this->available();
160 bool status = true;
161 if (len > available) {
162 ESP_LOGV(TAG, "underflow: requested %zu but returned %d, bytes", len, available);
163 len = available;
164 status = false;
165 }
166 for (size_t i = 0; i != len; i++) {
167 *data++ = this->input_buffer_.pop();
168 }
169 this->parent_->start_input(this);
170 return status;
171}
172void USBUartComponent::setup() { USBClient::setup(); }
173void USBUartComponent::loop() { USBClient::loop(); }
175 USBClient::dump_config();
176 for (auto &channel : this->channels_) {
177 ESP_LOGCONFIG(TAG,
178 " UART Channel %d\n"
179 " Baud Rate: %" PRIu32 " baud\n"
180 " Data Bits: %u\n"
181 " Parity: %s\n"
182 " Stop bits: %s\n"
183 " Debug: %s\n"
184 " Dummy receiver: %s",
185 channel->index_, channel->baud_rate_, channel->data_bits_, PARITY_NAMES[channel->parity_],
186 STOP_BITS_NAMES[channel->stop_bits_], YESNO(channel->debug_), YESNO(channel->dummy_receiver_));
187 }
188}
190 if (!channel->initialised_ || channel->input_started_ ||
191 channel->input_buffer_.get_free_space() < channel->cdc_dev_.in_ep->wMaxPacketSize)
192 return;
193 const auto *ep = channel->cdc_dev_.in_ep;
194 auto callback = [this, channel](const usb_host::TransferStatus &status) {
195 ESP_LOGV(TAG, "Transfer result: length: %u; status %X", status.data_len, status.error_code);
196 if (!status.success) {
197 ESP_LOGE(TAG, "Control transfer failed, status=%s", esp_err_to_name(status.error_code));
198 return;
199 }
200#ifdef USE_UART_DEBUGGER
201 if (channel->debug_) {
203 std::vector<uint8_t>(status.data, status.data + status.data_len), ','); // NOLINT()
204 }
205#endif
206 channel->input_started_ = false;
207 if (!channel->dummy_receiver_) {
208 for (size_t i = 0; i != status.data_len; i++) {
209 channel->input_buffer_.push(status.data[i]);
210 }
211 }
212 if (channel->input_buffer_.get_free_space() >= channel->cdc_dev_.in_ep->wMaxPacketSize) {
213 this->defer([this, channel] { this->start_input(channel); });
214 }
215 };
216 channel->input_started_ = true;
217 this->transfer_in(ep->bEndpointAddress, callback, ep->wMaxPacketSize);
218}
219
221 if (channel->output_started_)
222 return;
223 if (channel->output_buffer_.is_empty()) {
224 return;
225 }
226 const auto *ep = channel->cdc_dev_.out_ep;
227 auto callback = [this, channel](const usb_host::TransferStatus &status) {
228 ESP_LOGV(TAG, "Output Transfer result: length: %u; status %X", status.data_len, status.error_code);
229 channel->output_started_ = false;
230 this->defer([this, channel] { this->start_output(channel); });
231 };
232 channel->output_started_ = true;
233 uint8_t data[ep->wMaxPacketSize];
234 auto len = channel->output_buffer_.pop(data, ep->wMaxPacketSize);
235 this->transfer_out(ep->bEndpointAddress, callback, data, len);
236#ifdef USE_UART_DEBUGGER
237 if (channel->debug_) {
238 uart::UARTDebug::log_hex(uart::UART_DIRECTION_TX, std::vector<uint8_t>(data, data + len), ','); // NOLINT()
239 }
240#endif
241 ESP_LOGV(TAG, "Output %d bytes started", len);
242}
243
248static void fix_mps(const usb_ep_desc_t *ep) {
249 if (ep != nullptr) {
250 auto *ep_mutable = const_cast<usb_ep_desc_t *>(ep);
251 if (ep->wMaxPacketSize > 64) {
252 ESP_LOGW(TAG, "Corrected MPS of EP %u from %u to 64", ep->bEndpointAddress, ep->wMaxPacketSize);
253 ep_mutable->wMaxPacketSize = 64;
254 }
255 }
256}
258 auto cdc_devs = this->parse_descriptors(this->device_handle_);
259 if (cdc_devs.empty()) {
260 this->status_set_error("No CDC-ACM device found");
261 this->disconnect();
262 return;
263 }
264 ESP_LOGD(TAG, "Found %zu CDC-ACM devices", cdc_devs.size());
265 size_t i = 0;
266 for (auto *channel : this->channels_) {
267 if (i == cdc_devs.size()) {
268 ESP_LOGE(TAG, "No configuration found for channel %d", channel->index_);
269 this->status_set_warning("No configuration found for channel");
270 break;
271 }
272 channel->cdc_dev_ = cdc_devs[i++];
273 fix_mps(channel->cdc_dev_.in_ep);
274 fix_mps(channel->cdc_dev_.out_ep);
275 channel->initialised_ = true;
276 auto err =
277 usb_host_interface_claim(this->handle_, this->device_handle_, channel->cdc_dev_.bulk_interface_number, 0);
278 if (err != ESP_OK) {
279 ESP_LOGE(TAG, "usb_host_interface_claim failed: %s, channel=%d, intf=%d", esp_err_to_name(err), channel->index_,
280 channel->cdc_dev_.bulk_interface_number);
281 this->status_set_error("usb_host_interface_claim failed");
282 this->disconnect();
283 return;
284 }
285 }
286 this->enable_channels();
287}
288
290 for (auto *channel : this->channels_) {
291 if (channel->cdc_dev_.in_ep != nullptr) {
292 usb_host_endpoint_halt(this->device_handle_, channel->cdc_dev_.in_ep->bEndpointAddress);
293 usb_host_endpoint_flush(this->device_handle_, channel->cdc_dev_.in_ep->bEndpointAddress);
294 }
295 if (channel->cdc_dev_.out_ep != nullptr) {
296 usb_host_endpoint_halt(this->device_handle_, channel->cdc_dev_.out_ep->bEndpointAddress);
297 usb_host_endpoint_flush(this->device_handle_, channel->cdc_dev_.out_ep->bEndpointAddress);
298 }
299 if (channel->cdc_dev_.notify_ep != nullptr) {
300 usb_host_endpoint_halt(this->device_handle_, channel->cdc_dev_.notify_ep->bEndpointAddress);
301 usb_host_endpoint_flush(this->device_handle_, channel->cdc_dev_.notify_ep->bEndpointAddress);
302 }
303 usb_host_interface_release(this->handle_, this->device_handle_, channel->cdc_dev_.bulk_interface_number);
304 channel->initialised_ = false;
305 channel->input_started_ = false;
306 channel->output_started_ = false;
307 channel->input_buffer_.clear();
308 channel->output_buffer_.clear();
309 }
310 USBClient::on_disconnected();
311}
312
314 for (auto *channel : this->channels_) {
315 if (!channel->initialised_)
316 continue;
317 channel->input_started_ = false;
318 channel->output_started_ = false;
319 this->start_input(channel);
320 }
321}
322
323} // namespace usb_uart
324} // namespace esphome
325#endif // USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3
uint8_t status
Definition bl0942.h:8
void status_set_warning(const char *message=nullptr)
void defer(const std::string &name, std::function< void()> &&f)
Defer a callback to the next loop() call.
void status_set_error(const char *message=nullptr)
static void log_hex(UARTDirection direction, std::vector< uint8_t > bytes, uint8_t separator)
Log the bytes as hex values, separated by the provided separator character.
usb_host_client_handle_t handle_
Definition usb_host.h:94
void transfer_in(uint8_t ep_address, const transfer_cb_t &callback, uint16_t length)
Performs a transfer input operation.
void transfer_out(uint8_t ep_address, const transfer_cb_t &callback, const uint8_t *data, uint16_t length)
Performs an output transfer operation.
usb_device_handle_t device_handle_
Definition usb_host.h:95
void push(uint8_t item)
Definition usb_uart.cpp:108
size_t get_free_space() const
Definition usb_uart.h:56
size_t get_available() const
Definition usb_uart.h:53
bool peek_byte(uint8_t *data) override
Definition usb_uart.cpp:147
void write_array(const uint8_t *data, size_t len) override
Definition usb_uart.cpp:132
bool read_array(uint8_t *data, size_t len) override
Definition usb_uart.cpp:154
std::vector< USBUartChannel * > channels_
Definition usb_uart.h:119
void start_output(USBUartChannel *channel)
Definition usb_uart.cpp:220
void start_input(USBUartChannel *channel)
Definition usb_uart.cpp:189
virtual std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl)
Definition usb_uart.cpp:62
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:279
const nullopt_t nullopt((nullopt_t::init()))
const usb_ep_desc_t * out_ep
Definition usb_uart.h:27
const usb_ep_desc_t * in_ep
Definition usb_uart.h:26