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)
4#include "usb/usb_host.h"
14using namespace bytebuffer;
16static constexpr uint8_t SIO_SET_MODEM_CTRL = 0x01;
17static constexpr uint8_t SIO_SET_FLOW_CTRL = 0x02;
19static constexpr uint16_t SIO_DISABLE_FLOW_CTRL = 0x0000;
20static constexpr uint16_t SIO_RTS_CTS_HS = 0x0100;
21static constexpr uint16_t SIO_XON_XOFF_HS = 0x0400;
23static constexpr uint16_t SIO_XON_XOFF_CHARS = 0x1311;
25static constexpr uint16_t SIO_SET_DTR_MASK = 0x0100;
26static constexpr uint16_t SIO_SET_RTS_MASK = 0x0200;
27static constexpr uint16_t SIO_DTR_HIGH = 0x0001;
28static constexpr uint16_t SIO_RTS_HIGH = 0x0002;
43static int ftdi_to_clkbits_am(
int baudrate,
uint32_t *encoded_divisor) {
44 static const char FRAC_CODE[8] = {0, 3, 2, 4, 1, 5, 6, 7};
45 static const char AM_ADJUST_UP[8] = {0, 0, 0, 1, 0, 3, 2, 1};
46 static const char AM_ADJUST_DN[8] = {0, 0, 0, 1, 0, 1, 2, 3};
47 int divisor, best_divisor, best_baud, best_baud_diff;
49 divisor = 24000000 / baudrate;
51 divisor -= AM_ADJUST_DN[divisor & 7];
56 for (i = 0; i < 2; i++) {
57 int try_divisor = divisor + i;
61 if (try_divisor <= 8) {
63 }
else if (divisor < 16) {
66 try_divisor += AM_ADJUST_UP[try_divisor & 7];
67 if (try_divisor > 0x1FFF8) {
69 try_divisor = 0x1FFF8;
72 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
73 if (baud_estimate < baudrate) {
74 baud_diff = baudrate - baud_estimate;
76 baud_diff = baud_estimate - baudrate;
78 if (i == 0 || baud_diff < best_baud_diff) {
79 best_divisor = try_divisor;
80 best_baud = baud_estimate;
81 best_baud_diff = baud_diff;
87 *encoded_divisor = (best_divisor >> 3) | (FRAC_CODE[best_divisor & 7] << 14);
88 if (*encoded_divisor == 1) {
90 }
else if (*encoded_divisor == 0x4001) {
96static int ftdi_to_clkbits(
int baudrate,
unsigned int clk,
int clk_div,
uint32_t *encoded_divisor) {
97 static const char FRAC_CODE[8] = {0, 3, 2, 4, 1, 5, 6, 7};
99 int divisor, best_divisor;
100 if (baudrate >= clk / clk_div) {
101 *encoded_divisor = 0;
102 best_baud = clk / clk_div;
103 }
else if (baudrate >= clk / (clk_div + clk_div / 2)) {
104 *encoded_divisor = 1;
105 best_baud = clk / (clk_div + clk_div / 2);
106 }
else if (baudrate >= clk / (2 * clk_div)) {
107 *encoded_divisor = 2;
108 best_baud = clk / (2 * clk_div);
110 divisor = clk * 16 / clk_div / baudrate;
112 best_divisor = divisor / 2 + 1;
114 best_divisor = divisor / 2;
116 if (best_divisor > 0x20000)
117 best_divisor = 0x1ffff;
118 best_baud = clk * 16 / clk_div / best_divisor;
120 best_baud = best_baud / 2 + 1;
122 best_baud = best_baud / 2;
124 *encoded_divisor = (best_divisor >> 3) | (FRAC_CODE[best_divisor & 0x7] << 14);
135static FtdiConfig ftdi_convert_baudrate(
int baudrate, uint8_t chip_type, uint8_t channel_index) {
144 static constexpr uint32_t H_CLK = 120000000;
145 static constexpr uint32_t C_CLK = 48000000;
147 if (baudrate * 10 > H_CLK / 0x3fff) {
148 config.best_baud = ftdi_to_clkbits(baudrate, H_CLK, 10, &encoded_divisor);
149 encoded_divisor |= 0x20000;
151 config.best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
154 config.best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
156 config.best_baud = ftdi_to_clkbits_am(baudrate, &encoded_divisor);
159 config.value = (uint16_t) (encoded_divisor & 0xFFFF);
161 config.ftdi_index = (uint16_t) (encoded_divisor >> 8);
162 config.ftdi_index &= 0xFF00;
163 config.ftdi_index |= (channel_index + 1);
165 config.ftdi_index = (uint16_t) (encoded_divisor >> 16);
171static optional<CdcEps> get_uart(
const usb_config_desc_t *config_desc, uint8_t intf_idx) {
172 int conf_offset, ep_offset;
175 const auto *intf_desc = usb_parse_interface_descriptor(config_desc, intf_idx, 0, &conf_offset);
177 ESP_LOGD(TAG,
"usb_parse_interface_descriptor failed for intf_idx=%d (end of interfaces)", intf_idx);
181 "intf_desc [idx=%d]: bInterfaceClass=%02X, bInterfaceSubClass=%02X, bInterfaceProtocol=%02X, "
182 "bNumEndpoints=%d, bInterfaceNumber=%d",
183 intf_idx, intf_desc->bInterfaceClass, intf_desc->bInterfaceSubClass, intf_desc->bInterfaceProtocol,
184 intf_desc->bNumEndpoints, intf_desc->bInterfaceNumber);
186 std::vector<const usb_ep_desc_t *> endpoints;
187 for (uint8_t i = 0; i != intf_desc->bNumEndpoints; i++) {
188 ep_offset = conf_offset;
189 const auto *ep = usb_parse_endpoint_descriptor_by_index(intf_desc, i, config_desc->wTotalLength, &ep_offset);
191 ESP_LOGE(TAG,
"Ran out of endpoints at %d before finding all %d endpoints", i, intf_desc->bNumEndpoints);
194 ESP_LOGD(TAG,
"ep: bEndpointAddress=%02X, bmAttributes=%02X", ep->bEndpointAddress, ep->bmAttributes);
196 if (ep->bmAttributes != 0x2) {
197 ESP_LOGD(TAG,
"Skipping non-bulk endpoint: %02X", ep->bEndpointAddress);
200 endpoints.push_back(ep);
203 const usb_ep_desc_t *ep1 =
nullptr;
204 const usb_ep_desc_t *ep2 =
nullptr;
205 for (
const auto *ep : endpoints) {
206 if (ep1 ==
nullptr) {
208 }
else if (ep2 ==
nullptr) {
214 if (ep1 ==
nullptr || ep2 ==
nullptr) {
215 ESP_LOGD(TAG,
"Interface %d has %zu endpoints (need 2 bulk endpoints)", intf_idx, endpoints.size());
219 ESP_LOGD(TAG,
"Interface %d: ep1=0x%02X, ep2=0x%02X", intf_idx, ep1->bEndpointAddress, ep2->bEndpointAddress);
221 if (ep1->bEndpointAddress & usb_host::USB_DIR_IN) {
224 ESP_LOGD(TAG,
"ep1 is IN (RX): ep1=0x%02X (in_ep), ep2=0x%02X (out_ep)", ep1->bEndpointAddress,
225 ep2->bEndpointAddress);
229 ESP_LOGD(TAG,
"ep1 is OUT (TX): ep1=0x%02X (out_ep), ep2=0x%02X (in_ep)", ep1->bEndpointAddress,
230 ep2->bEndpointAddress);
233 eps.bulk_interface_number = intf_desc->bInterfaceNumber;
234 eps.bulk_interface_class = intf_desc->bInterfaceClass;
239 const usb_config_desc_t *config_desc;
240 const usb_device_desc_t *device_desc;
241 std::vector<CdcEps> cdc_devs{};
242 std::string type_string;
244 if (usb_host_get_device_descriptor(dev_hdl, &device_desc) != ESP_OK) {
245 ESP_LOGE(TAG,
"get_device_descriptor failed");
248 if (usb_host_get_active_config_descriptor(dev_hdl, &config_desc) != ESP_OK) {
249 ESP_LOGE(TAG,
"get_active_config_descriptor failed");
252 if (device_desc->bcdDevice == 0x400 || (device_desc->bcdDevice == 0x200 && device_desc->iSerialNumber == 0)) {
254 type_string =
"BM type chip";
255 }
else if (device_desc->bcdDevice == 0x200) {
257 type_string =
"AM type chip";
258 }
else if (device_desc->bcdDevice == 0x500) {
260 type_string =
"2232C chip";
261 }
else if (device_desc->bcdDevice == 0x600) {
263 type_string =
"type R chip";
264 }
else if (device_desc->bcdDevice == 0x700) {
266 type_string =
"2232H chip";
267 }
else if (device_desc->bcdDevice == 0x800) {
269 type_string =
"4232H chip";
270 }
else if (device_desc->bcdDevice == 0x900) {
272 type_string =
"232H type chip";
273 }
else if (device_desc->bcdDevice == 0x1000) {
275 type_string =
"230x chip";
278 ESP_LOGD(TAG,
"Found FTDI %s based device", type_string.c_str());
279 for (
size_t intf_idx = 0; intf_idx < this->
channels_.size(); intf_idx++) {
280 if (
auto eps = get_uart(config_desc,
static_cast<uint8_t
>(intf_idx))) {
281 cdc_devs.push_back(*eps);
282 ESP_LOGD(TAG,
"Found CDC interface at USB interface index %zu", intf_idx);
295 auto started =
false;
296 if (!channel->
input_started_.compare_exchange_strong(started,
true))
303 ESP_LOGE(TAG,
"RX Transfer failed, status=%s", esp_err_to_name(
status.error_code));
309 size_t uart_data_len = (
status.data_len > 2) ? (
status.data_len - 2) : 0;
311 if (uart_data_len > 0) {
312 ESP_LOGV(TAG,
"RX callback: Received %zu bytes, channel=%d", uart_data_len, channel->
index_);
315 if (chunk ==
nullptr) {
325 memcpy(chunk->
data,
status.data + 2, uart_data_len);
326 chunk->
length =
static_cast<uint16_t
>(uart_data_len);
329#ifdef USE_UART_DEBUGGER
332 std::vector<uint8_t>(
status.data + 2,
status.data + 2 + uart_data_len),
',',
339 }
else if (
status.data_len >= 2) {
340 ESP_LOGVV(TAG,
"RX: Status packet, modem=0x%02X line=0x%02X, ch=%d",
status.data[0],
status.data[1],
348 if (!this->
transfer_in(ep->bEndpointAddress, callback, ep->wMaxPacketSize)) {
349 ESP_LOGE(TAG,
"RX transfer submission failed for ep=0x%02X", ep->bEndpointAddress);
355 ESP_LOGW(TAG,
"RX buffer overflow on channel %d, clearing to resync", channel->
index_);
360 const uint8_t *response) {
371 auto config = ftdi_convert_baudrate(channel->
baud_rate_, this->chip_type_, channel->
index_);
373 ESP_LOGD(TAG,
"Baudrate: %u, value=0x%04X, ftdi_index=0x%04X", (
unsigned) channel->
baud_rate_, config.value,
375 this->
config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_OUT, 0x03, config.value, usb_index);
380 value |=
static_cast<uint8_t
>(channel->
line_parity_()) << 8;
382 value |= (0x00 << 14);
388 uint16_t
mode = SIO_DISABLE_FLOW_CTRL;
391 mode = SIO_RTS_CTS_HS;
393 mode = SIO_XON_XOFF_HS;
394 value = SIO_XON_XOFF_CHARS;
396 ESP_LOGD(TAG,
"SIO_SET_FLOW_CTRL: mode=0x%04X",
mode);
397 this->
config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_OUT, SIO_SET_FLOW_CTRL, value,
412 const uint16_t value =
413 SIO_SET_DTR_MASK | SIO_SET_RTS_MASK | (channel->
dtr_ ? SIO_DTR_HIGH : 0) | (channel->
rts_ ? SIO_RTS_HIGH : 0);
414 ESP_LOGD(TAG,
"SIO_SET_MODEM_CTRL: DTR=%s RTS=%s", ONOFF(channel->
dtr_), ONOFF(channel->
rts_));
415 this->
config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_OUT, SIO_SET_MODEM_CTRL, value,
BedjetMode mode
BedJet operating mode.
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.
UARTFlowControl flow_control_
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.
LineParity line_parity_() const
std::atomic< bool > input_started_
std::atomic< bool > initialised_
LineStopBits line_stop_bits_() const
std::vector< USBUartChannelBase * > channels_
LockFreeQueue< UsbDataChunk, USB_DATA_QUEUE_SIZE > usb_data_queue_
void config_transfer_(uint8_t type, uint8_t request, uint16_t value, uint16_t index, const std::vector< uint8_t > &data={}, uint8_t *dest=nullptr)
EventPool< UsbDataChunk, USB_DATA_QUEUE_SIZE - 1 > chunk_pool_
void modem_control_transfer(USBUartChannelBase *channel) override
bool config_step(USBUartChannelBase *channel, uint8_t step, bool reload, bool ok, const uint8_t *response) override
void on_rx_overflow(USBUartChannelBase *channel) override
std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl) override
void start_input(USBUartChannelBase *channel) override
@ UART_FLOW_CONTROL_RTS_CTS
@ UART_FLOW_CONTROL_XON_XOFF
Application App
Global storage of Application pointer - only one Application can exist.
uint8_t bulk_interface_number
const usb_ep_desc_t * in_ep
uint8_t data[usb_host::USB_MAX_PACKET_SIZE]
USBUartChannelBase * channel