Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
Este repositório está arquivado. Você pode visualizar os arquivos e realizar clone, mas não poderá realizar push nem abrir issues e pull requests.

Usb.cpp 34KB

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