ESPHome 2026.8.0-dev
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)
8#include <vector>
9#include "usb/usb_host.h"
10#include <freertos/FreeRTOS.h>
11#include <freertos/task.h>
14#include <atomic>
15
17
18// THREADING MODEL:
19// This component uses a dedicated USB task for event processing to prevent data loss.
20// - USB Task (high priority): Handles USB events, executes transfer callbacks, releases transfer slots
21// - Main Loop Task: Initiates transfers, processes device connect/disconnect events
22//
23// Thread-safe communication:
24// - Lock-free queues for USB task -> main loop events (SPSC pattern)
25// - Lock-free TransferRequest pool using atomic bitmask (MCMP pattern - multi-consumer, multi-producer)
26//
27// TransferRequest pool access pattern:
28// - get_trq_() [allocate]: Called from BOTH USB task and main loop threads
29// * USB task: via USB UART input callbacks that restart transfers immediately
30// * Main loop: for output transfers and flow-controlled input restarts
31// - release_trq() [deallocate]: Called from BOTH USB task and main loop threads
32// * USB task: immediately after transfer callback completes (critical for preventing slot exhaustion)
33// * Main loop: when transfer submission fails
34//
35// The multi-threaded allocation/deallocation is intentional for performance:
36// - USB task can immediately restart input transfers and release slots without context switching
37// - Main loop controls backpressure by deciding when to restart after consuming data
38// The atomic bitmask ensures thread-safe allocation/deallocation without mutex blocking.
39
40static const char *const TAG = "usb_host";
41
42// Forward declarations
43struct TransferRequest;
44class USBClient;
45
46// constants for setup packet type
47static constexpr uint8_t USB_RECIP_DEVICE = 0;
48static constexpr uint8_t USB_RECIP_INTERFACE = 1;
49static constexpr uint8_t USB_RECIP_ENDPOINT = 2;
50static constexpr uint8_t USB_TYPE_STANDARD = 0 << 5;
51static constexpr uint8_t USB_TYPE_CLASS = 1 << 5;
52static constexpr uint8_t USB_TYPE_VENDOR = 2 << 5;
53static constexpr uint8_t USB_DIR_MASK = 1 << 7;
54static constexpr uint8_t USB_DIR_IN = 1 << 7;
55static constexpr uint8_t USB_DIR_OUT = 0;
56static constexpr size_t SETUP_PACKET_SIZE = 8;
57
58static constexpr size_t MAX_REQUESTS = USB_HOST_MAX_REQUESTS; // maximum number of outstanding requests possible.
59static_assert(MAX_REQUESTS >= 1 && MAX_REQUESTS <= 32, "MAX_REQUESTS must be between 1 and 32");
60
61// Select appropriate bitmask type for tracking allocation of TransferRequest slots.
62// The bitmask must have at least as many bits as MAX_REQUESTS, so:
63// - Use uint16_t for up to 16 requests (MAX_REQUESTS <= 16)
64// - Use uint32_t for 17-32 requests (MAX_REQUESTS > 16)
65// This is tied to the static_assert above, which enforces MAX_REQUESTS is between 1 and 32.
66// If MAX_REQUESTS is increased above 32, this logic and the static_assert must be updated.
67using trq_bitmask_t = std::conditional<(MAX_REQUESTS <= 16), uint16_t, uint32_t>::type;
68static constexpr trq_bitmask_t ALL_REQUESTS_IN_USE = MAX_REQUESTS == 32 ? ~0 : (1 << MAX_REQUESTS) - 1;
69
70static constexpr size_t USB_MAX_PACKET_SIZE =
71 USB_HOST_MAX_PACKET_SIZE; // Max USB packet size (64 for FS, 512 for P4 HS)
72static constexpr size_t USB_EVENT_QUEUE_SIZE = 32; // Size of event queue between USB task and main loop
73static constexpr size_t USB_TASK_STACK_SIZE = 4096; // Stack size for USB task (same as ESP-IDF USB examples)
74static constexpr UBaseType_t USB_TASK_PRIORITY = 5; // Higher priority than main loop (tskIDLE_PRIORITY + 5)
75
76// used to report a transfer status
78 uint8_t *data;
79 size_t data_len;
80 void *user_data;
81 uint16_t error_code;
82 uint8_t endpoint;
83 bool success;
84};
85
86using transfer_cb_t = std::function<void(const TransferStatus &)>;
87
88class USBClient;
89
90// struct used to capture all data needed for a transfer
97
102
103struct UsbEvent {
105 union {
106 struct {
107 uint8_t address;
109 struct {
110 usb_device_handle_t handle;
113
114 // Required for EventPool - no cleanup needed for POD types
115 void release() {}
116};
117
118// callback function type.
119
128class USBClient : public Component {
129 friend class USBHost;
130
131 public:
132 USBClient(uint16_t vid, uint16_t pid) : trq_in_use_(0), vid_(vid), pid_(pid) {}
133 void setup() override;
134 void loop() override;
135 // setup must happen after the host bus has been setup
136 float get_setup_priority() const override { return setup_priority::IO; }
137 void on_opened(uint8_t addr);
138 void on_removed(usb_device_handle_t handle);
139 bool transfer_in(uint8_t ep_address, const transfer_cb_t &callback, uint16_t length);
140 bool transfer_out(uint8_t ep_address, const transfer_cb_t &callback, const uint8_t *data, uint16_t length);
141 void dump_config() override;
142 void release_trq(TransferRequest *trq);
144 bool control_transfer(uint8_t type, uint8_t request, uint16_t value, uint16_t index, const transfer_cb_t &callback,
145 const std::vector<uint8_t> &data = {});
146
147 // Lock-free event queue and pool for USB task to main loop communication
148 // Must be public for access from static callbacks
150 // Pool sized to queue capacity (SIZE-1) because LockFreeQueue<T,N> is a ring
151 // buffer that holds N-1 elements. This guarantees allocate() returns nullptr
152 // before push() can fail, preventing a pool slot leak.
153 EventPool<UsbEvent, USB_EVENT_QUEUE_SIZE - 1> event_pool;
154
155 protected:
156 // Process USB events from the queue. Returns true if any work was done.
157 // Subclasses should call this instead of USBClient::loop() to combine
158 // with their own work check for a single disable_loop() decision.
159 bool process_usb_events_();
160 void handle_open_state_();
161 TransferRequest *get_trq_(); // Lock-free allocation using atomic bitmask (multi-consumer safe)
162 virtual void disconnect();
163 virtual void on_connected() {}
164 virtual void on_disconnected() {
165 // Reset all requests to available (all bits to 0)
166 this->trq_in_use_.store(0);
167 }
168
169 // USB task management
170 static void usb_task_fn(void *arg);
171 [[noreturn]] void usb_task_loop_() const;
172
173 // Members ordered to minimize struct padding on 32-bit platforms
174 TransferRequest requests_[MAX_REQUESTS]{};
175 TaskHandle_t usb_task_handle_{nullptr};
176 usb_host_client_handle_t handle_{};
177 usb_device_handle_t device_handle_{};
180 // Lock-free pool management using atomic bitmask (no dynamic allocation)
181 // Bit i = 1: requests_[i] is in use, Bit i = 0: requests_[i] is available
182 // Supports multiple concurrent consumers and producers (both threads can allocate/deallocate)
183 std::atomic<trq_bitmask_t> trq_in_use_;
184 uint16_t vid_{};
185 uint16_t pid_{};
186};
187class USBHost final : public Component {
188 public:
189 float get_setup_priority() const override { return setup_priority::BUS; }
190 void loop() override;
191 void setup() override;
192
193 protected:
194 std::vector<USBClient *> clients_{};
195};
196
197} // namespace esphome::usb_host
198
199#endif // USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3 ||
200 // USE_ESP32_VARIANT_ESP32S31 || USE_ESP32_VARIANT_ESP32H4
USBClient(uint16_t vid, uint16_t pid)
Definition usb_host.h:132
trq_bitmask_t get_trq_in_use() const
Definition usb_host.h:143
usb_host_client_handle_t handle_
Definition usb_host.h:176
TransferRequest requests_[MAX_REQUESTS]
Definition usb_host.h:174
float get_setup_priority() const override
Definition usb_host.h:136
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)
static void usb_task_fn(void *arg)
virtual void on_connected()
Definition usb_host.h:163
EventPool< UsbEvent, USB_EVENT_QUEUE_SIZE - 1 > event_pool
Definition usb_host.h:153
TaskHandle_t usb_task_handle_
Definition usb_host.h:175
virtual void on_disconnected()
Definition usb_host.h:164
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 on_removed(usb_device_handle_t handle)
usb_device_handle_t device_handle_
Definition usb_host.h:177
std::atomic< trq_bitmask_t > trq_in_use_
Definition usb_host.h:183
LockFreeQueue< UsbEvent, USB_EVENT_QUEUE_SIZE > event_queue
Definition usb_host.h:149
std::vector< USBClient * > clients_
Definition usb_host.h:194
float get_setup_priority() const override
Definition usb_host.h:189
uint16_t type
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
std::conditional<(MAX_REQUESTS<=16), uint16_t, uint32_t >::type trq_bitmask_t
Definition usb_host.h:67
std::function< void(const TransferStatus &)> transfer_cb_t
Definition usb_host.h:86
usb_device_handle_t handle
Definition usb_host.h:110
union esphome::usb_host::UsbEvent::@180 data
struct esphome::usb_host::UsbEvent::@180::@181 device_new
struct esphome::usb_host::UsbEvent::@180::@182 device_gone
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle