ESPHome 2026.10.1
Loading...
Searching...
No Matches
usb_host.h
Go to the documentation of this file.
1#pragma once
2
3// Should not be needed, but it's required to pass CI clang-tidy checks
4#if defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || \
5 defined(USE_ESP32_VARIANT_ESP32S31) || defined(USE_ESP32_VARIANT_ESP32H4)
9#include <vector>
10#include "usb/usb_host.h"
11#include <freertos/FreeRTOS.h>
12#include <freertos/task.h>
15#include <atomic>
16#include <span>
17
18namespace esphome::usb_host {
19
20// THREADING MODEL:
21// This component uses a dedicated USB task for event processing to prevent data loss.
22// - USB Task (high priority): Handles USB events, executes transfer callbacks, releases transfer slots
23// - Main Loop Task: Initiates transfers, processes device connect/disconnect events
24//
25// Thread-safe communication:
26// - Lock-free queues for USB task -> main loop events (SPSC pattern)
27// - Lock-free TransferRequest pool using atomic bitmask (MCMP pattern - multi-consumer, multi-producer)
28//
29// TransferRequest pool access pattern:
30// - get_trq_() [allocate]: Called from BOTH USB task and main loop threads
31// * USB task: via USB UART input callbacks that restart transfers immediately
32// * Main loop: for output transfers and flow-controlled input restarts
33// - release_trq() [deallocate]: Called from BOTH USB task and main loop threads
34// * USB task: immediately after transfer callback completes (critical for preventing slot exhaustion)
35// * Main loop: when transfer submission fails
36//
37// The multi-threaded allocation/deallocation is intentional for performance:
38// - USB task can immediately restart input transfers and release slots without context switching
39// - Main loop controls backpressure by deciding when to restart after consuming data
40// The atomic bitmask ensures thread-safe allocation/deallocation without mutex blocking.
41
42static const char *const TAG = "usb_host";
43
44// Forward declarations
45struct TransferRequest;
46class USBClient;
47
48// constants for setup packet type
49static constexpr uint8_t USB_RECIP_DEVICE = 0;
50static constexpr uint8_t USB_RECIP_INTERFACE = 1;
51static constexpr uint8_t USB_RECIP_ENDPOINT = 2;
52static constexpr uint8_t USB_TYPE_STANDARD = 0 << 5;
53static constexpr uint8_t USB_TYPE_CLASS = 1 << 5;
54static constexpr uint8_t USB_TYPE_VENDOR = 2 << 5;
55static constexpr uint8_t USB_DIR_MASK = 1 << 7;
56static constexpr uint8_t USB_DIR_IN = 1 << 7;
57static constexpr uint8_t USB_DIR_OUT = 0;
58static constexpr size_t SETUP_PACKET_SIZE = 8;
59
60static constexpr size_t MAX_REQUESTS = USB_HOST_MAX_REQUESTS; // maximum number of outstanding requests possible.
61static_assert(MAX_REQUESTS >= 1 && MAX_REQUESTS <= 32, "MAX_REQUESTS must be between 1 and 32");
62
63// Select appropriate bitmask type for tracking allocation of TransferRequest slots.
64// The bitmask must have at least as many bits as MAX_REQUESTS, so:
65// - Use uint16_t for up to 16 requests (MAX_REQUESTS <= 16)
66// - Use uint32_t for 17-32 requests (MAX_REQUESTS > 16)
67// This is tied to the static_assert above, which enforces MAX_REQUESTS is between 1 and 32.
68// If MAX_REQUESTS is increased above 32, this logic and the static_assert must be updated.
69using trq_bitmask_t = std::conditional<(MAX_REQUESTS <= 16), uint16_t, uint32_t>::type;
70static constexpr trq_bitmask_t ALL_REQUESTS_IN_USE = MAX_REQUESTS == 32 ? ~0 : (1 << MAX_REQUESTS) - 1;
71
72static constexpr size_t USB_MAX_PACKET_SIZE =
73 USB_HOST_MAX_PACKET_SIZE; // Max USB packet size (64 for FS, 512 for P4 HS)
74static constexpr size_t USB_EVENT_QUEUE_SIZE = 32; // Size of event queue between USB task and main loop
75static constexpr size_t USB_TASK_STACK_SIZE = 4096; // Stack size for USB task (same as ESP-IDF USB examples)
76static constexpr UBaseType_t USB_TASK_PRIORITY = 5; // Higher priority than main loop (tskIDLE_PRIORITY + 5)
77
78// used to report a transfer status
80 uint8_t *data;
81 size_t data_len;
82 void *user_data;
83 uint16_t error_code;
84 uint8_t endpoint;
85 bool success;
86};
87
88using transfer_cb_t = std::function<void(const TransferStatus &)>;
89
90class USBClient;
91
92// struct used to capture all data needed for a transfer
99
104
105struct UsbEvent {
107 union {
108 struct {
109 uint8_t address;
111 struct {
112 usb_device_handle_t handle;
115
116 // Required for EventPool - no cleanup needed for POD types
117 void release() {}
118};
119
120// callback function type.
121
122// USB string descriptors hold at most 126 characters; one more for the terminator
123static constexpr size_t DESC_STRING_BUF_SIZE = 128;
124
128 uint16_t vendor_id;
129 uint16_t product_id;
130 uint16_t bcd_device;
131 char manufacturer[DESC_STRING_BUF_SIZE];
132 char product[DESC_STRING_BUF_SIZE];
133 char serial_number[DESC_STRING_BUF_SIZE];
134};
135
139bool copy_descriptor_string(const usb_str_desc_t *desc, std::span<char, DESC_STRING_BUF_SIZE> buffer);
140
149class USBClient : public Component {
150 friend class USBHost;
151
152 public:
153 USBClient(uint16_t vid, uint16_t pid) : trq_in_use_(0), vid_(vid), pid_(pid) {}
154 void setup() override;
155 void loop() override;
156 // setup must happen after the host bus has been setup
157 float get_setup_priority() const override { return setup_priority::IO; }
158 void on_opened(uint8_t addr);
159 void on_removed(usb_device_handle_t handle);
160 bool transfer_in(uint8_t ep_address, const transfer_cb_t &callback, uint16_t length);
161 bool transfer_out(uint8_t ep_address, const transfer_cb_t &callback, const uint8_t *data, uint16_t length);
162 void dump_config() override;
163 void release_trq(TransferRequest *trq);
165 bool control_transfer(uint8_t type, uint8_t request, uint16_t value, uint16_t index, const transfer_cb_t &callback,
166 const std::vector<uint8_t> &data = {});
167 void set_manufacturer_filter(const char16_t *manufacturer) { this->manufacturer_filter_ = manufacturer; }
168 void set_product_filter(const char16_t *product) { this->product_filter_ = product; }
169
171 bool is_connected() const { return this->connection_reported_; }
172
175 bool get_device_info(UsbDeviceInfo &info) const;
176
183 template<typename F> void add_on_connection_callback(F &&callback) {
184 this->connection_callback_.add(std::forward<F>(callback));
185 }
186
187 // Lock-free event queue and pool for USB task to main loop communication
188 // Must be public for access from static callbacks
190 // Pool sized to queue capacity (SIZE-1) because LockFreeQueue<T,N> is a ring
191 // buffer that holds N-1 elements. This guarantees allocate() returns nullptr
192 // before push() can fail, preventing a pool slot leak.
193 EventPool<UsbEvent, USB_EVENT_QUEUE_SIZE - 1> event_pool;
194
195 protected:
196 // Process USB events from the queue. Returns true if any work was done.
197 // Subclasses should call this instead of USBClient::loop() to combine
198 // with their own work check for a single disable_loop() decision.
199 bool process_usb_events_();
200 void handle_open_state_();
201 TransferRequest *get_trq_(); // Lock-free allocation using atomic bitmask (multi-consumer safe)
202 virtual void disconnect();
203 virtual void on_connected() {}
204
207 virtual bool reports_connection_itself() const { return false; }
210 void report_connected_();
211 virtual void on_disconnected() {
212 // Reset all requests to available (all bits to 0)
213 this->trq_in_use_.store(0);
214 }
215
216 // USB task management
217 static void usb_task_fn(void *arg);
218 [[noreturn]] void usb_task_loop_() const;
219
220 // Members ordered to minimize struct padding on 32-bit platforms
221 TransferRequest requests_[MAX_REQUESTS]{};
222 TaskHandle_t usb_task_handle_{nullptr};
223 usb_host_client_handle_t handle_{};
224 usb_device_handle_t device_handle_{};
228 // Lock-free pool management using atomic bitmask (no dynamic allocation)
229 // Bit i = 1: requests_[i] is in use, Bit i = 0: requests_[i] is available
230 // Supports multiple concurrent consumers and producers (both threads can allocate/deallocate)
231 std::atomic<trq_bitmask_t> trq_in_use_;
232 const char16_t *manufacturer_filter_{nullptr};
233 const char16_t *product_filter_{nullptr};
234 uint16_t vid_{};
235 uint16_t pid_{};
236 // Whether the connection callbacks were told about the current device, so a removal is
237 // only ever reported for a device that was reported connected
239};
240class USBHost final : public Component {
241 public:
242 float get_setup_priority() const override { return setup_priority::BUS; }
243 void loop() override;
244 void setup() override;
245
246 protected:
247 std::vector<USBClient *> clients_{};
248};
249
250} // namespace esphome::usb_host
251
252#endif // USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3 ||
253 // USE_ESP32_VARIANT_ESP32S31 || USE_ESP32_VARIANT_ESP32H4
USBClient(uint16_t vid, uint16_t pid)
Definition usb_host.h:153
LazyCallbackManager< void(bool)> connection_callback_
Definition usb_host.h:227
virtual bool reports_connection_itself() const
Whether the subclass reports the device as connected itself, once its own setup of the device has fin...
Definition usb_host.h:207
trq_bitmask_t get_trq_in_use() const
Definition usb_host.h:164
usb_host_client_handle_t handle_
Definition usb_host.h:223
TransferRequest requests_[MAX_REQUESTS]
Definition usb_host.h:221
float get_setup_priority() const override
Definition usb_host.h:157
bool transfer_out(uint8_t ep_address, const transfer_cb_t &callback, const uint8_t *data, uint16_t length)
Performs an output transfer operation.
void release_trq(TransferRequest *trq)
const char16_t * product_filter_
Definition usb_host.h:233
static void usb_task_fn(void *arg)
void set_product_filter(const char16_t *product)
Definition usb_host.h:168
virtual void on_connected()
Definition usb_host.h:203
EventPool< UsbEvent, USB_EVENT_QUEUE_SIZE - 1 > event_pool
Definition usb_host.h:193
bool is_connected() const
Whether a device has been opened and its setup by the subclass has finished.
Definition usb_host.h:171
TaskHandle_t usb_task_handle_
Definition usb_host.h:222
const char16_t * manufacturer_filter_
Definition usb_host.h:232
bool get_device_info(UsbDeviceInfo &info) const
Copy the connected device's identity out of the cached USB descriptors.
virtual void on_disconnected()
Definition usb_host.h:211
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.
void add_on_connection_callback(F &&callback)
Register a callback for the device this client claims being connected (true) or removed (false).
Definition usb_host.h:183
void on_removed(usb_device_handle_t handle)
usb_device_handle_t device_handle_
Definition usb_host.h:224
void set_manufacturer_filter(const char16_t *manufacturer)
Definition usb_host.h:167
std::atomic< trq_bitmask_t > trq_in_use_
Definition usb_host.h:231
void report_connected_()
Report the claimed device to the connection callbacks.
LockFreeQueue< UsbEvent, USB_EVENT_QUEUE_SIZE > event_queue
Definition usb_host.h:189
std::vector< USBClient * > clients_
Definition usb_host.h:247
float get_setup_priority() const override
Definition usb_host.h:242
uint16_t type
uint32_t buffer
Definition gif.cpp:50
constexpr float BUS
For communication buses like i2c/spi.
Definition component.h:39
constexpr float IO
For components that represent GPIO pins like PCF8573.
Definition component.h:41
const char *const TAG
Definition spi.cpp:7
std::conditional<(MAX_REQUESTS<=16), uint16_t, uint32_t >::type trq_bitmask_t
Definition usb_host.h:69
bool copy_descriptor_string(const usb_str_desc_t *desc, std::span< char, DESC_STRING_BUF_SIZE > buffer)
Copy a USB string descriptor into a NUL-terminated buffer.
std::function< void(const TransferStatus &)> transfer_cb_t
Definition usb_host.h:88
Identity of a connected USB device, copied out of the descriptors the USB host stack caches for the l...
Definition usb_host.h:127
char serial_number[DESC_STRING_BUF_SIZE]
Definition usb_host.h:133
char product[DESC_STRING_BUF_SIZE]
Definition usb_host.h:132
char manufacturer[DESC_STRING_BUF_SIZE]
Definition usb_host.h:131
union esphome::usb_host::UsbEvent::@181 data
struct esphome::usb_host::UsbEvent::@181::@182 device_new
usb_device_handle_t handle
Definition usb_host.h:112
struct esphome::usb_host::UsbEvent::@181::@183 device_gone
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle