TinyWifiDongle 0.1.0
Header-only USB WiFi dongle for Arduino
Loading...
Searching...
No Matches
Esp32UsbNcm.h
Go to the documentation of this file.
1#pragma once
2// USB CDC-NCM device on the ESP32-S2/S3 (board setting: "USB Mode: USB-OTG (TinyUSB)").
3//
4// Threading: TinyUSB's NCM driver is not thread-safe, so every call into it
5// (tud_network_xmit / can_xmit / recv_renew) is made from the TinyUSB task.
6// Other tasks only enqueue frames and schedule work with usbd_defer_func().
7#include <Arduino.h>
8#include "esp_mac.h"
9#include "esp_timer.h"
10#include "esp32-hal-tinyusb.h"
11#include "tusb.h"
12#include "device/usbd_pvt.h" // usbd_defer_func, usbd_edpt_busy
13#include "portable/synopsys/dwc2/dwc2_type.h" // register layout of the USB controller
14
16
17#if !CFG_TUD_NCM
18#error "TinyWifiDongle: this core was built without TinyUSB NCM (CFG_TUD_NCM)."
19#endif
20
21namespace twd {
22
38class Esp32UsbNcm : public UsbTransport {
39 public:
43 struct Stats {
44 uint32_t rxFrames;
45 uint32_t txFrames;
46 uint32_t txDrops;
47 uint32_t txBusy;
48 uint32_t resets;
49 };
50
51 bool begin(const char* productName) override {
52 product_ = productName;
53 instance() = this;
54 deriveMacs();
55 txQueue_ = xQueueCreate(kTxQueueLen, sizeof(TxItem));
56 if (!txQueue_) {
57 TWD_LOGGER.error("USB: not enough memory for the send queue");
58 return false;
59 }
60 esp_timer_create_args_t args = {};
61 args.arg = this;
62 args.callback = &Esp32UsbNcm::drainTimerCb;
63 args.name = "ncmTx";
64 if (esp_timer_create(&args, &drainTimer_) != ESP_OK) {
65 TWD_LOGGER.error("USB: could not create the send timer");
66 return false;
67 }
68 args.callback = &Esp32UsbNcm::reconnectTimerCb;
69 args.name = "ncmUsb";
70 if (esp_timer_create(&args, &reconnectTimer_) != ESP_OK) {
71 TWD_LOGGER.error("USB: could not create the reconnect timer");
72 return false;
73 }
74 esp_err_t err = tinyusb_enable_interface(USB_INTERFACE_CUSTOM, TUD_CDC_NCM_DESC_LEN, &Esp32UsbNcm::descriptorCb);
75 if (err != ESP_OK) {
76 TWD_LOGGER.error("USB: could not register the network interface (%s); was USB already started?",
77 esp_err_to_name(err));
78 return false;
79 }
80 return true;
81 }
82
83 bool ready() override { return tud_ready(); }
84
85 void setReceiver(FrameReceiver* receiver) override { receiver_ = receiver; }
86
87 void setHostMac(const uint8_t mac[6]) override {
88 memcpy(hostMac_, mac, 6);
89 macFixed_ = true;
90 }
91
93 bool send(const uint8_t* frame, uint16_t len) override {
94 if (!tud_ready() || len == 0 || len > CFG_TUD_NET_MTU) return false; // nobody listening
95 // The NCM driver sends 56 bytes of NTB headers plus the frame rounded up
96 // to 4 bytes as one USB transfer. A transfer that is an exact multiple of
97 // the 64 byte packet size needs a terminating zero-length packet, which
98 // wedges the send path on this chip. Trailing zero bytes on an Ethernet
99 // frame are harmless, so such frames are padded.
100 size_t outLen = len;
101 if ((kNtbHeader + ((len + 3u) & ~3u)) % 64 == 0) outLen = len + 4u;
102 uint8_t* copy = (uint8_t*)malloc(outLen);
103 if (!copy) {
104 stats_.txDrops++;
105 return false;
106 }
107 memcpy(copy, frame, len);
108 memset(copy + len, 0, outLen - len);
109 TxItem item = {copy, (uint16_t)outLen};
110 if (xQueueSend(txQueue_, &item, 0) != pdTRUE) {
111 free(copy);
112 stats_.txDrops++; // congested: TCP will retransmit
113 return false;
114 }
115 scheduleDrain();
116 return true;
117 }
118
120 void setMaxFrame(uint16_t bytes) { maxFrame_ = bytes; }
121
124 void setStallTimeout(uint32_t ms) { stallTimeoutMs_ = ms; }
125
127 const uint8_t* hostMac() const { return hostMac_; }
128
130 Stats stats() const { return stats_; }
137#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
138 volatile dwc2_regs_t* d = reinterpret_cast<volatile dwc2_regs_t*>(0x60080000); // USB-OTG of the S2/S3
139 unsigned n = epIn_ & 0x7F;
140 // Two short lines: the log port drops what does not fit its buffer.
141 TWD_LOGGER.warning("dw%u ctl=%08x tsiz=%08x int=%08x txs=%x", n, (unsigned)d->epin[n].diepctl, (unsigned)d->epin[n].tsiz,
142 (unsigned)d->epin[n].diepint, (unsigned)d->epin[n].dtxfsts);
143 vTaskDelay(pdMS_TO_TICKS(100));
144 TWD_LOGGER.warning("dw em=%08x gi=%08x/%08x da=%08x/%08x", (unsigned)d->diepempmsk, (unsigned)d->gintsts,
145 (unsigned)d->gintmsk, (unsigned)d->daint, (unsigned)d->daintmsk);
146#else
147 TWD_LOGGER.warning("controller registers: not available on this chip");
148#endif
149 }
150
152 uint32_t txQueued() const { return txQueue_ ? uxQueueMessagesWaiting(txQueue_) : 0; }
153
154 // ---- called by the TinyUSB glue at the bottom of this file -------------------
156 static Esp32UsbNcm* instance_() { return instance(); }
157
159 void onNcmReceive(const uint8_t* src, uint16_t size) {
160 stats_.rxFrames++;
161 if (receiver_) receiver_->onFrame(src, size);
162 // The NCM driver hands over one datagram per tud_network_recv_renew(), and
163 // the call must happen after the receive callback returned. Count the
164 // accepted datagrams and work them off in one deferred call; renew itself
165 // may deliver further datagrams, which just raise the count again.
166 renewCount_++;
167 if (renewActive_) return;
168 renewActive_ = true;
169 usbd_defer_func(&Esp32UsbNcm::renewCb, this, false);
170 }
171
172 private:
173 static constexpr int kTxQueueLen = 32;
174 static constexpr size_t kNtbHeader = 56; // NTH + NDP headers of the driver's NTB
175 struct TxItem {
176 uint8_t* data;
177 uint16_t len;
178 };
179
180 String product_;
181 FrameReceiver* receiver_ = nullptr;
182 QueueHandle_t txQueue_ = nullptr;
183 esp_timer_handle_t drainTimer_ = nullptr;
184 esp_timer_handle_t reconnectTimer_ = nullptr;
185 uint8_t hostMac_[6] = {};
186 char macStr_[13] = {}; // hostMac_ as 12 hex chars (NCM string descriptor)
187 uint32_t stallTimeoutMs_ = 1000;
188 uint16_t maxFrame_ = CFG_TUD_NET_MTU; // wMaxSegmentSize announced to the host
189 bool macFixed_ = false; // set by setHostMac(): do not derive the MAC from the chip id
190 uint8_t epIn_ = 0; // bulk IN endpoint address of the data pipe
191 Stats stats_ = {};
192
193 // TinyUSB task only.
194 volatile bool drainPending_ = false;
195 volatile bool renewActive_ = false;
196 volatile uint32_t renewCount_ = 0;
197 bool stalled_ = false;
198 uint32_t stallSince_ = 0;
199
200 static Esp32UsbNcm*& instance() {
201 static Esp32UsbNcm* p = nullptr;
202 return p;
203 }
204
205 void deriveMacs() {
206 if (!macFixed_) {
207 uint8_t base[6];
208 esp_efuse_mac_get_default(base);
209 memcpy(hostMac_, base, 6);
210 hostMac_[0] = (hostMac_[0] | 0x02) & 0xFE; // locally administered, unicast
211 hostMac_[5] ^= 0x01;
212 }
213 snprintf(macStr_, sizeof(macStr_), "%02X%02X%02X%02X%02X%02X", hostMac_[0], hostMac_[1], hostMac_[2], hostMac_[3],
214 hostMac_[4], hostMac_[5]);
215 }
216
217 static uint16_t descriptorCb(uint8_t* dst, uint8_t* itf) {
218 Esp32UsbNcm* s = instance();
219 uint8_t itfnum = *itf;
220 *itf += 2; // control + data interface
221 uint8_t strDesc = tinyusb_add_string_descriptor(s->product_.c_str());
222 uint8_t strMac = tinyusb_add_string_descriptor(s->macStr_);
223 uint8_t epData = tinyusb_get_free_duplex_endpoint();
224 uint8_t epNotif = tinyusb_get_free_in_endpoint();
225 if (!strDesc || !strMac || !epData || !epNotif) {
226 TWD_LOGGER.error("USB: no free endpoints or string descriptors for the network interface");
227 return 0;
228 }
229 s->epIn_ = (uint8_t)(0x80 | epData);
230 const uint16_t bulk = TUD_OPT_HIGH_SPEED ? 512 : 64;
231 uint8_t desc[] = {TUD_CDC_NCM_DESCRIPTOR(itfnum, strDesc, strMac, (uint8_t)(0x80 | epNotif), 64, epData,
232 (uint8_t)(0x80 | epData), bulk, s->maxFrame_, 50, 0)};
233 memcpy(dst, desc, sizeof(desc));
234 return sizeof(desc);
235 }
236
237 // ---- transmit: queue -> NCM driver, in the TinyUSB task -------------------------
238 void scheduleDrain() {
239 if (__atomic_exchange_n(&drainPending_, true, __ATOMIC_ACQ_REL)) return;
240 usbd_defer_func(&Esp32UsbNcm::drainCb, this, false);
241 }
242 static void drainTimerCb(void* arg) { ((Esp32UsbNcm*)arg)->scheduleDrain(); }
243 static void drainCb(void* arg) { ((Esp32UsbNcm*)arg)->drain(); }
244
245 // One frame per USB transfer: the NCM driver would otherwise batch frames
246 // that arrive while a transfer is in flight, and the padding rule in send()
247 // only holds for a transfer carrying a single frame.
248 void drain() {
249 drainPending_ = false;
250 TxItem item;
251 uint32_t now = millis();
252 while (xQueuePeek(txQueue_, &item, 0) == pdTRUE) {
253 if (tud_ready()) {
254 if (usbd_edpt_busy(0, epIn_) || !tud_network_can_xmit(item.len)) {
255 stats_.txBusy++;
256 if (!stalled_) {
257 stalled_ = true;
258 stallSince_ = now;
259 } else if (stallTimeoutMs_ && now - stallSince_ > stallTimeoutMs_) {
260 recover();
261 return;
262 }
263 esp_timer_start_once(drainTimer_, 300); // transfer in flight: retry shortly (us)
264 return;
265 }
266 stalled_ = false;
267 tud_network_xmit(item.data, item.len); // copies via tud_network_xmit_cb
268 stats_.txFrames++;
269 } else {
270 stats_.txDrops++;
271 stalled_ = false;
272 }
273 xQueueReceive(txQueue_, &item, 0);
274 free(item.data);
275 }
276 stalled_ = false;
277 }
278
279 // Safety net: if the send path stops making progress, drop the queued frames
280 // and make the host enumerate the device again.
281 void recover() {
282 stats_.resets++;
283 TWD_LOGGER.warning("USB: no send progress for %u ms, dropping %u queued frames and re-enumerating",
284 (unsigned)stallTimeoutMs_, (unsigned)uxQueueMessagesWaiting(txQueue_));
285 TxItem it;
286 while (xQueueReceive(txQueue_, &it, 0) == pdTRUE) free(it.data);
287 stalled_ = false;
288 tud_disconnect();
289 esp_timer_start_once(reconnectTimer_, 800000);
290 }
291 static void reconnectTimerCb(void* arg) { usbd_defer_func(&Esp32UsbNcm::connectCb, arg, false); }
292 static void connectCb(void*) { tud_connect(); }
293
294 static void renewCb(void* arg) {
295 Esp32UsbNcm* s = (Esp32UsbNcm*)arg;
296 while (s->renewCount_) {
297 s->renewCount_--;
298 tud_network_recv_renew();
299 }
300 s->renewActive_ = false;
301 }
302};
303
304} // namespace twd
305
306// ---- TinyUSB network class callbacks (override the core's weak stubs) ---------
307extern "C" {
308bool tud_network_recv_cb(const uint8_t* src, uint16_t size) {
310 if (s) s->onNcmReceive(src, size);
311 return true;
312}
313uint16_t tud_network_xmit_cb(uint8_t* dst, void* ref, uint16_t arg) {
314 memcpy(dst, ref, arg);
315 return arg;
316}
318}
bool tud_network_recv_cb(const uint8_t *src, uint16_t size)
void tud_network_init_cb(void)
uint16_t tud_network_xmit_cb(uint8_t *dst, void *ref, uint16_t arg)
Portable abstractions the dongle is built from.
static twd::LoggerClass TWD_LOGGER
The logger used by all components; configure it in the sketch with TWD_LOGGER.begin(Serial).
Definition Logger.h:107
USB CDC-NCM network device for the ESP32-S2/S3 (TinyUSB).
Definition Esp32UsbNcm.h:38
bool ready() override
The host has enumerated and configured the device.
Definition Esp32UsbNcm.h:83
void logControllerState()
uint32_t txQueued() const
Number of frames waiting to be sent to the host.
Stats stats() const
Current counters.
void setHostMac(const uint8_t mac[6]) override
Definition Esp32UsbNcm.h:87
void setReceiver(FrameReceiver *receiver) override
Frames coming from the host are passed to receiver.
Definition Esp32UsbNcm.h:85
void onNcmReceive(const uint8_t *src, uint16_t size)
A frame from the host (TinyUSB task; must not block).
static Esp32UsbNcm * instance_()
The instance that receives the TinyUSB callbacks.
void setStallTimeout(uint32_t ms)
void setMaxFrame(uint16_t bytes)
Largest Ethernet frame announced to the host; call before begin().
bool send(const uint8_t *frame, uint16_t len) override
Runs in the caller's task: copy, enqueue, never block.
Definition Esp32UsbNcm.h:93
bool begin(const char *productName) override
Registers the USB network interface (before the USB stack is started).
Definition Esp32UsbNcm.h:51
const uint8_t * hostMac() const
MAC address of the adapter as the host sees it.
Consumer of Ethernet frames.
Definition Interfaces.h:23
void error(const char *fmt,...)
Definition Logger.h:75
void warning(const char *fmt,...)
Definition Logger.h:69
Moves Ethernet frames between the MCU and the USB host.
Definition Interfaces.h:37
Counters since start: frames received from and sent to the host, frames dropped on the way out,...
Definition Esp32UsbNcm.h:43
uint32_t resets
stall recoveries (USB re-enumerations)
Definition Esp32UsbNcm.h:48
uint32_t txFrames
frames handed to the USB driver
Definition Esp32UsbNcm.h:45
uint32_t txBusy
polls that found the driver busy
Definition Esp32UsbNcm.h:47
uint32_t txDrops
frames dropped on the way out
Definition Esp32UsbNcm.h:46
uint32_t rxFrames
frames received from the host
Definition Esp32UsbNcm.h:44