ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
ft23xx.cpp
Go to the documentation of this file.
1#if defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32P4) || \
2 defined(USE_ESP32_VARIANT_ESP32S31) || defined(USE_ESP32_VARIANT_ESP32H4)
3#include "usb_uart.h"
4#include "usb/usb_host.h"
5#include "esphome/core/log.h"
8
10#include <cinttypes>
11
12namespace esphome::usb_uart {
13
14using namespace bytebuffer;
15
16// FTDI chip family identifiers. These map to USB device bcdDevice values
17// and determine how baudrate divisors and clock sources are calculated.
28
29static int ftdi_to_clkbits_am(int baudrate, uint32_t *encoded_divisor) {
30 static const char FRAC_CODE[8] = {0, 3, 2, 4, 1, 5, 6, 7};
31 static const char AM_ADJUST_UP[8] = {0, 0, 0, 1, 0, 3, 2, 1};
32 static const char AM_ADJUST_DN[8] = {0, 0, 0, 1, 0, 1, 2, 3};
33 int divisor, best_divisor, best_baud, best_baud_diff;
34 int i;
35 divisor = 24000000 / baudrate;
36
37 divisor -= AM_ADJUST_DN[divisor & 7];
38
39 best_divisor = 0;
40 best_baud = 0;
41 best_baud_diff = 0;
42 for (i = 0; i < 2; i++) {
43 int try_divisor = divisor + i;
44 int baud_estimate;
45 int baud_diff;
46
47 if (try_divisor <= 8) {
48 try_divisor = 8;
49 } else if (divisor < 16) {
50 try_divisor = 16;
51 } else {
52 try_divisor += AM_ADJUST_UP[try_divisor & 7];
53 if (try_divisor > 0x1FFF8) {
54 // Round down to maximum supported divisor value (for AM)
55 try_divisor = 0x1FFF8;
56 }
57 }
58 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
59 if (baud_estimate < baudrate) {
60 baud_diff = baudrate - baud_estimate;
61 } else {
62 baud_diff = baud_estimate - baudrate;
63 }
64 if (i == 0 || baud_diff < best_baud_diff) {
65 best_divisor = try_divisor;
66 best_baud = baud_estimate;
67 best_baud_diff = baud_diff;
68 if (baud_diff == 0) {
69 break;
70 }
71 }
72 }
73 *encoded_divisor = (best_divisor >> 3) | (FRAC_CODE[best_divisor & 7] << 14);
74 if (*encoded_divisor == 1) {
75 *encoded_divisor = 0; // 3000000 baud
76 } else if (*encoded_divisor == 0x4001) {
77 *encoded_divisor = 1; // 2000000 baud (BM only)
78 }
79 return best_baud;
80}
81
82static int ftdi_to_clkbits(int baudrate, unsigned int clk, int clk_div, uint32_t *encoded_divisor) {
83 static const char FRAC_CODE[8] = {0, 3, 2, 4, 1, 5, 6, 7};
84 int best_baud = 0;
85 int divisor, best_divisor;
86 if (baudrate >= clk / clk_div) {
87 *encoded_divisor = 0;
88 best_baud = clk / clk_div;
89 } else if (baudrate >= clk / (clk_div + clk_div / 2)) {
90 *encoded_divisor = 1;
91 best_baud = clk / (clk_div + clk_div / 2);
92 } else if (baudrate >= clk / (2 * clk_div)) {
93 *encoded_divisor = 2;
94 best_baud = clk / (2 * clk_div);
95 } else {
96 divisor = clk * 16 / clk_div / baudrate;
97 if (divisor & 1) {
98 best_divisor = divisor / 2 + 1;
99 } else {
100 best_divisor = divisor / 2;
101 }
102 if (best_divisor > 0x20000)
103 best_divisor = 0x1ffff;
104 best_baud = clk * 16 / clk_div / best_divisor;
105 if (best_baud & 1) {
106 best_baud = best_baud / 2 + 1;
107 } else {
108 best_baud = best_baud / 2;
109 }
110 *encoded_divisor = (best_divisor >> 3) | (FRAC_CODE[best_divisor & 0x7] << 14);
111 }
112 return best_baud;
113}
114
115struct FtdiConfig {
116 uint16_t value;
117 uint16_t ftdi_index;
118 int best_baud;
119};
120
121static FtdiConfig ftdi_convert_baudrate(int baudrate, uint8_t chip_type, uint8_t channel_index) {
122 uint32_t encoded_divisor;
123
124 FtdiConfig config{};
125
126 if (baudrate <= 0) {
127 return config;
128 }
129
130 static constexpr uint32_t H_CLK = 120000000;
131 static constexpr uint32_t C_CLK = 48000000;
132 if ((chip_type == TYPE_2232H) || (chip_type == TYPE_4232H) || (chip_type == TYPE_232H)) {
133 if (baudrate * 10 > H_CLK / 0x3fff) {
134 config.best_baud = ftdi_to_clkbits(baudrate, H_CLK, 10, &encoded_divisor);
135 encoded_divisor |= 0x20000; /* switch on CLK/10*/
136 } else {
137 config.best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
138 }
139 } else if ((chip_type == TYPE_BM) || (chip_type == TYPE_2232C) || (chip_type == TYPE_R) || (chip_type == TYPE_230X)) {
140 config.best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
141 } else {
142 config.best_baud = ftdi_to_clkbits_am(baudrate, &encoded_divisor);
143 }
144
145 config.value = (uint16_t) (encoded_divisor & 0xFFFF);
146 if (chip_type == TYPE_2232H || chip_type == TYPE_4232H || chip_type == TYPE_232H) {
147 config.ftdi_index = (uint16_t) (encoded_divisor >> 8);
148 config.ftdi_index &= 0xFF00;
149 config.ftdi_index |= (channel_index + 1);
150 } else {
151 config.ftdi_index = (uint16_t) (encoded_divisor >> 16);
152 }
153
154 return config;
155}
156
157static optional<CdcEps> get_uart(const usb_config_desc_t *config_desc, uint8_t intf_idx) {
158 int conf_offset, ep_offset;
159 CdcEps eps{};
160
161 const auto *intf_desc = usb_parse_interface_descriptor(config_desc, intf_idx, 0, &conf_offset);
162 if (!intf_desc) {
163 ESP_LOGD(TAG, "usb_parse_interface_descriptor failed for intf_idx=%d (end of interfaces)", intf_idx);
164 return nullopt;
165 }
166 ESP_LOGD(TAG,
167 "intf_desc [idx=%d]: bInterfaceClass=%02X, bInterfaceSubClass=%02X, bInterfaceProtocol=%02X, "
168 "bNumEndpoints=%d, bInterfaceNumber=%d",
169 intf_idx, intf_desc->bInterfaceClass, intf_desc->bInterfaceSubClass, intf_desc->bInterfaceProtocol,
170 intf_desc->bNumEndpoints, intf_desc->bInterfaceNumber);
171
172 std::vector<const usb_ep_desc_t *> endpoints;
173 for (uint8_t i = 0; i != intf_desc->bNumEndpoints; i++) {
174 ep_offset = conf_offset;
175 const auto *ep = usb_parse_endpoint_descriptor_by_index(intf_desc, i, config_desc->wTotalLength, &ep_offset);
176 if (!ep) {
177 ESP_LOGE(TAG, "Ran out of endpoints at %d before finding all %d endpoints", i, intf_desc->bNumEndpoints);
178 return nullopt;
179 }
180 ESP_LOGD(TAG, "ep: bEndpointAddress=%02X, bmAttributes=%02X", ep->bEndpointAddress, ep->bmAttributes);
181
182 if (ep->bmAttributes != 0x2) {
183 ESP_LOGD(TAG, "Skipping non-bulk endpoint: %02X", ep->bEndpointAddress);
184 continue;
185 }
186 endpoints.push_back(ep);
187 }
188
189 const usb_ep_desc_t *ep1 = nullptr;
190 const usb_ep_desc_t *ep2 = nullptr;
191 for (const auto *ep : endpoints) {
192 if (ep1 == nullptr) {
193 ep1 = ep;
194 } else if (ep2 == nullptr) {
195 ep2 = ep;
196 break;
197 }
198 }
199
200 if (ep1 == nullptr || ep2 == nullptr) {
201 ESP_LOGD(TAG, "Interface %d has %zu endpoints (need 2 bulk endpoints)", intf_idx, endpoints.size());
202 return nullopt;
203 }
204
205 ESP_LOGD(TAG, "Interface %d: ep1=0x%02X, ep2=0x%02X", intf_idx, ep1->bEndpointAddress, ep2->bEndpointAddress);
206
207 if (ep1->bEndpointAddress & usb_host::USB_DIR_IN) {
208 eps.in_ep = ep1;
209 eps.out_ep = ep2;
210 ESP_LOGD(TAG, "ep1 is IN (RX): ep1=0x%02X (in_ep), ep2=0x%02X (out_ep)", ep1->bEndpointAddress,
211 ep2->bEndpointAddress);
212 } else {
213 eps.out_ep = ep1;
214 eps.in_ep = ep2;
215 ESP_LOGD(TAG, "ep1 is OUT (TX): ep1=0x%02X (out_ep), ep2=0x%02X (in_ep)", ep1->bEndpointAddress,
216 ep2->bEndpointAddress);
217 }
218
219 eps.bulk_interface_number = intf_desc->bInterfaceNumber;
220 return eps;
221}
222
223std::vector<CdcEps> USBUartTypeFT23XX::parse_descriptors(usb_device_handle_t dev_hdl) {
224 const usb_config_desc_t *config_desc;
225 const usb_device_desc_t *device_desc;
226 std::vector<CdcEps> cdc_devs{};
227 std::string type_string;
228
229 if (usb_host_get_device_descriptor(dev_hdl, &device_desc) != ESP_OK) {
230 ESP_LOGE(TAG, "get_device_descriptor failed");
231 return {};
232 }
233 if (usb_host_get_active_config_descriptor(dev_hdl, &config_desc) != ESP_OK) {
234 ESP_LOGE(TAG, "get_active_config_descriptor failed");
235 return {};
236 }
237 if (device_desc->bcdDevice == 0x400 || (device_desc->bcdDevice == 0x200 && device_desc->iSerialNumber == 0)) {
238 this->chip_type_ = TYPE_BM;
239 type_string = "BM type chip";
240 } else if (device_desc->bcdDevice == 0x200) {
241 this->chip_type_ = TYPE_AM;
242 type_string = "AM type chip";
243 } else if (device_desc->bcdDevice == 0x500) {
244 this->chip_type_ = TYPE_2232C;
245 type_string = "2232C chip";
246 } else if (device_desc->bcdDevice == 0x600) {
247 this->chip_type_ = TYPE_R;
248 type_string = "type R chip";
249 } else if (device_desc->bcdDevice == 0x700) {
250 this->chip_type_ = TYPE_2232H;
251 type_string = "2232H chip";
252 } else if (device_desc->bcdDevice == 0x800) {
253 this->chip_type_ = TYPE_4232H;
254 type_string = "4232H chip";
255 } else if (device_desc->bcdDevice == 0x900) {
256 this->chip_type_ = TYPE_232H;
257 type_string = "232H type chip";
258 } else if (device_desc->bcdDevice == 0x1000) {
259 this->chip_type_ = TYPE_230X;
260 type_string = "230x chip";
261 }
262
263 ESP_LOGD(TAG, "Found FTDI %s based device", type_string.c_str());
264 for (size_t intf_idx = 0; intf_idx < this->channels_.size(); intf_idx++) {
265 if (auto eps = get_uart(config_desc, static_cast<uint8_t>(intf_idx))) {
266 cdc_devs.push_back(*eps);
267 ESP_LOGD(TAG, "Found CDC interface at USB interface index %zu", intf_idx);
268 }
269 }
270 return cdc_devs;
271}
272
274 if (!channel->initialised_.load())
275 return;
276
277 // Use compare_exchange_strong to avoid a check-then-act race: start_input() is called
278 // from both the USB task (self-restart on success) and the main loop (backpressure
279 // restart), so a plain load()/store() pair can let both threads submit a transfer.
280 auto started = false;
281 if (!channel->input_started_.compare_exchange_strong(started, true))
282 return;
283
284 const auto *ep = channel->cdc_dev_.in_ep;
285
286 auto callback = [this, channel](const usb_host::TransferStatus &status) {
287 if (!status.success) {
288 ESP_LOGE(TAG, "RX Transfer failed, status=%s", esp_err_to_name(status.error_code));
289 channel->input_started_.store(false);
290 return;
291 }
292
293 // FTDI prepends a 2-byte modem/line status header to every bulk IN packet.
294 size_t uart_data_len = (status.data_len > 2) ? (status.data_len - 2) : 0;
295
296 if (uart_data_len > 0) {
297 ESP_LOGV(TAG, "RX callback: Received %zu bytes, channel=%d", uart_data_len, channel->index_);
298 if (!channel->dummy_receiver_) {
299 UsbDataChunk *chunk = this->chunk_pool_.allocate();
300 if (chunk == nullptr) {
301 this->usb_data_queue_.increment_dropped_count();
302 channel->input_started_.store(false);
303 // Queue is full — wake the main loop to drain it, then let read_array()
304 // retrigger start_input() rather than spinning here in the USB task.
307 return;
308 }
309 // Strip the 2-byte FTDI header before queuing.
310 memcpy(chunk->data, status.data + 2, uart_data_len);
311 chunk->length = static_cast<uint16_t>(uart_data_len);
312 chunk->channel = channel;
313 this->usb_data_queue_.push(chunk);
314#ifdef USE_UART_DEBUGGER
315 if (channel->debug_) {
317 std::vector<uint8_t>(status.data + 2, status.data + 2 + uart_data_len), ',',
318 channel->debug_prefix_);
319 }
320#endif
323 }
324 } else if (status.data_len >= 2) {
325 ESP_LOGVV(TAG, "RX: Status packet, modem=0x%02X line=0x%02X, ch=%d", status.data[0], status.data[1],
326 channel->index_);
327 }
328
329 channel->input_started_.store(false);
330 this->start_input(channel);
331 };
332
333 if (!this->transfer_in(ep->bEndpointAddress, callback, ep->wMaxPacketSize)) {
334 ESP_LOGE(TAG, "RX transfer submission failed for ep=0x%02X", ep->bEndpointAddress);
335 channel->input_started_.store(false);
336 }
337}
338
340 ESP_LOGW(TAG, "RX buffer overflow on channel %d, clearing to resync", channel->index_);
341 channel->input_buffer_.clear();
342}
343
344bool USBUartTypeFT23XX::config_step(USBUartChannel *channel, uint8_t step, bool reload, bool ok,
345 const uint8_t *response) {
346 // On reload (settings change on an open channel) skip the SIO reset; the FTDI set_termios
347 // path only re-applies baud + line properties and does not re-assert DTR/RTS.
348 if (reload)
349 step++;
350 switch (step) {
351 case 0: // SIO reset (init only)
352 this->config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_OUT, 0x00, 0x00,
353 channel->cdc_dev_.bulk_interface_number + 1);
354 return true;
355 case 1: { // set baudrate
356 auto config = ftdi_convert_baudrate(channel->baud_rate_, this->chip_type_, channel->index_);
357 uint16_t usb_index = (config.ftdi_index & 0xFF00) | (channel->cdc_dev_.bulk_interface_number + 1);
358 ESP_LOGD(TAG, "Baudrate: %u, value=0x%04X, ftdi_index=0x%04X", (unsigned) channel->baud_rate_, config.value,
359 config.ftdi_index);
360 this->config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_OUT, 0x03, config.value, usb_index);
361 return true;
362 }
363 case 2: { // set line properties (data bits / parity / stop bits)
364 uint16_t value = channel->data_bits_;
365 switch (channel->parity_) {
367 value |= (0x00 << 8);
368 break;
370 value |= (0x01 << 8);
371 break;
373 value |= (0x02 << 8);
374 break;
376 value |= (0x03 << 8);
377 break;
379 value |= (0x04 << 8);
380 break;
381 }
382 switch (channel->stop_bits_) {
383 default: // 1 bit
384 value |= (0x00 << 11);
385 break;
387 value |= (0x01 << 11);
388 break;
390 value |= (0x02 << 11);
391 break;
392 }
393 value |= (0x00 << 14);
394 this->config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_OUT, 0x04, value,
395 channel->cdc_dev_.bulk_interface_number + 1);
396 return true;
397 }
398 case 3: // set modem control DTR+RTS (init only)
399 if (reload)
400 return false;
401 this->config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_OUT, 0x01, 0x0000,
402 channel->cdc_dev_.bulk_interface_number + 1);
403 return true;
404 default:
405 return false;
406 }
407}
408
409} // namespace esphome::usb_uart
410#endif // USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3 || USE_ESP32_VARIANT_ESP32P4 ||
411 // USE_ESP32_VARIANT_ESP32S31 || USE_ESP32_VARIANT_ESP32H4
uint8_t status
Definition bl0942.h:8
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
static void log_hex(UARTDirection direction, std::vector< uint8_t > bytes, uint8_t separator, StringRef prefix=StringRef())
Log the bytes as hex values, separated by the provided separator character.
bool transfer_in(uint8_t ep_address, const transfer_cb_t &callback, uint16_t length)
Performs a transfer input operation.
std::atomic< bool > input_started_
Definition usb_uart.h:180
std::atomic< bool > initialised_
Definition usb_uart.h:182
void config_transfer_(uint8_t type, uint8_t request, uint16_t value, uint16_t index, const std::vector< uint8_t > &data={})
Definition usb_uart.cpp:565
std::vector< USBUartChannel * > channels_
Definition usb_uart.h:239
LockFreeQueue< UsbDataChunk, USB_DATA_QUEUE_SIZE > usb_data_queue_
Definition usb_uart.h:213
EventPool< UsbDataChunk, USB_DATA_QUEUE_SIZE - 1 > chunk_pool_
Definition usb_uart.h:215
bool config_step(USBUartChannel *channel, uint8_t step, bool reload, bool ok, const uint8_t *response) override
Definition ft23xx.cpp:344
void on_rx_overflow(USBUartChannel *channel) override
Definition ft23xx.cpp:339
std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl) override
Definition ft23xx.cpp:223
void start_input(USBUartChannel *channel) override
Definition ft23xx.cpp:273
@ UART_CONFIG_STOP_BITS_1_5
Definition usb_uart.h:80
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
const usb_ep_desc_t * in_ep
Definition usb_uart.h:34
uint8_t data[usb_host::USB_MAX_PACKET_SIZE]
Definition usb_uart.h:111