ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
cp210x.cpp
Go to the documentation of this file.
1#if defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || \
2 defined(USE_ESP32_VARIANT_ESP32S31) || defined(USE_ESP32_VARIANT_ESP32H4)
3#include "usb_uart.h"
4#include "usb/usb_host.h"
6#include "esphome/core/log.h"
7
9
10#include <cinttypes>
11#include <iterator>
12
13namespace esphome::usb_uart {
14
15using namespace bytebuffer;
20static constexpr uint8_t IFC_ENABLE = 0x00; // Enable or disable the interface.
21static constexpr uint8_t SET_BAUDDIV = 0x01; // Set the baud rate divisor.
22static constexpr uint8_t GET_BAUDDIV = 0x02; // Get the baud rate divisor.
23static constexpr uint8_t SET_LINE_CTL = 0x03; // Set the line control.
24static constexpr uint8_t GET_LINE_CTL = 0x04; // Get the line control.
25static constexpr uint8_t SET_BREAK = 0x05; // Set a BREAK.
26static constexpr uint8_t IMM_CHAR = 0x06; // Send character out of order.
27static constexpr uint8_t SET_MHS = 0x07; // Set modem handshaking.
28static constexpr uint8_t GET_MDMSTS = 0x08; // Get modem status.
29static constexpr uint8_t SET_XON = 0x09; // Emulate XON.
30static constexpr uint8_t SET_XOFF = 0x0A; // Emulate XOFF.
31static constexpr uint8_t SET_EVENTMASK = 0x0B; // Set the event mask.
32static constexpr uint8_t GET_EVENTMASK = 0x0C; // Get the event mask.
33static constexpr uint8_t GET_EVENTSTATE = 0x16; // Get the event state.
34static constexpr uint8_t SET_RECEIVE = 0x17; // Set receiver max timeout.
35static constexpr uint8_t GET_RECEIVE = 0x18; // Get receiver max timeout.
36static constexpr uint8_t SET_CHAR = 0x0D; // Set special character individually.
37static constexpr uint8_t GET_CHARS = 0x0E; // Get special characters.
38static constexpr uint8_t GET_PROPS = 0x0F; // Get properties.
39static constexpr uint8_t GET_COMM_STATUS = 0x10; // Get the serial status.
40static constexpr uint8_t RESET = 0x11; // Reset.
41static constexpr uint8_t PURGE = 0x12; // Purge.
42static constexpr uint8_t SET_FLOW = 0x13; // Set flow control.
43static constexpr uint8_t GET_FLOW = 0x14; // Get flow control.
44static constexpr uint8_t EMBED_EVENTS = 0x15; // Control embedding of events in the data stream.
45static constexpr uint8_t GET_BAUDRATE = 0x1D; // Get the baud rate.
46static constexpr uint8_t SET_BAUDRATE = 0x1E; // Set the baud rate.
47static constexpr uint8_t SET_CHARS = 0x19; // Set special characters.
48static constexpr uint8_t VENDOR_SPECIFIC = 0xFF; // Vendor specific command.
49
50// VENDOR_SPECIFIC wValue reads
51static constexpr uint16_t GET_FW_VER_2N = 0x0010;
52static constexpr uint16_t GET_PARTNUM = 0x370B;
53
54static constexpr uint8_t PARTNUM_CP2102N_QFN28 = 0x20;
55static constexpr uint8_t PARTNUM_CP2102N_QFN24 = 0x21;
56static constexpr uint8_t PARTNUM_CP2102N_QFN20 = 0x22;
57
58// CP2102N firmware up to 1.0.4 reads xon_limit as flow_replace (erratum E104)
59static constexpr uint32_t CP2102N_LAST_FW_WITHOUT_FLOW_CONTROL = 0x010004;
60
61// SET_MHS value bits. The high byte selects which lines the low byte changes.
62static constexpr uint16_t CONTROL_DTR = 0x0001;
63static constexpr uint16_t CONTROL_RTS = 0x0002;
64static constexpr uint16_t CONTROL_WRITE_DTR = 0x0100;
65static constexpr uint16_t CONTROL_WRITE_RTS = 0x0200;
66
67// CP210xFlowBlock::control_handshake bits
68static constexpr uint32_t SERIAL_DTR_MASK = 0x03;
69static constexpr uint32_t SERIAL_DTR_INACTIVE = 0x00;
70static constexpr uint32_t SERIAL_DTR_ACTIVE = 0x01;
71static constexpr uint32_t SERIAL_CTS_HANDSHAKE = 1 << 3;
72static constexpr uint32_t SERIAL_DSR_HANDSHAKE = 1 << 4;
73static constexpr uint32_t SERIAL_DCD_HANDSHAKE = 1 << 5;
74static constexpr uint32_t SERIAL_DSR_SENSITIVITY = 1 << 6;
75
76// CP210xFlowBlock::flow_replace bits
77static constexpr uint32_t SERIAL_AUTO_TRANSMIT = 1 << 0;
78static constexpr uint32_t SERIAL_AUTO_RECEIVE = 1 << 1;
79static constexpr uint32_t SERIAL_RTS_MASK = 0xC0;
80static constexpr uint32_t SERIAL_RTS_INACTIVE = 0x00;
81static constexpr uint32_t SERIAL_RTS_ACTIVE = 0x40;
82static constexpr uint32_t SERIAL_RTS_FLOW_CTL = 0x80;
83
84// Receive queue levels at which the chip sends XON and XOFF
85static constexpr uint32_t XON_XOFF_LIMIT = 128;
86// SET_CHARS block: EOF, error, break, event, XON and XOFF characters. XON and XOFF are the
87// termios defaults DC1 and DC3.
88static constexpr uint8_t SPECIAL_CHARS[] = {0, 0, 0, 0, 0x11, 0x13};
89
90// Put DTR and RTS into the block. Under RTS/CTS an asserted RTS hands the line to the chip.
91static void set_block_modem_lines(CP210xFlowBlock &block, bool dtr, bool rts) {
92 block.control_handshake =
93 (block.control_handshake & ~SERIAL_DTR_MASK) | (dtr ? SERIAL_DTR_ACTIVE : SERIAL_DTR_INACTIVE);
94 uint32_t rts_bits = SERIAL_RTS_INACTIVE;
95 if (rts)
96 rts_bits = (block.control_handshake & SERIAL_CTS_HANDSHAKE) ? SERIAL_RTS_FLOW_CTL : SERIAL_RTS_ACTIVE;
97 block.flow_replace = (block.flow_replace & ~SERIAL_RTS_MASK) | rts_bits;
98}
99
100std::vector<CdcEps> USBUartTypeCP210X::parse_descriptors(usb_device_handle_t dev_hdl) {
101 const usb_config_desc_t *config_desc;
102 const usb_device_desc_t *device_desc;
103 int conf_offset = 0, ep_offset;
104 std::vector<CdcEps> cdc_devs{};
105
106 // Get required descriptors
107 if (usb_host_get_device_descriptor(dev_hdl, &device_desc) != ESP_OK) {
108 ESP_LOGE(TAG, "get_device_descriptor failed");
109 return {};
110 }
111 if (usb_host_get_active_config_descriptor(dev_hdl, &config_desc) != ESP_OK) {
112 ESP_LOGE(TAG, "get_active_config_descriptor failed");
113 return {};
114 }
115 ESP_LOGD(TAG, "bDeviceClass: %u, bDeviceSubClass: %u, bNumInterfaces: %u", device_desc->bDeviceClass,
116 device_desc->bDeviceSubClass, config_desc->bNumInterfaces);
117 if (device_desc->bDeviceClass != 0) {
118 ESP_LOGE(TAG, "bDeviceClass != 0");
119 return {};
120 }
121
122 for (uint8_t i = 0; i != config_desc->bNumInterfaces; i++) {
123 const auto *data_desc = usb_parse_interface_descriptor(config_desc, i, 0, &conf_offset);
124 if (!data_desc) {
125 ESP_LOGE(TAG, "data_desc: usb_parse_interface_descriptor failed");
126 break;
127 }
128 if (data_desc->bNumEndpoints != 2 || data_desc->bInterfaceClass != USB_CLASS_VENDOR_SPEC) {
129 ESP_LOGE(TAG, "data_desc: bInterfaceClass == %u, bInterfaceSubClass == %u, bNumEndpoints == %u",
130 data_desc->bInterfaceClass, data_desc->bInterfaceSubClass, data_desc->bNumEndpoints);
131 continue;
132 }
133 ep_offset = conf_offset;
134 const auto *out_ep = usb_parse_endpoint_descriptor_by_index(data_desc, 0, config_desc->wTotalLength, &ep_offset);
135 if (!out_ep) {
136 ESP_LOGE(TAG, "out_ep: usb_parse_endpoint_descriptor_by_index failed");
137 continue;
138 }
139 ep_offset = conf_offset;
140 const auto *in_ep = usb_parse_endpoint_descriptor_by_index(data_desc, 1, config_desc->wTotalLength, &ep_offset);
141 if (!in_ep) {
142 ESP_LOGE(TAG, "in_ep: usb_parse_endpoint_descriptor_by_index failed");
143 continue;
144 }
145 CdcEps eps = in_ep->bEndpointAddress & usb_host::USB_DIR_IN
146 ? CdcEps{nullptr, in_ep, out_ep, data_desc->bInterfaceNumber}
147 : CdcEps{nullptr, out_ep, in_ep, data_desc->bInterfaceNumber};
148 eps.bulk_interface_class = data_desc->bInterfaceClass;
149 cdc_devs.push_back(eps);
150 }
151 return cdc_devs;
152}
153
154bool USBUartTypeCP210X::config_device_step(uint8_t step, bool ok, const uint8_t *response) {
155 switch (step) {
156 case 0:
157 // A fresh device: the previous one's cached blocks must not steer modem_control_transfer()
158 this->no_flow_control_ = false;
159 this->flow_blocks_.fill({});
160 this->config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_IN, VENDOR_SPECIFIC, GET_PARTNUM, 0,
161 std::vector<uint8_t>(1), this->cfg_response_);
162 return true;
163 case 1:
164 if (!ok)
165 return false;
166 ESP_LOGD(TAG, "Part number 0x%02X", response[0]);
167 if (response[0] != PARTNUM_CP2102N_QFN28 && response[0] != PARTNUM_CP2102N_QFN24 &&
168 response[0] != PARTNUM_CP2102N_QFN20)
169 return false;
170 this->config_transfer_(USB_VENDOR_DEV | usb_host::USB_DIR_IN, VENDOR_SPECIFIC, GET_FW_VER_2N, 0,
171 std::vector<uint8_t>(3), this->cfg_response_);
172 return true;
173 case 2: {
174 if (!ok)
175 return false;
176 const uint32_t version = encode_uint24(response[0], response[1], response[2]);
177 ESP_LOGD(TAG, "CP2102N firmware %u.%u.%u", response[0], response[1], response[2]);
178 this->no_flow_control_ = version <= CP2102N_LAST_FW_WITHOUT_FLOW_CONTROL;
179 if (this->no_flow_control_) {
180 ESP_LOGW(TAG, "CP2102N firmware 1.0.4 and older cannot do flow control (erratum E104), using none");
181 }
182 return false;
183 }
184 default:
185 return false;
186 }
187}
188
189bool USBUartTypeCP210X::config_step(USBUartChannelBase *channel, uint8_t step, bool reload, bool ok,
190 const uint8_t *response) {
191 // On reload, skip the one-time IFC_ENABLE step (the interface is already enabled).
192 if (reload)
193 step++;
194 const bool xon_xoff = channel->flow_control_ == uart::UART_FLOW_CONTROL_XON_XOFF;
195 if (step >= 3) {
196 if (this->no_flow_control_) {
197 // Firmware with erratum E104 takes flow_replace from xon_limit, so a SET_FLOW can drop RTS.
198 // Skip the flow control steps; the lines then stay on SET_MHS as the cached block has no CTS.
199 step += 3;
200 } else if (!xon_xoff) {
201 // SET_CHARS is only needed for XON/XOFF
202 step++;
203 }
204 }
205 switch (step) {
206 case 0:
207 this->config_transfer_(USB_VENDOR_IFC | usb_host::USB_DIR_OUT, IFC_ENABLE, 1, channel->index_);
208 return true;
209 case 1: {
210 uint16_t line_control = static_cast<uint8_t>(channel->line_stop_bits_());
211 line_control |= static_cast<uint8_t>(channel->line_parity_()) << 4;
212 line_control |= channel->data_bits_ << 8;
213 ESP_LOGD(TAG, "Line control value 0x%X", line_control);
214 this->config_transfer_(USB_VENDOR_IFC | usb_host::USB_DIR_OUT, SET_LINE_CTL, line_control, channel->index_);
215 return true;
216 }
217 case 2: {
218 auto baud = ByteBuffer::wrap(channel->baud_rate_, LITTLE);
219 this->config_transfer_(USB_VENDOR_IFC | usb_host::USB_DIR_OUT, SET_BAUDRATE, 0, channel->index_, baud.get_data());
220 return true;
221 }
222 case 3:
223 this->config_transfer_(USB_VENDOR_IFC | usb_host::USB_DIR_OUT, SET_CHARS, 0, channel->index_,
224 std::vector<uint8_t>(std::begin(SPECIAL_CHARS), std::end(SPECIAL_CHARS)));
225 return true;
226 case 4: {
227 // Read into the channel's cached block, which the next step edits and writes back
228 this->config_transfer_(USB_VENDOR_IFC | usb_host::USB_DIR_IN, GET_FLOW, 0, channel->index_,
229 std::vector<uint8_t>(sizeof(CP210xFlowBlock)),
230 reinterpret_cast<uint8_t *>(&this->flow_blocks_[channel->index_]));
231 return true;
232 }
233 case 5: {
234 // Set flow control, re-applied on every settings change. The block also carries DTR and RTS,
235 // so this puts them on the wire too.
236 auto &block = this->flow_blocks_[channel->index_];
237 block.control_handshake &=
238 ~(SERIAL_DSR_HANDSHAKE | SERIAL_DCD_HANDSHAKE | SERIAL_DSR_SENSITIVITY | SERIAL_CTS_HANDSHAKE);
240 block.control_handshake |= SERIAL_CTS_HANDSHAKE;
241 assign_bits(block.flow_replace, SERIAL_AUTO_TRANSMIT | SERIAL_AUTO_RECEIVE, xon_xoff);
242 if (xon_xoff) {
243 block.xon_limit = XON_XOFF_LIMIT;
244 block.xoff_limit = XON_XOFF_LIMIT;
245 }
246 set_block_modem_lines(block, channel->dtr_, channel->rts_);
247 this->set_flow_transfer_(channel);
248 return true;
249 }
250 case 6:
251 // Raise the lines on open (init only)
252 if (reload)
253 return false;
254 this->modem_control_transfer(channel);
255 return true;
256 default:
257 return false;
258 }
259}
260
262 // Under RTS/CTS the chip drives RTS, so the lines go through SET_FLOW
263 auto &block = this->flow_blocks_[channel->index_];
264 if (block.control_handshake & SERIAL_CTS_HANDSHAKE) {
265 set_block_modem_lines(block, channel->dtr_, channel->rts_);
266 this->set_flow_transfer_(channel);
267 return;
268 }
269 const uint16_t value =
270 CONTROL_WRITE_DTR | CONTROL_WRITE_RTS | (channel->dtr_ ? CONTROL_DTR : 0) | (channel->rts_ ? CONTROL_RTS : 0);
271 ESP_LOGD(TAG, "SET_MHS: DTR=%s RTS=%s", ONOFF(channel->dtr_), ONOFF(channel->rts_));
272 this->config_transfer_(USB_VENDOR_IFC | usb_host::USB_DIR_OUT, SET_MHS, value, channel->index_);
273}
274
276 const auto &block = this->flow_blocks_[channel->index_];
277 ESP_LOGD(TAG, "SET_FLOW: control handshake 0x%02" PRIX32 ", flow replace 0x%02" PRIX32, block.control_handshake,
278 block.flow_replace);
279 const auto *bytes = reinterpret_cast<const uint8_t *>(&block);
280 this->config_transfer_(USB_VENDOR_IFC | usb_host::USB_DIR_OUT, SET_FLOW, 0, channel->index_,
281 std::vector<uint8_t>(bytes, bytes + sizeof(block)));
282}
283} // namespace esphome::usb_uart
284
285#endif // USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S2 || USE_ESP32_VARIANT_ESP32S3 ||
286 // USE_ESP32_VARIANT_ESP32S31 || USE_ESP32_VARIANT_ESP32H4
static ByteBuffer wrap(T value, Endian endianness=LITTLE)
Definition bytebuffer.h:155
LineStopBits line_stop_bits_() const
Definition usb_uart.cpp:709
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)
Definition usb_uart.cpp:569
void modem_control_transfer(USBUartChannelBase *channel) override
Definition cp210x.cpp:261
bool config_device_step(uint8_t step, bool ok, const uint8_t *response) override
Definition cp210x.cpp:154
void set_flow_transfer_(USBUartChannelBase *channel)
Definition cp210x.cpp:275
std::vector< CdcEps > parse_descriptors(usb_device_handle_t dev_hdl) override
Definition cp210x.cpp:100
bool config_step(USBUartChannelBase *channel, uint8_t step, bool reload, bool ok, const uint8_t *response) override
Definition cp210x.cpp:189
std::array< CP210xFlowBlock, MAX_CHANNELS > flow_blocks_
Definition usb_uart.h:356
uint32_t value
Definition hal.cpp:41
ESPHOME_ALWAYS_INLINE constexpr void assign_bits(T &value, std::type_identity_t< T > mask, bool on)
Set the bits of mask in value when on is true, clear them otherwise.
Definition helpers.h:1150
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:1047
static void uint32_t