51 bool begin(
const char* productName)
override {
52 product_ = productName;
55 txQueue_ = xQueueCreate(kTxQueueLen,
sizeof(TxItem));
57 TWD_LOGGER.error(
"USB: not enough memory for the send queue");
60 esp_timer_create_args_t args = {};
62 args.callback = &Esp32UsbNcm::drainTimerCb;
64 if (esp_timer_create(&args, &drainTimer_) != ESP_OK) {
65 TWD_LOGGER.error(
"USB: could not create the send timer");
68 args.callback = &Esp32UsbNcm::reconnectTimerCb;
70 if (esp_timer_create(&args, &reconnectTimer_) != ESP_OK) {
71 TWD_LOGGER.error(
"USB: could not create the reconnect timer");
74 esp_err_t err = tinyusb_enable_interface(USB_INTERFACE_CUSTOM, TUD_CDC_NCM_DESC_LEN, &Esp32UsbNcm::descriptorCb);
76 TWD_LOGGER.error(
"USB: could not register the network interface (%s); was USB already started?",
77 esp_err_to_name(err));
83 bool ready()
override {
return tud_ready(); }
88 memcpy(hostMac_, mac, 6);
93 bool send(
const uint8_t* frame, uint16_t len)
override {
94 if (!tud_ready() || len == 0 || len > CFG_TUD_NET_MTU)
return false;
101 if ((kNtbHeader + ((len + 3u) & ~3u)) % 64 == 0) outLen = len + 4u;
102 uint8_t* copy = (uint8_t*)malloc(outLen);
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) {
127 const uint8_t*
hostMac()
const {
return hostMac_; }
137#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
138 volatile dwc2_regs_t* d =
reinterpret_cast<volatile dwc2_regs_t*
>(0x60080000);
139 unsigned n = epIn_ & 0x7F;
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);
147 TWD_LOGGER.warning(
"controller registers: not available on this chip");
152 uint32_t
txQueued()
const {
return txQueue_ ? uxQueueMessagesWaiting(txQueue_) : 0; }
161 if (receiver_) receiver_->onFrame(src, size);
167 if (renewActive_)
return;
169 usbd_defer_func(&Esp32UsbNcm::renewCb,
this,
false);
173 static constexpr int kTxQueueLen = 32;
174 static constexpr size_t kNtbHeader = 56;
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] = {};
187 uint32_t stallTimeoutMs_ = 1000;
188 uint16_t maxFrame_ = CFG_TUD_NET_MTU;
189 bool macFixed_ =
false;
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;
200 static Esp32UsbNcm*& instance() {
201 static Esp32UsbNcm* p =
nullptr;
208 esp_efuse_mac_get_default(base);
209 memcpy(hostMac_, base, 6);
210 hostMac_[0] = (hostMac_[0] | 0x02) & 0xFE;
213 snprintf(macStr_,
sizeof(macStr_),
"%02X%02X%02X%02X%02X%02X", hostMac_[0], hostMac_[1], hostMac_[2], hostMac_[3],
214 hostMac_[4], hostMac_[5]);
217 static uint16_t descriptorCb(uint8_t* dst, uint8_t* itf) {
218 Esp32UsbNcm* s = instance();
219 uint8_t itfnum = *itf;
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");
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));
238 void scheduleDrain() {
239 if (__atomic_exchange_n(&drainPending_,
true, __ATOMIC_ACQ_REL))
return;
240 usbd_defer_func(&Esp32UsbNcm::drainCb,
this,
false);
242 static void drainTimerCb(
void* arg) { ((Esp32UsbNcm*)arg)->scheduleDrain(); }
243 static void drainCb(
void* arg) { ((Esp32UsbNcm*)arg)->drain(); }
249 drainPending_ =
false;
251 uint32_t now = millis();
252 while (xQueuePeek(txQueue_, &item, 0) == pdTRUE) {
254 if (usbd_edpt_busy(0, epIn_) || !tud_network_can_xmit(item.len)) {
259 }
else if (stallTimeoutMs_ && now - stallSince_ > stallTimeoutMs_) {
263 esp_timer_start_once(drainTimer_, 300);
267 tud_network_xmit(item.data, item.len);
273 xQueueReceive(txQueue_, &item, 0);
283 TWD_LOGGER.
warning(
"USB: no send progress for %u ms, dropping %u queued frames and re-enumerating",
284 (
unsigned)stallTimeoutMs_, (
unsigned)uxQueueMessagesWaiting(txQueue_));
286 while (xQueueReceive(txQueue_, &it, 0) == pdTRUE) free(it.data);
289 esp_timer_start_once(reconnectTimer_, 800000);
291 static void reconnectTimerCb(
void* arg) { usbd_defer_func(&Esp32UsbNcm::connectCb, arg,
false); }
292 static void connectCb(
void*) { tud_connect(); }
294 static void renewCb(
void* arg) {
295 Esp32UsbNcm* s = (Esp32UsbNcm*)arg;
296 while (s->renewCount_) {
298 tud_network_recv_renew();
300 s->renewActive_ =
false;