My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. /**
  2. * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. *
  18. * Contact information
  19. * -------------------
  20. *
  21. * Circuits At Home, LTD
  22. * Web : http://www.circuitsathome.com
  23. * e-mail : support@circuitsathome.com
  24. */
  25. /* USB functions */
  26. #include "../../../inc/MarlinConfigPre.h"
  27. #if ENABLED(USB_FLASH_DRIVE_SUPPORT) && DISABLED(USE_UHS3_USB)
  28. #include "Usb.h"
  29. static uint8_t usb_error = 0;
  30. static uint8_t usb_task_state;
  31. /* constructor */
  32. USB::USB() : bmHubPre(0) {
  33. usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; //set up state machine
  34. init();
  35. }
  36. /* Initialize data structures */
  37. void USB::init() {
  38. //devConfigIndex = 0;
  39. bmHubPre = 0;
  40. }
  41. uint8_t USB::getUsbTaskState() {
  42. return usb_task_state;
  43. }
  44. void USB::setUsbTaskState(uint8_t state) {
  45. usb_task_state = state;
  46. }
  47. EpInfo* USB::getEpInfoEntry(uint8_t addr, uint8_t ep) {
  48. UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
  49. if (!p || !p->epinfo)
  50. return nullptr;
  51. EpInfo *pep = p->epinfo;
  52. for (uint8_t i = 0; i < p->epcount; i++) {
  53. if ((pep)->epAddr == ep)
  54. return pep;
  55. pep++;
  56. }
  57. return nullptr;
  58. }
  59. /* set device table entry */
  60. /* each device is different and has different number of endpoints. This function plugs endpoint record structure, defined in application, to devtable */
  61. uint8_t USB::setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr) {
  62. if (!eprecord_ptr)
  63. return USB_ERROR_INVALID_ARGUMENT;
  64. UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
  65. if (!p)
  66. return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  67. p->address.devAddress = addr;
  68. p->epinfo = eprecord_ptr;
  69. p->epcount = epcount;
  70. return 0;
  71. }
  72. uint8_t USB::SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t *nak_limit) {
  73. UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
  74. if (!p)
  75. return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  76. if (!p->epinfo)
  77. return USB_ERROR_EPINFO_IS_NULL;
  78. *ppep = getEpInfoEntry(addr, ep);
  79. if (!*ppep)
  80. return USB_ERROR_EP_NOT_FOUND_IN_TBL;
  81. *nak_limit = (0x0001UL << (((*ppep)->bmNakPower > USB_NAK_MAX_POWER) ? USB_NAK_MAX_POWER : (*ppep)->bmNakPower));
  82. (*nak_limit)--;
  83. /*
  84. USBTRACE2("\r\nAddress: ", addr);
  85. USBTRACE2(" EP: ", ep);
  86. USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower);
  87. USBTRACE2(" NAK Limit: ", nak_limit);
  88. USBTRACE("\r\n");
  89. */
  90. regWr(rPERADDR, addr); //set peripheral address
  91. uint8_t mode = regRd(rMODE);
  92. //Serial.print("\r\nMode: ");
  93. //Serial.println( mode, HEX);
  94. //Serial.print("\r\nLS: ");
  95. //Serial.println(p->lowspeed, HEX);
  96. // Set bmLOWSPEED and bmHUBPRE in case of low-speed device, reset them otherwise
  97. regWr(rMODE, (p->lowspeed) ? mode | bmLOWSPEED | bmHubPre : mode & ~(bmHUBPRE | bmLOWSPEED));
  98. return 0;
  99. }
  100. /* Control transfer. Sets address, endpoint, fills control packet with necessary data, dispatches control packet, and initiates bulk IN transfer, */
  101. /* depending on request. Actual requests are defined as inlines */
  102. /* return codes: */
  103. /* 00 = success */
  104. /* 01-0f = non-zero HRSLT */
  105. uint8_t USB::ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi,
  106. uint16_t wInd, uint16_t total, uint16_t nbytes, uint8_t* dataptr, USBReadParser *p) {
  107. bool direction = false; //request direction, IN or OUT
  108. uint8_t rcode;
  109. SETUP_PKT setup_pkt;
  110. EpInfo *pep = nullptr;
  111. uint16_t nak_limit = 0;
  112. rcode = SetAddress(addr, ep, &pep, &nak_limit);
  113. if (rcode) return rcode;
  114. direction = ((bmReqType & 0x80) > 0);
  115. /* fill in setup packet */
  116. setup_pkt.ReqType_u.bmRequestType = bmReqType;
  117. setup_pkt.bRequest = bRequest;
  118. setup_pkt.wVal_u.wValueLo = wValLo;
  119. setup_pkt.wVal_u.wValueHi = wValHi;
  120. setup_pkt.wIndex = wInd;
  121. setup_pkt.wLength = total;
  122. bytesWr(rSUDFIFO, 8, (uint8_t*) & setup_pkt); //transfer to setup packet FIFO
  123. rcode = dispatchPkt(tokSETUP, ep, nak_limit); //dispatch packet
  124. if (rcode) return rcode; // Return HRSLT if not zero
  125. if (dataptr != nullptr) { //data stage, if present
  126. if (direction) { //IN transfer
  127. uint16_t left = total;
  128. pep->bmRcvToggle = 1; //bmRCVTOG1;
  129. while (left) {
  130. // Bytes read into buffer
  131. uint16_t read = nbytes;
  132. //uint16_t read = (left<nbytes) ? left : nbytes;
  133. rcode = InTransfer(pep, nak_limit, &read, dataptr);
  134. if (rcode == hrTOGERR) {
  135. // yes, we flip it wrong here so that next time it is actually correct!
  136. pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
  137. continue;
  138. }
  139. if (rcode) return rcode;
  140. // Invoke callback function if inTransfer completed successfully and callback function pointer is specified
  141. if (!rcode && p) ((USBReadParser*)p)->Parse(read, dataptr, total - left);
  142. left -= read;
  143. if (read < nbytes) break;
  144. }
  145. }
  146. else { //OUT transfer
  147. pep->bmSndToggle = 1; //bmSNDTOG1;
  148. rcode = OutTransfer(pep, nak_limit, nbytes, dataptr);
  149. }
  150. if (rcode) return rcode; // return error
  151. }
  152. // Status stage
  153. return dispatchPkt((direction) ? tokOUTHS : tokINHS, ep, nak_limit); //GET if direction
  154. }
  155. /* IN transfer to arbitrary endpoint. Assumes PERADDR is set. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */
  156. /* Keep sending INs and writes data to memory area pointed by 'data' */
  157. /* rcode 0 if no errors. rcode 01-0f is relayed from dispatchPkt(). Rcode f0 means RCVDAVIRQ error,
  158. fe USB xfer timeout */
  159. uint8_t USB::inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t* data, uint8_t bInterval /*= 0*/) {
  160. EpInfo *pep = nullptr;
  161. uint16_t nak_limit = 0;
  162. uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit);
  163. if (rcode) {
  164. USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81);
  165. USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81);
  166. USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81);
  167. return rcode;
  168. }
  169. return InTransfer(pep, nak_limit, nbytesptr, data, bInterval);
  170. }
  171. uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t* data, uint8_t bInterval /*= 0*/) {
  172. uint8_t rcode = 0;
  173. uint8_t pktsize;
  174. uint16_t nbytes = *nbytesptr;
  175. //printf("Requesting %i bytes ", nbytes);
  176. uint8_t maxpktsize = pep->maxPktSize;
  177. *nbytesptr = 0;
  178. regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value
  179. // use a 'break' to exit this loop
  180. for (;;) {
  181. rcode = dispatchPkt(tokIN, pep->epAddr, nak_limit); //IN packet to EP-'endpoint'. Function takes care of NAKS.
  182. if (rcode == hrTOGERR) {
  183. // yes, we flip it wrong here so that next time it is actually correct!
  184. pep->bmRcvToggle = (regRd(rHRSL) & bmRCVTOGRD) ? 0 : 1;
  185. regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value
  186. continue;
  187. }
  188. if (rcode) {
  189. //printf(">>>>>>>> Problem! dispatchPkt %2.2x\r\n", rcode);
  190. break; //should be 0, indicating ACK. Else return error code.
  191. }
  192. /* check for RCVDAVIRQ and generate error if not present */
  193. /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */
  194. if ((regRd(rHIRQ) & bmRCVDAVIRQ) == 0) {
  195. //printf(">>>>>>>> Problem! NO RCVDAVIRQ!\r\n");
  196. rcode = 0xF0; //receive error
  197. break;
  198. }
  199. pktsize = regRd(rRCVBC); //number of received bytes
  200. //printf("Got %i bytes \r\n", pktsize);
  201. // This would be OK, but...
  202. //assert(pktsize <= nbytes);
  203. if (pktsize > nbytes) {
  204. // This can happen. Use of assert on Arduino locks up the Arduino.
  205. // So I will trim the value, and hope for the best.
  206. //printf(">>>>>>>> Problem! Wanted %i bytes but got %i.\r\n", nbytes, pktsize);
  207. pktsize = nbytes;
  208. }
  209. int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr);
  210. if (mem_left < 0) mem_left = 0;
  211. data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data);
  212. regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer
  213. *nbytesptr += pktsize; // add this packet's byte count to total transfer length
  214. /* The transfer is complete under two conditions: */
  215. /* 1. The device sent a short packet (L.T. maxPacketSize) */
  216. /* 2. 'nbytes' have been transferred. */
  217. if (pktsize < maxpktsize || *nbytesptr >= nbytes) { // Transferred 'nbytes' bytes?
  218. // Save toggle value
  219. pep->bmRcvToggle = ((regRd(rHRSL) & bmRCVTOGRD)) ? 1 : 0;
  220. //printf("\r\n");
  221. rcode = 0;
  222. break;
  223. }
  224. else if (bInterval > 0)
  225. delay(bInterval); // Delay according to polling interval
  226. }
  227. return rcode;
  228. }
  229. /* OUT transfer to arbitrary endpoint. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */
  230. /* Handles NAK bug per Maxim Application Note 4000 for single buffer transfer */
  231. /* rcode 0 if no errors. rcode 01-0f is relayed from HRSL */
  232. uint8_t USB::outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* data) {
  233. EpInfo *pep = nullptr;
  234. uint16_t nak_limit = 0;
  235. uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit);
  236. if (rcode) return rcode;
  237. return OutTransfer(pep, nak_limit, nbytes, data);
  238. }
  239. uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data) {
  240. uint8_t rcode = hrSUCCESS, retry_count;
  241. uint8_t *data_p = data; //local copy of the data pointer
  242. uint16_t bytes_tosend, nak_count;
  243. uint16_t bytes_left = nbytes;
  244. uint8_t maxpktsize = pep->maxPktSize;
  245. if (maxpktsize < 1 || maxpktsize > 64)
  246. return USB_ERROR_INVALID_MAX_PKT_SIZE;
  247. uint32_t timeout = (uint32_t)millis() + USB_XFER_TIMEOUT;
  248. regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); //set toggle value
  249. while (bytes_left) {
  250. retry_count = 0;
  251. nak_count = 0;
  252. bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left;
  253. bytesWr(rSNDFIFO, bytes_tosend, data_p); //filling output FIFO
  254. regWr(rSNDBC, bytes_tosend); //set number of bytes
  255. regWr(rHXFR, (tokOUT | pep->epAddr)); //dispatch packet
  256. while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ
  257. regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ
  258. rcode = (regRd(rHRSL) & 0x0F);
  259. while (rcode && ((int32_t)((uint32_t)millis() - timeout) < 0L)) {
  260. switch (rcode) {
  261. case hrNAK:
  262. nak_count++;
  263. if (nak_limit && (nak_count == nak_limit))
  264. goto breakout;
  265. //return ( rcode);
  266. break;
  267. case hrTIMEOUT:
  268. retry_count++;
  269. if (retry_count == USB_RETRY_LIMIT)
  270. goto breakout;
  271. //return ( rcode);
  272. break;
  273. case hrTOGERR:
  274. // yes, we flip it wrong here so that next time it is actually correct!
  275. pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
  276. regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); //set toggle value
  277. break;
  278. default:
  279. goto breakout;
  280. }
  281. /* process NAK according to Host out NAK bug */
  282. regWr(rSNDBC, 0);
  283. regWr(rSNDFIFO, *data_p);
  284. regWr(rSNDBC, bytes_tosend);
  285. regWr(rHXFR, (tokOUT | pep->epAddr)); //dispatch packet
  286. while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ
  287. regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ
  288. rcode = (regRd(rHRSL) & 0x0F);
  289. } // while rcode && ....
  290. bytes_left -= bytes_tosend;
  291. data_p += bytes_tosend;
  292. } // while bytes_left...
  293. breakout:
  294. pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 1 : 0; //bmSNDTOG1 : bmSNDTOG0; //update toggle
  295. return ( rcode); //should be 0 in all cases
  296. }
  297. /* dispatch USB packet. Assumes peripheral address is set and relevant buffer is loaded/empty */
  298. /* If NAK, tries to re-send up to nak_limit times */
  299. /* If nak_limit == 0, do not count NAKs, exit after timeout */
  300. /* If bus timeout, re-sends up to USB_RETRY_LIMIT times */
  301. /* return codes 0x00-0x0F are HRSLT( 0x00 being success ), 0xFF means timeout */
  302. uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) {
  303. uint32_t timeout = (uint32_t)millis() + USB_XFER_TIMEOUT;
  304. uint8_t tmpdata;
  305. uint8_t rcode = hrSUCCESS;
  306. uint8_t retry_count = 0;
  307. uint16_t nak_count = 0;
  308. while ((int32_t)((uint32_t)millis() - timeout) < 0L) {
  309. #if defined(ESP8266) || defined(ESP32)
  310. yield(); // needed in order to reset the watchdog timer on the ESP8266
  311. #endif
  312. regWr(rHXFR, (token | ep)); //launch the transfer
  313. rcode = USB_ERROR_TRANSFER_TIMEOUT;
  314. while ((int32_t)((uint32_t)millis() - timeout) < 0L) { //wait for transfer completion
  315. #if defined(ESP8266) || defined(ESP32)
  316. yield(); // needed to reset the watchdog timer on the ESP8266
  317. #endif
  318. tmpdata = regRd(rHIRQ);
  319. if (tmpdata & bmHXFRDNIRQ) {
  320. regWr(rHIRQ, bmHXFRDNIRQ); //clear the interrupt
  321. rcode = 0x00;
  322. break;
  323. }
  324. } // while millis() < timeout
  325. //if (rcode != 0x00) //exit if timeout
  326. // return ( rcode);
  327. rcode = (regRd(rHRSL) & 0x0F); //analyze transfer result
  328. switch (rcode) {
  329. case hrNAK:
  330. nak_count++;
  331. if (nak_limit && (nak_count == nak_limit))
  332. return (rcode);
  333. break;
  334. case hrTIMEOUT:
  335. retry_count++;
  336. if (retry_count == USB_RETRY_LIMIT)
  337. return (rcode);
  338. break;
  339. default:
  340. return (rcode);
  341. }
  342. } // while timeout > millis()
  343. return rcode;
  344. }
  345. /* USB main task. Performs enumeration/cleanup */
  346. void USB::Task() { //USB state machine
  347. uint8_t rcode;
  348. uint8_t tmpdata;
  349. static uint32_t delay = 0;
  350. //USB_DEVICE_DESCRIPTOR buf;
  351. bool lowspeed = false;
  352. MAX3421E::Task();
  353. tmpdata = getVbusState();
  354. /* modify USB task state if Vbus changed */
  355. switch (tmpdata) {
  356. case SE1: //illegal state
  357. usb_task_state = USB_DETACHED_SUBSTATE_ILLEGAL;
  358. lowspeed = false;
  359. break;
  360. case SE0: //disconnected
  361. if ((usb_task_state & USB_STATE_MASK) != USB_STATE_DETACHED)
  362. usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE;
  363. lowspeed = false;
  364. break;
  365. case LSHOST:
  366. lowspeed = true;
  367. //intentional fallthrough
  368. case FSHOST: //attached
  369. if ((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) {
  370. delay = (uint32_t)millis() + USB_SETTLE_DELAY;
  371. usb_task_state = USB_ATTACHED_SUBSTATE_SETTLE;
  372. }
  373. break;
  374. }
  375. for (uint8_t i = 0; i < USB_NUMDEVICES; i++)
  376. if (devConfig[i]) rcode = devConfig[i]->Poll();
  377. switch (usb_task_state) {
  378. case USB_DETACHED_SUBSTATE_INITIALIZE:
  379. init();
  380. for (uint8_t i = 0; i < USB_NUMDEVICES; i++)
  381. if (devConfig[i])
  382. rcode = devConfig[i]->Release();
  383. usb_task_state = USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE;
  384. break;
  385. case USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE: //just sit here
  386. break;
  387. case USB_DETACHED_SUBSTATE_ILLEGAL: //just sit here
  388. break;
  389. case USB_ATTACHED_SUBSTATE_SETTLE: //settle time for just attached device
  390. if ((int32_t)((uint32_t)millis() - delay) >= 0L)
  391. usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE;
  392. else break; // don't fall through
  393. case USB_ATTACHED_SUBSTATE_RESET_DEVICE:
  394. regWr(rHCTL, bmBUSRST); //issue bus reset
  395. usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE;
  396. break;
  397. case USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE:
  398. if ((regRd(rHCTL) & bmBUSRST) == 0) {
  399. tmpdata = regRd(rMODE) | bmSOFKAENAB; //start SOF generation
  400. regWr(rMODE, tmpdata);
  401. usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_SOF;
  402. //delay = (uint32_t)millis() + 20; //20ms wait after reset per USB spec
  403. }
  404. break;
  405. case USB_ATTACHED_SUBSTATE_WAIT_SOF: //todo: change check order
  406. if (regRd(rHIRQ) & bmFRAMEIRQ) {
  407. //when first SOF received _and_ 20ms has passed we can continue
  408. /*
  409. if (delay < (uint32_t)millis()) //20ms passed
  410. usb_task_state = USB_STATE_CONFIGURING;
  411. */
  412. usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET;
  413. delay = (uint32_t)millis() + 20;
  414. }
  415. break;
  416. case USB_ATTACHED_SUBSTATE_WAIT_RESET:
  417. if ((int32_t)((uint32_t)millis() - delay) >= 0L) usb_task_state = USB_STATE_CONFIGURING;
  418. else break; // don't fall through
  419. case USB_STATE_CONFIGURING:
  420. //Serial.print("\r\nConf.LS: ");
  421. //Serial.println(lowspeed, HEX);
  422. rcode = Configuring(0, 0, lowspeed);
  423. if (!rcode)
  424. usb_task_state = USB_STATE_RUNNING;
  425. else if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) {
  426. usb_error = rcode;
  427. usb_task_state = USB_STATE_ERROR;
  428. }
  429. break;
  430. case USB_STATE_RUNNING:
  431. break;
  432. case USB_STATE_ERROR:
  433. //MAX3421E::Init();
  434. break;
  435. }
  436. }
  437. uint8_t USB::DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed) {
  438. //uint8_t buf[12];
  439. uint8_t rcode;
  440. UsbDevice *p0 = nullptr, *p = nullptr;
  441. // Get pointer to pseudo device with address 0 assigned
  442. p0 = addrPool.GetUsbDevicePtr(0);
  443. if (!p0) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  444. if (!p0->epinfo) return USB_ERROR_EPINFO_IS_NULL;
  445. p0->lowspeed = lowspeed;
  446. // Allocate new address according to device class
  447. uint8_t bAddress = addrPool.AllocAddress(parent, false, port);
  448. if (!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
  449. p = addrPool.GetUsbDevicePtr(bAddress);
  450. if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  451. p->lowspeed = lowspeed;
  452. // Assign new address to the device
  453. rcode = setAddr(0, 0, bAddress);
  454. if (rcode) {
  455. addrPool.FreeAddress(bAddress);
  456. bAddress = 0;
  457. }
  458. return rcode;
  459. }
  460. uint8_t USB::AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lowspeed) {
  461. //printf("AttemptConfig: parent = %i, port = %i\r\n", parent, port);
  462. uint8_t retries = 0;
  463. again:
  464. uint8_t rcode = devConfig[driver]->ConfigureDevice(parent, port, lowspeed);
  465. if (rcode == USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET) {
  466. if (parent == 0) {
  467. // Send a bus reset on the root interface.
  468. regWr(rHCTL, bmBUSRST); //issue bus reset
  469. delay(102); // delay 102ms, compensate for clock inaccuracy.
  470. }
  471. else {
  472. // reset parent port
  473. devConfig[parent]->ResetHubPort(port);
  474. }
  475. }
  476. else if (rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works
  477. delay(100);
  478. retries++;
  479. goto again;
  480. }
  481. else if (rcode)
  482. return rcode;
  483. rcode = devConfig[driver]->Init(parent, port, lowspeed);
  484. if (rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works
  485. delay(100);
  486. retries++;
  487. goto again;
  488. }
  489. if (rcode) {
  490. // Issue a bus reset, because the device may be in a limbo state
  491. if (parent == 0) {
  492. // Send a bus reset on the root interface.
  493. regWr(rHCTL, bmBUSRST); //issue bus reset
  494. delay(102); // delay 102ms, compensate for clock inaccuracy.
  495. }
  496. else {
  497. // reset parent port
  498. devConfig[parent]->ResetHubPort(port);
  499. }
  500. }
  501. return rcode;
  502. }
  503. /**
  504. * This is broken. It needs to enumerate differently.
  505. * It causes major problems with several devices if detected in an unexpected order.
  506. *
  507. * Oleg - I wouldn't do anything before the newly connected device is considered sane.
  508. * i.e.(delays are not indicated for brevity):
  509. * 1. reset
  510. * 2. GetDevDescr();
  511. * 3a. If ACK, continue with allocating address, addressing, etc.
  512. * 3b. Else reset again, count resets, stop at some number (5?).
  513. * 4. When max.number of resets is reached, toggle power/fail
  514. * If desired, this could be modified by performing two resets with GetDevDescr() in the middle - however, from my experience, if a device answers to GDD()
  515. * it doesn't need to be reset again
  516. * New steps proposal:
  517. * 1: get address pool instance. exit on fail
  518. * 2: pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf). exit on fail.
  519. * 3: bus reset, 100ms delay
  520. * 4: set address
  521. * 5: pUsb->setEpInfoEntry(bAddress, 1, epInfo), exit on fail
  522. * 6: while (configurations) {
  523. * for (each configuration) {
  524. * for (each driver) {
  525. * 6a: Ask device if it likes configuration. Returns 0 on OK.
  526. * If successful, the driver configured device.
  527. * The driver now owns the endpoints, and takes over managing them.
  528. * The following will need codes:
  529. * Everything went well, instance consumed, exit with success.
  530. * Instance already in use, ignore it, try next driver.
  531. * Not a supported device, ignore it, try next driver.
  532. * Not a supported configuration for this device, ignore it, try next driver.
  533. * Could not configure device, fatal, exit with fail.
  534. * }
  535. * }
  536. * }
  537. * 7: for (each driver) {
  538. * 7a: Ask device if it knows this VID/PID. Acts exactly like 6a, but using VID/PID
  539. * 8: if we get here, no driver likes the device plugged in, so exit failure.
  540. *
  541. */
  542. uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) {
  543. //uint8_t bAddress = 0;
  544. //printf("Configuring: parent = %i, port = %i\r\n", parent, port);
  545. uint8_t devConfigIndex;
  546. uint8_t rcode = 0;
  547. uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
  548. USB_DEVICE_DESCRIPTOR *udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR *>(buf);
  549. UsbDevice *p = nullptr;
  550. EpInfo *oldep_ptr = nullptr;
  551. EpInfo epInfo;
  552. epInfo.epAddr = 0;
  553. epInfo.maxPktSize = 8;
  554. epInfo.bmSndToggle = 0;
  555. epInfo.bmRcvToggle = 0;
  556. epInfo.bmNakPower = USB_NAK_MAX_POWER;
  557. //delay(2000);
  558. AddressPool &addrPool = GetAddressPool();
  559. // Get pointer to pseudo device with address 0 assigned
  560. p = addrPool.GetUsbDevicePtr(0);
  561. if (!p) {
  562. //printf("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n");
  563. return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  564. }
  565. // Save old pointer to EP_RECORD of address 0
  566. oldep_ptr = p->epinfo;
  567. // Temporary assign new pointer to epInfo to p->epinfo in order to
  568. // avoid toggle inconsistence
  569. p->epinfo = &epInfo;
  570. p->lowspeed = lowspeed;
  571. // Get device descriptor
  572. rcode = getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf);
  573. // Restore p->epinfo
  574. p->epinfo = oldep_ptr;
  575. if (rcode) {
  576. //printf("Configuring error: Can't get USB_DEVICE_DESCRIPTOR\r\n");
  577. return rcode;
  578. }
  579. // to-do?
  580. // Allocate new address according to device class
  581. //bAddress = addrPool.AllocAddress(parent, false, port);
  582. uint16_t vid = udd->idVendor, pid = udd->idProduct;
  583. uint8_t klass = udd->bDeviceClass, subklass = udd->bDeviceSubClass;
  584. // Attempt to configure if VID/PID or device class matches with a driver
  585. // Qualify with subclass too.
  586. //
  587. // VID/PID & class tests default to false for drivers not yet ported
  588. // subclass defaults to true, so you don't have to define it if you don't have to.
  589. //
  590. for (devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) {
  591. if (!devConfig[devConfigIndex]) continue; // no driver
  592. if (devConfig[devConfigIndex]->GetAddress()) continue; // consumed
  593. if (devConfig[devConfigIndex]->DEVSUBCLASSOK(subklass) && (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass))) {
  594. rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed);
  595. if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED)
  596. break;
  597. }
  598. }
  599. if (devConfigIndex < USB_NUMDEVICES) return rcode;
  600. // blindly attempt to configure
  601. for (devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) {
  602. if (!devConfig[devConfigIndex]) continue;
  603. if (devConfig[devConfigIndex]->GetAddress()) continue; // consumed
  604. if (devConfig[devConfigIndex]->DEVSUBCLASSOK(subklass) && (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass))) continue; // If this is true it means it must have returned USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED above
  605. rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed);
  606. //printf("ERROR ENUMERATING %2.2x\r\n", rcode);
  607. if (!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) {
  608. // in case of an error dev_index should be reset to 0
  609. // in order to start from the very beginning the
  610. // next time the program gets here
  611. //if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE)
  612. // devConfigIndex = 0;
  613. return rcode;
  614. }
  615. }
  616. // Arriving here means the device class is unsupported by registered classes
  617. return DefaultAddressing(parent, port, lowspeed);
  618. }
  619. uint8_t USB::ReleaseDevice(uint8_t addr) {
  620. if (addr) {
  621. for (uint8_t i = 0; i < USB_NUMDEVICES; i++) {
  622. if (!devConfig[i]) continue;
  623. if (devConfig[i]->GetAddress() == addr)
  624. return devConfig[i]->Release();
  625. }
  626. }
  627. return 0;
  628. }
  629. #if 1 //!defined(USB_METHODS_INLINE)
  630. //get device descriptor
  631. uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) {
  632. return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, nbytes, dataptr, nullptr);
  633. }
  634. //get configuration descriptor
  635. uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) {
  636. return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, nbytes, dataptr, nullptr);
  637. }
  638. /* Requests Configuration Descriptor. Sends two Get Conf Descr requests. The first one gets the total length of all descriptors, then the second one requests this
  639. total length. The length of the first request can be shorter ( 4 bytes ), however, there are devices which won't work unless this length is set to 9 */
  640. uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p) {
  641. const uint8_t bufSize = 64;
  642. uint8_t buf[bufSize];
  643. USB_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast<USB_CONFIGURATION_DESCRIPTOR *>(buf);
  644. uint8_t ret = getConfDescr(addr, ep, 9, conf, buf);
  645. if (ret) return ret;
  646. uint16_t total = ucd->wTotalLength;
  647. //USBTRACE2("\r\ntotal conf.size:", total);
  648. return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, total, bufSize, buf, p);
  649. }
  650. //get string descriptor
  651. uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t ns, uint8_t index, uint16_t langid, uint8_t* dataptr) {
  652. return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, ns, ns, dataptr, nullptr);
  653. }
  654. //set address
  655. uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) {
  656. uint8_t rcode = ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, nullptr, nullptr);
  657. //delay(2); //per USB 2.0 sect.9.2.6.3
  658. delay(300); // Older spec says you should wait at least 200ms
  659. return rcode;
  660. //return ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, nullptr, nullptr);
  661. }
  662. //set configuration
  663. uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) {
  664. return ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, 0x0000, nullptr, nullptr);
  665. }
  666. #endif // defined(USB_METHODS_INLINE)
  667. #endif // USB_FLASH_DRIVE_SUPPORT