TinyWifiDongle 0.1.0
Header-only USB WiFi dongle for Arduino
Loading...
Searching...
No Matches
Rp2040UsbNcm.h
Go to the documentation of this file.
1#pragma once
2// USB CDC-NCM device for the Raspberry Pi Pico W / Pico 2 W (arduino-pico core,
3// USB stack "Pico SDK", which is the default).
4//
5// The core's NCM driver is used at frame level. Frames are exchanged through
6// two queues and two pools of frame buffers (one per direction, so a burst
7// towards the host cannot starve the acknowledgements coming from it); a
8// worker in the core's lwIP/CYW43 async context moves them in and out of the
9// USB stack under the USB mutex.
10#include <Arduino.h>
11#include <LwipEthernet.h> // __getEthernetContext()
12#include <USB.h>
13#include <pico/async_context.h>
14#include <pico/mutex.h>
15#include <pico/util/queue.h>
16#include <tusb-ncm.h> // empty header: makes the build include the core's NCM class driver
17#include <tusb.h>
18
20
21#if !CFG_TUD_NCM
22#error "TinyWifiDongle: the USB stack of this core has no NCM class (CFG_TUD_NCM). Use USB Stack: Pico SDK."
23#endif
24
25extern "C" {
26extern uint8_t tud_network_mac_address[6];
27}
28
29namespace twd {
30
45class Rp2040UsbNcm : public UsbTransport {
46 public:
48 struct Stats {
49 uint32_t rxFrames;
50 uint32_t txFrames;
51 uint32_t txDrops;
52 uint32_t rxDrops;
53 };
54
55 bool begin(const char* productName) override {
56 instance() = this;
57 product_ = productName;
58 if (!toHost_) toHost_ = kDefaultToHost;
59 if (!fromHost_) fromHost_ = kDefaultFromHost;
60 txPool_ = (Frame*)calloc(toHost_, sizeof(Frame));
61 rxPool_ = (Frame*)calloc(fromHost_, sizeof(Frame));
62 if (!txPool_ || !rxPool_) {
63 TWD_LOGGER.error("USB: not enough memory for %d + %d frame buffers", toHost_, fromHost_);
64 free(txPool_);
65 free(rxPool_);
66 txPool_ = rxPool_ = nullptr;
67 return false;
68 }
69 queue_init(&txFreeQ_, sizeof(Frame*), toHost_);
70 queue_init(&txQ_, sizeof(Frame*), toHost_);
71 queue_init(&rxFreeQ_, sizeof(Frame*), fromHost_);
72 queue_init(&rxQ_, sizeof(Frame*), fromHost_);
73 for (int i = 0; i < toHost_; i++) {
74 Frame* f = &txPool_[i];
75 f->rx = false;
76 queue_try_add(&txFreeQ_, &f);
77 }
78 for (int i = 0; i < fromHost_; i++) {
79 Frame* f = &rxPool_[i];
80 f->rx = true;
81 queue_try_add(&rxFreeQ_, &f);
82 }
83 worker_.user_data = this;
84 worker_.do_work = &Rp2040UsbNcm::work;
85 if (!async_context_add_when_pending_worker(__getEthernetContext(), &worker_)) {
86 TWD_LOGGER.error("USB: could not add the worker to the async context");
87 return false;
88 }
89
90 memcpy(tud_network_mac_address, hostMac_, 6);
91 snprintf(macStr_, sizeof(macStr_), "%02X%02X%02X%02X%02X%02X", hostMac_[0], hostMac_[1], hostMac_[2], hostMac_[3],
92 hostMac_[4], hostMac_[5]);
93
94 USB.disconnect();
95 epIn_ = USB.registerEndpointIn();
96 epOut_ = USB.registerEndpointOut();
97 epNotif_ = USB.registerEndpointIn();
98 strDesc_ = USB.registerString(product_.c_str());
99 strMac_ = USB.registerString(macStr_);
100 if (!epIn_ || !epOut_ || !epNotif_) {
101 TWD_LOGGER.error("USB: no free endpoints for the network interface");
102 USB.connect();
103 return false;
104 }
105 id_ = USB.registerInterface(2, &Rp2040UsbNcm::interfaceCb, this, TUD_CDC_NCM_DESC_LEN, 3, 0);
106 USB.connect();
107 return true;
108 }
109
110 bool ready() override { return tud_ready(); }
111
112 void setReceiver(FrameReceiver* receiver) override { receiver_ = receiver; }
113
114 void setHostMac(const uint8_t mac[6]) override { memcpy(hostMac_, mac, 6); }
115
118 void setBuffers(uint8_t toHost, uint8_t fromHost) {
119 toHost_ = toHost;
120 fromHost_ = fromHost;
121 }
122
124 bool send(const uint8_t* frame, uint16_t len) override {
125 if (!tud_ready() || len == 0 || len > kMaxFrame) return false; // nobody listening
126 Frame* f = allocToHost();
127 if (!f) {
128 stats_.txDrops++;
129 return false;
130 }
131 f->len = len;
132 memcpy(f->data, frame, len);
133 if (!queue_try_add(&txQ_, &f)) {
134 release(f);
135 stats_.txDrops++;
136 return false;
137 }
138 schedule();
139 return true;
140 }
141
143 Stats stats() const { return stats_; }
144
146 uint32_t txQueued() { return queue_get_level(&txQ_); }
147
148 // ---- called by the TinyUSB glue at the bottom of this file -------------------
150 static Rp2040UsbNcm* instance_() { return instance(); }
151
153 static uint16_t copyFrame(uint8_t* dst, void* ref) {
154 Frame* f = (Frame*)ref;
155 memcpy(dst, f->data, f->len);
156 return f->len;
157 }
158
160 bool onNcmReceive(const uint8_t* src, uint16_t size) {
161 Frame* f = allocFromHost();
162 if (!f || size > kMaxFrame) {
163 if (f) release(f);
164 stats_.rxDrops++;
165 schedule();
166 return false; // TinyUSB keeps the packet until the next recv_renew()
167 }
168 f->len = size;
169 memcpy(f->data, src, size);
170 if (!queue_try_add(&rxQ_, &f)) {
171 release(f);
172 stats_.rxDrops++;
173 schedule();
174 return false;
175 }
176 stats_.rxFrames++;
177 gotRx_ = true;
178 schedule();
179 return true;
180 }
181
182 private:
183 static constexpr uint16_t kNotifEndpointSize = 64; // size of the interrupt endpoint of the NCM class
184#if defined(PICO_RP2350)
185 static constexpr int kDefaultToHost = 48; // RP2350: 520 KB of RAM
186 static constexpr int kDefaultFromHost = 16;
187#else
188 static constexpr int kDefaultToHost = 24; // RP2040: 264 KB of RAM
189 static constexpr int kDefaultFromHost = 8;
190#endif
191 static constexpr uint16_t kMaxFrame = 1536;
192 struct Frame {
193 uint16_t len;
194 bool rx; // belongs to the pool of frames from the host
195 uint8_t data[kMaxFrame];
196 };
197
198 String product_;
199 FrameReceiver* receiver_ = nullptr;
200 uint8_t hostMac_[6] = {};
201 char macStr_[13] = {};
202 uint8_t epIn_ = 0, epOut_ = 0, epNotif_ = 0, strDesc_ = 0, strMac_ = 0, id_ = 0;
203 Frame* txPool_ = nullptr;
204 Frame* rxPool_ = nullptr;
205 int toHost_ = 0, fromHost_ = 0; // buffers per direction
206 queue_t txFreeQ_, rxFreeQ_, rxQ_, txQ_;
207 async_when_pending_worker_t worker_ = {};
208 volatile bool gotRx_ = false;
209 Stats stats_ = {};
210
211 static Rp2040UsbNcm*& instance() {
212 static Rp2040UsbNcm* p = nullptr;
213 return p;
214 }
215
216 Frame* allocToHost() {
217 Frame* f = nullptr;
218 return queue_try_remove(&txFreeQ_, &f) ? f : nullptr;
219 }
220 Frame* allocFromHost() {
221 Frame* f = nullptr;
222 return queue_try_remove(&rxFreeQ_, &f) ? f : nullptr;
223 }
224 void release(Frame* f) { queue_try_add(f->rx ? &rxFreeQ_ : &txFreeQ_, &f); }
225 void schedule() { async_context_set_work_pending(__getEthernetContext(), &worker_); }
226
227 static void interfaceCb(int itf, uint8_t* dst, int len, void* param) {
228 Rp2040UsbNcm* s = (Rp2040UsbNcm*)param;
229 uint8_t desc[TUD_CDC_NCM_DESC_LEN] = {
230 // interface number, description string, MAC string, notification endpoint and size,
231 // data endpoints (out, in) and size, largest Ethernet frame
232 TUD_CDC_NCM_DESCRIPTOR((uint8_t)itf, s->strDesc_, s->strMac_, s->epNotif_, kNotifEndpointSize, s->epOut_, s->epIn_,
233 CFG_TUD_NET_ENDPOINT_SIZE, CFG_TUD_NET_MTU)};
234 memcpy(dst, desc, len);
235 }
236
237 // Worker in the lwIP async context.
238 static void work(async_context_t*, async_when_pending_worker_t* w) { ((Rp2040UsbNcm*)w->user_data)->pump(w); }
239
240 void pump(async_when_pending_worker_t* w) {
241 // Host -> uplink: this context may call the WiFi chip.
242 Frame* f;
243 while (queue_try_remove(&rxQ_, &f)) {
244 if (receiver_) receiver_->onFrame(f->data, f->len);
245 release(f);
246 }
247
248 // The USB stack is shared with the rest of the core: take its mutex or try again later.
249 if (!mutex_try_enter(&USB.mutex, nullptr)) {
250 w->work_pending = true;
251 return;
252 }
253 while (queue_try_peek(&txQ_, &f)) {
254 if (!tud_ready()) { // host went away: drop what is queued
255 queue_try_remove(&txQ_, &f);
256 release(f);
257 stats_.txDrops++;
258 continue;
259 }
260 if (!tud_network_can_xmit(f->len)) break; // driver busy, try again below
261 tud_network_xmit(f, 0); // copies via tud_network_xmit_cb
262 queue_try_remove(&txQ_, &f);
263 release(f);
264 stats_.txFrames++;
265 }
266 // The driver hands over one datagram per renew.
267 int limit = 10;
268 do {
269 gotRx_ = false;
270 tud_network_recv_renew();
271 tud_task();
272 } while (gotRx_ && --limit > 0);
273 mutex_exit(&USB.mutex);
274
275 if (!queue_is_empty(&txQ_) || !queue_is_empty(&rxQ_)) w->work_pending = true;
276 }
277};
278
279} // namespace twd
280
281// ---- TinyUSB network class callbacks ---------------------------------------------
282extern "C" {
283uint8_t tud_network_mac_address[6] = {0};
284
286
287bool tud_network_recv_cb(const uint8_t* src, uint16_t size) {
289 return s ? s->onNcmReceive(src, size) : false;
290}
291
292uint16_t tud_network_xmit_cb(uint8_t* dst, void* ref, uint16_t arg) {
293 (void)arg;
294 return twd::Rp2040UsbNcm::copyFrame(dst, ref);
295}
296}
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
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)
uint8_t tud_network_mac_address[6]
Consumer of Ethernet frames.
Definition Interfaces.h:23
USB CDC-NCM network device for the Raspberry Pi Pico W / Pico 2 W.
uint32_t txQueued()
Number of frames waiting to be sent to the host.
void setBuffers(uint8_t toHost, uint8_t fromHost)
void setHostMac(const uint8_t mac[6]) override
static Rp2040UsbNcm * instance_()
The instance that receives the TinyUSB callbacks.
bool ready() override
The host has enumerated and configured the device.
Stats stats() const
Current counters.
bool begin(const char *productName) override
Registers the USB network interface (before the USB stack is started).
bool onNcmReceive(const uint8_t *src, uint16_t size)
A frame from the host. May run in interrupt context: copy and queue only.
static uint16_t copyFrame(uint8_t *dst, void *ref)
Copies the frame ref (as passed to tud_network_xmit()) to dst; returns its length.
bool send(const uint8_t *frame, uint16_t len) override
Queues the frame; never blocks. Returns false if it was dropped.
void setReceiver(FrameReceiver *receiver) override
Frames coming from the host are passed to receiver.
Moves Ethernet frames between the MCU and the USB host.
Definition Interfaces.h:37
Counters since start.
uint32_t rxFrames
frames received from the host
uint32_t txDrops
frames dropped on the way out (no buffer, host not ready)
uint32_t txFrames
frames handed to the USB stack
uint32_t rxDrops
frames from the host dropped (no buffer)