ESPHome 2026.4.3
Loading...
Searching...
No Matches
usb_uart.h
Go to the documentation of this file.
1#pragma once
2
3#if defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
11#include <atomic>
12#include <functional>
13
14namespace esphome::usb_uart {
15
16class USBUartTypeCdcAcm;
17class USBUartComponent;
18class USBUartChannel;
19
20static const char *const TAG = "usb_uart";
21
22static constexpr uint8_t USB_CDC_SUBCLASS_ACM = 0x02;
23static constexpr uint8_t USB_SUBCLASS_COMMON = 0x02;
24static constexpr uint8_t USB_SUBCLASS_NULL = 0x00;
25static constexpr uint8_t USB_PROTOCOL_NULL = 0x00;
26static constexpr uint8_t USB_DEVICE_PROTOCOL_IAD = 0x01;
27static constexpr uint8_t USB_VENDOR_IFC = usb_host::USB_TYPE_VENDOR | usb_host::USB_RECIP_INTERFACE;
28static constexpr uint8_t USB_VENDOR_DEV = usb_host::USB_TYPE_VENDOR | usb_host::USB_RECIP_DEVICE;
29
30struct CdcEps {
31 const usb_ep_desc_t *notify_ep;
32 const usb_ep_desc_t *in_ep;
33 const usb_ep_desc_t *out_ep;
36};
37
67
75
81
82static const char *const PARITY_NAMES[] = {"NONE", "ODD", "EVEN", "MARK", "SPACE"};
83static const char *const STOP_BITS_NAMES[] = {"1", "1.5", "2"};
84
86 public:
87 RingBuffer(uint16_t buffer_size) : buffer_size_(buffer_size), buffer_(new uint8_t[buffer_size]) {}
88 bool is_empty() const { return this->read_pos_ == this->insert_pos_; }
89 size_t get_available() const {
90 return (this->insert_pos_ + this->buffer_size_ - this->read_pos_) % this->buffer_size_;
91 };
92 size_t get_free_space() const { return this->buffer_size_ - 1 - this->get_available(); }
93 uint8_t peek() const { return this->buffer_[this->read_pos_]; }
94 void push(uint8_t item);
95 void push(const uint8_t *data, size_t len);
96 uint8_t pop();
97 size_t pop(uint8_t *data, size_t len);
98 void clear() { this->read_pos_ = this->insert_pos_ = 0; }
99
100 protected:
101 uint16_t insert_pos_ = 0;
102 uint16_t read_pos_ = 0;
103 uint16_t buffer_size_;
104 uint8_t *buffer_;
105};
106
107// Structure for queuing received USB data chunks
109 static constexpr size_t MAX_CHUNK_SIZE = 64; // USB packet size
111 uint8_t length; // Max 64 bytes, so uint8_t is sufficient
113
114 // Required for EventPool - no cleanup needed for POD types
115 void release() {}
116};
117
118// Structure for queuing outgoing USB data chunks (one per USB FS packet)
120 static constexpr size_t MAX_CHUNK_SIZE = 64; // USB FS MPS
122 uint8_t length;
123
124 // Required for EventPool - no cleanup needed for POD types
125 void release() {}
126};
127
128class USBUartChannel : public uart::UARTComponent, public Parented<USBUartComponent> {
129 friend class USBUartComponent;
130 friend class USBUartTypeCdcAcm;
131 friend class USBUartTypeCP210X;
132 friend class USBUartTypeCH34X;
133
134 public:
135 // Number of output chunk slots per channel, derived from buffer_size config.
136 // Computed as ceil(buffer_size / 64) + 1 in Python codegen; defaults to 5 (256 / 64 + 1).
137 static constexpr uint8_t USB_OUTPUT_CHUNK_COUNT = USB_UART_OUTPUT_CHUNK_COUNT;
138
139 USBUartChannel(uint8_t index, uint16_t buffer_size) : index_(index), input_buffer_(RingBuffer(buffer_size)) {}
140 void write_array(const uint8_t *data, size_t len) override;
141 bool peek_byte(uint8_t *data) override;
142 bool read_array(uint8_t *data, size_t len) override;
143 size_t available() override { return this->input_buffer_.get_available(); }
144 bool is_connected() override { return this->initialised_.load(); }
145 uart::UARTFlushResult flush() override;
146 void check_logger_conflict() override {}
147 void set_parity(UARTParityOptions parity) { this->parity_ = parity; }
148 void set_debug(bool debug) { this->debug_ = debug; }
149 void set_dummy_receiver(bool dummy_receiver) { this->dummy_receiver_ = dummy_receiver; }
150 void set_debug_prefix(const char *prefix) { this->debug_prefix_ = StringRef(prefix); }
151 void set_flush_timeout(uint32_t flush_timeout_ms) override { this->flush_timeout_ms_ = flush_timeout_ms; }
152
157 void set_rx_callback(std::function<void()> cb) { this->rx_callback_ = std::move(cb); }
158
159 protected:
160 // Larger structures first (8+ bytes)
163 // Pool sized to queue capacity (SIZE-1) because LockFreeQueue<T,N> is a ring
164 // buffer that holds N-1 elements. This guarantees allocate() returns nullptr
165 // before push() can fail, preventing a pool slot leak.
167 std::function<void()> rx_callback_{};
170 // 4-byte fields
173 // 1-byte fields (no padding between groups)
174 std::atomic<bool> input_started_{true};
175 std::atomic<bool> output_started_{true};
176 std::atomic<bool> initialised_{false};
177 const uint8_t index_;
178 bool debug_{};
180};
181
183 public:
184 USBUartComponent(uint16_t vid, uint16_t pid) : usb_host::USBClient(vid, pid) {}
185 void setup() override;
186 void loop() override;
187 void dump_config() override;
188 std::vector<USBUartChannel *> get_channels() { return this->channels_; }
189
190 void add_channel(USBUartChannel *channel) { this->channels_.push_back(channel); }
191
192 void start_input(USBUartChannel *channel);
193 void start_output(USBUartChannel *channel);
194
195 // Lock-free data transfer from USB task to main loop
196 static constexpr int USB_DATA_QUEUE_SIZE = 32;
198 // Pool sized to queue capacity (SIZE-1) — see USBUartChannel::output_pool_ comment.
200
201 protected:
202 std::vector<USBUartChannel *> channels_{};
203};
204
206 public:
207 USBUartTypeCdcAcm(uint16_t vid, uint16_t pid) : USBUartComponent(vid, pid) {}
208
209 protected:
210 virtual std::vector<CdcEps> parse_descriptors(usb_device_handle_t dev_hdl);
211 void on_connected() override;
212 void on_disconnected() override;
213 virtual void enable_channels();
217 void start_channels();
218};
219
221 public:
222 USBUartTypeCP210X(uint16_t vid, uint16_t pid) : USBUartTypeCdcAcm(vid, pid) {}
223
224 protected:
225 std::vector<CdcEps> parse_descriptors(usb_device_handle_t dev_hdl) override;
226 void enable_channels() override;
227};
229 public:
230 USBUartTypeCH34X(uint16_t vid, uint16_t pid) : USBUartTypeCdcAcm(vid, pid) {}
231 void dump_config() override;
232
233 protected:
234 void enable_channels() override;
235 std::vector<CdcEps> parse_descriptors(usb_device_handle_t dev_hdl) override;
236
237 private:
238 void apply_line_settings_();
239 CH34xChipType chiptype_{CHIP_UNKNOWN};
240 const char *chip_name_{"unknown"};
241 uint8_t num_ports_{1};
242};
243
244} // namespace esphome::usb_uart
245
246#endif // USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3
Helper class to easily give an object a parent of type T.
Definition helpers.h:1998
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
USBClient(uint16_t vid, uint16_t pid)
Definition usb_host.h:129
void push(uint8_t item)
Definition usb_uart.cpp:108
RingBuffer(uint16_t buffer_size)
Definition usb_uart.h:87
size_t get_free_space() const
Definition usb_uart.h:92
size_t get_available() const
Definition usb_uart.h:89
void set_dummy_receiver(bool dummy_receiver)
Definition usb_uart.h:149
EventPool< UsbOutputChunk, USB_OUTPUT_CHUNK_COUNT - 1 > output_pool_
Definition usb_uart.h:166
std::atomic< bool > input_started_
Definition usb_uart.h:174
std::atomic< bool > initialised_
Definition usb_uart.h:176
LockFreeQueue< UsbOutputChunk, USB_OUTPUT_CHUNK_COUNT > output_queue_
Definition usb_uart.h:162
bool peek_byte(uint8_t *data) override
Definition usb_uart.cpp:188
void set_flush_timeout(uint32_t flush_timeout_ms) override
Definition usb_uart.h:151
std::function< void()> rx_callback_
Definition usb_uart.h:167
void set_parity(UARTParityOptions parity)
Definition usb_uart.h:147
void write_array(const uint8_t *data, size_t len) override
Definition usb_uart.cpp:137
void check_logger_conflict() override
Definition usb_uart.h:146
void set_rx_callback(std::function< void()> cb)
Register a callback invoked immediately after data is pushed to the input ring buffer.
Definition usb_uart.h:157
uart::UARTFlushResult flush() override
Definition usb_uart.cpp:172
static constexpr uint8_t USB_OUTPUT_CHUNK_COUNT
Definition usb_uart.h:137
bool read_array(uint8_t *data, size_t len) override
Definition usb_uart.cpp:195
void set_debug_prefix(const char *prefix)
Definition usb_uart.h:150
USBUartChannel(uint8_t index, uint16_t buffer_size)
Definition usb_uart.h:139
std::atomic< bool > output_started_
Definition usb_uart.h:175
void add_channel(USBUartChannel *channel)
Definition usb_uart.h:190
USBUartComponent(uint16_t vid, uint16_t pid)
Definition usb_uart.h:184
std::vector< USBUartChannel * > channels_
Definition usb_uart.h:202
LockFreeQueue< UsbDataChunk, USB_DATA_QUEUE_SIZE > usb_data_queue_
Definition usb_uart.h:197
void start_output(USBUartChannel *channel)
Definition usb_uart.cpp:343
void start_input(USBUartChannel *channel)
Definition usb_uart.cpp:274
std::vector< USBUartChannel * > get_channels()
Definition usb_uart.h:188
static constexpr int USB_DATA_QUEUE_SIZE
Definition usb_uart.h:196
EventPool< UsbDataChunk, USB_DATA_QUEUE_SIZE - 1 > chunk_pool_
Definition usb_uart.h:199
std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl) override
Definition ch34x.cpp:163
USBUartTypeCH34X(uint16_t vid, uint16_t pid)
Definition usb_uart.h:230
USBUartTypeCP210X(uint16_t vid, uint16_t pid)
Definition usb_uart.h:222
std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl) override
Definition cp210x.cpp:45
void start_channels()
Resets per-channel transfer flags and posts the first bulk IN transfer.
Definition usb_uart.cpp:534
USBUartTypeCdcAcm(uint16_t vid, uint16_t pid)
Definition usb_uart.h:207
virtual std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl)
Definition usb_uart.cpp:62
const char *const TAG
Definition spi.cpp:7
UARTFlushResult
Result of a flush() call.
@ UART_CONFIG_STOP_BITS_1_5
Definition usb_uart.h:78
std::string size_t len
Definition helpers.h:1045
static void uint32_t
const usb_ep_desc_t * out_ep
Definition usb_uart.h:33
const usb_ep_desc_t * notify_ep
Definition usb_uart.h:31
const usb_ep_desc_t * in_ep
Definition usb_uart.h:32
uint8_t interrupt_interface_number
Definition usb_uart.h:35
uint8_t data[MAX_CHUNK_SIZE]
Definition usb_uart.h:110
static constexpr size_t MAX_CHUNK_SIZE
Definition usb_uart.h:109
uint8_t data[MAX_CHUNK_SIZE]
Definition usb_uart.h:121
static constexpr size_t MAX_CHUNK_SIZE
Definition usb_uart.h:120