USBCore.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. /* Copyright (c) 2010, Peter Barrett
  2. **
  3. ** Permission to use, copy, modify, and/or distribute this software for
  4. ** any purpose with or without fee is hereby granted, provided that the
  5. ** above copyright notice and this permission notice appear in all copies.
  6. **
  7. ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  8. ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  9. ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
  10. ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
  11. ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  12. ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
  13. ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  14. ** SOFTWARE.
  15. */
  16. #include "USBAPI.h"
  17. #if defined(USBCON)
  18. #define EP_TYPE_CONTROL 0x00
  19. #define EP_TYPE_BULK_IN 0x81
  20. #define EP_TYPE_BULK_OUT 0x80
  21. #define EP_TYPE_INTERRUPT_IN 0xC1
  22. #define EP_TYPE_INTERRUPT_OUT 0xC0
  23. #define EP_TYPE_ISOCHRONOUS_IN 0x41
  24. #define EP_TYPE_ISOCHRONOUS_OUT 0x40
  25. /** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */
  26. #define TX_RX_LED_PULSE_MS 100
  27. volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */
  28. volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */
  29. //==================================================================
  30. //==================================================================
  31. extern const u16 STRING_LANGUAGE[] PROGMEM;
  32. extern const u8 STRING_PRODUCT[] PROGMEM;
  33. extern const u8 STRING_MANUFACTURER[] PROGMEM;
  34. extern const DeviceDescriptor USB_DeviceDescriptor PROGMEM;
  35. extern const DeviceDescriptor USB_DeviceDescriptorA PROGMEM;
  36. const u16 STRING_LANGUAGE[2] = {
  37. (3<<8) | (2+2),
  38. 0x0409 // English
  39. };
  40. #ifndef USB_PRODUCT
  41. // If no product is provided, use USB IO Board
  42. #define USB_PRODUCT "USB IO Board"
  43. #endif
  44. const u8 STRING_PRODUCT[] PROGMEM = USB_PRODUCT;
  45. #if USB_VID == 0x2341
  46. # if defined(USB_MANUFACTURER)
  47. # undef USB_MANUFACTURER
  48. # endif
  49. # define USB_MANUFACTURER "Arduino LLC"
  50. #elif USB_VID == 0x1b4f
  51. # if defined(USB_MANUFACTURER)
  52. # undef USB_MANUFACTURER
  53. # endif
  54. # define USB_MANUFACTURER "SparkFun"
  55. #elif !defined(USB_MANUFACTURER)
  56. // Fall through to unknown if no manufacturer name was provided in a macro
  57. # define USB_MANUFACTURER "Unknown"
  58. #endif
  59. const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER;
  60. #ifdef CDC_ENABLED
  61. #define DEVICE_CLASS 0x02
  62. #else
  63. #define DEVICE_CLASS 0x00
  64. #endif
  65. // DEVICE DESCRIPTOR
  66. const DeviceDescriptor USB_DeviceDescriptor =
  67. D_DEVICE(0x00,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1);
  68. const DeviceDescriptor USB_DeviceDescriptorA =
  69. D_DEVICE(DEVICE_CLASS,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1);
  70. //==================================================================
  71. //==================================================================
  72. volatile u8 _usbConfiguration = 0;
  73. static inline void WaitIN(void)
  74. {
  75. while (!(UEINTX & (1<<TXINI)))
  76. ;
  77. }
  78. static inline void ClearIN(void)
  79. {
  80. UEINTX = ~(1<<TXINI);
  81. }
  82. static inline void WaitOUT(void)
  83. {
  84. while (!(UEINTX & (1<<RXOUTI)))
  85. ;
  86. }
  87. static inline u8 WaitForINOrOUT()
  88. {
  89. while (!(UEINTX & ((1<<TXINI)|(1<<RXOUTI))))
  90. ;
  91. return (UEINTX & (1<<RXOUTI)) == 0;
  92. }
  93. static inline void ClearOUT(void)
  94. {
  95. UEINTX = ~(1<<RXOUTI);
  96. }
  97. void Recv(volatile u8* data, u8 count)
  98. {
  99. while (count--)
  100. *data++ = UEDATX;
  101. RXLED1; // light the RX LED
  102. RxLEDPulse = TX_RX_LED_PULSE_MS;
  103. }
  104. static inline u8 Recv8()
  105. {
  106. RXLED1; // light the RX LED
  107. RxLEDPulse = TX_RX_LED_PULSE_MS;
  108. return UEDATX;
  109. }
  110. static inline void Send8(u8 d)
  111. {
  112. UEDATX = d;
  113. }
  114. static inline void SetEP(u8 ep)
  115. {
  116. UENUM = ep;
  117. }
  118. static inline u8 FifoByteCount()
  119. {
  120. return UEBCLX;
  121. }
  122. static inline u8 ReceivedSetupInt()
  123. {
  124. return UEINTX & (1<<RXSTPI);
  125. }
  126. static inline void ClearSetupInt()
  127. {
  128. UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
  129. }
  130. static inline void Stall()
  131. {
  132. UECONX = (1<<STALLRQ) | (1<<EPEN);
  133. }
  134. static inline u8 ReadWriteAllowed()
  135. {
  136. return UEINTX & (1<<RWAL);
  137. }
  138. static inline u8 Stalled()
  139. {
  140. return UEINTX & (1<<STALLEDI);
  141. }
  142. static inline u8 FifoFree()
  143. {
  144. return UEINTX & (1<<FIFOCON);
  145. }
  146. static inline void ReleaseRX()
  147. {
  148. UEINTX = 0x6B; // FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1
  149. }
  150. static inline void ReleaseTX()
  151. {
  152. UEINTX = 0x3A; // FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0
  153. }
  154. static inline u8 FrameNumber()
  155. {
  156. return UDFNUML;
  157. }
  158. //==================================================================
  159. //==================================================================
  160. u8 USBGetConfiguration(void)
  161. {
  162. return _usbConfiguration;
  163. }
  164. #define USB_RECV_TIMEOUT
  165. class LockEP
  166. {
  167. u8 _sreg;
  168. public:
  169. LockEP(u8 ep) : _sreg(SREG)
  170. {
  171. cli();
  172. SetEP(ep & 7);
  173. }
  174. ~LockEP()
  175. {
  176. SREG = _sreg;
  177. }
  178. };
  179. // Number of bytes, assumes a rx endpoint
  180. u8 USB_Available(u8 ep)
  181. {
  182. LockEP lock(ep);
  183. return FifoByteCount();
  184. }
  185. // Non Blocking receive
  186. // Return number of bytes read
  187. int USB_Recv(u8 ep, void* d, int len)
  188. {
  189. if (!_usbConfiguration || len < 0)
  190. return -1;
  191. LockEP lock(ep);
  192. u8 n = FifoByteCount();
  193. len = min(n,len);
  194. n = len;
  195. u8* dst = (u8*)d;
  196. while (n--)
  197. *dst++ = Recv8();
  198. if (len && !FifoByteCount()) // release empty buffer
  199. ReleaseRX();
  200. return len;
  201. }
  202. // Recv 1 byte if ready
  203. int USB_Recv(u8 ep)
  204. {
  205. u8 c;
  206. if (USB_Recv(ep,&c,1) != 1)
  207. return -1;
  208. return c;
  209. }
  210. // Space in send EP
  211. u8 USB_SendSpace(u8 ep)
  212. {
  213. LockEP lock(ep);
  214. if (!ReadWriteAllowed())
  215. return 0;
  216. return 64 - FifoByteCount();
  217. }
  218. // Blocking Send of data to an endpoint
  219. int USB_Send(u8 ep, const void* d, int len)
  220. {
  221. if (!_usbConfiguration)
  222. return -1;
  223. int r = len;
  224. const u8* data = (const u8*)d;
  225. u8 timeout = 250; // 250ms timeout on send? TODO
  226. while (len)
  227. {
  228. u8 n = USB_SendSpace(ep);
  229. if (n == 0)
  230. {
  231. if (!(--timeout))
  232. return -1;
  233. delay(1);
  234. continue;
  235. }
  236. if (n > len)
  237. n = len;
  238. {
  239. LockEP lock(ep);
  240. // Frame may have been released by the SOF interrupt handler
  241. if (!ReadWriteAllowed())
  242. continue;
  243. len -= n;
  244. if (ep & TRANSFER_ZERO)
  245. {
  246. while (n--)
  247. Send8(0);
  248. }
  249. else if (ep & TRANSFER_PGM)
  250. {
  251. while (n--)
  252. Send8(pgm_read_byte(data++));
  253. }
  254. else
  255. {
  256. while (n--)
  257. Send8(*data++);
  258. }
  259. if (!ReadWriteAllowed() || ((len == 0) && (ep & TRANSFER_RELEASE))) // Release full buffer
  260. ReleaseTX();
  261. }
  262. }
  263. TXLED1; // light the TX LED
  264. TxLEDPulse = TX_RX_LED_PULSE_MS;
  265. return r;
  266. }
  267. extern const u8 _initEndpoints[] PROGMEM;
  268. const u8 _initEndpoints[] =
  269. {
  270. 0,
  271. #ifdef CDC_ENABLED
  272. EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM
  273. EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT
  274. EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN
  275. #endif
  276. #ifdef HID_ENABLED
  277. EP_TYPE_INTERRUPT_IN // HID_ENDPOINT_INT
  278. #endif
  279. };
  280. #define EP_SINGLE_64 0x32 // EP0
  281. #define EP_DOUBLE_64 0x36 // Other endpoints
  282. static
  283. void InitEP(u8 index, u8 type, u8 size)
  284. {
  285. UENUM = index;
  286. UECONX = 1;
  287. UECFG0X = type;
  288. UECFG1X = size;
  289. }
  290. static
  291. void InitEndpoints()
  292. {
  293. for (u8 i = 1; i < sizeof(_initEndpoints); i++)
  294. {
  295. UENUM = i;
  296. UECONX = 1;
  297. UECFG0X = pgm_read_byte(_initEndpoints+i);
  298. UECFG1X = EP_DOUBLE_64;
  299. }
  300. UERST = 0x7E; // And reset them
  301. UERST = 0;
  302. }
  303. // Handle CLASS_INTERFACE requests
  304. static
  305. bool ClassInterfaceRequest(Setup& setup)
  306. {
  307. u8 i = setup.wIndex;
  308. #ifdef CDC_ENABLED
  309. if (CDC_ACM_INTERFACE == i)
  310. return CDC_Setup(setup);
  311. #endif
  312. #ifdef HID_ENABLED
  313. if (HID_INTERFACE == i)
  314. return HID_Setup(setup);
  315. #endif
  316. return false;
  317. }
  318. int _cmark;
  319. int _cend;
  320. void InitControl(int end)
  321. {
  322. SetEP(0);
  323. _cmark = 0;
  324. _cend = end;
  325. }
  326. static
  327. bool SendControl(u8 d)
  328. {
  329. if (_cmark < _cend)
  330. {
  331. if (!WaitForINOrOUT())
  332. return false;
  333. Send8(d);
  334. if (!((_cmark + 1) & 0x3F))
  335. ClearIN(); // Fifo is full, release this packet
  336. }
  337. _cmark++;
  338. return true;
  339. };
  340. // Clipped by _cmark/_cend
  341. int USB_SendControl(u8 flags, const void* d, int len)
  342. {
  343. int sent = len;
  344. const u8* data = (const u8*)d;
  345. bool pgm = flags & TRANSFER_PGM;
  346. while (len--)
  347. {
  348. u8 c = pgm ? pgm_read_byte(data++) : *data++;
  349. if (!SendControl(c))
  350. return -1;
  351. }
  352. return sent;
  353. }
  354. // Send a USB descriptor string. The string is stored in PROGMEM as a
  355. // plain ASCII string but is sent out as UTF-16 with the correct 2-byte
  356. // prefix
  357. static bool USB_SendStringDescriptor(const u8*string_P, u8 string_len) {
  358. SendControl(2 + string_len * 2);
  359. SendControl(3);
  360. for(u8 i = 0; i < string_len; i++) {
  361. bool r = SendControl(pgm_read_byte(&string_P[i]));
  362. r &= SendControl(0); // high byte
  363. if(!r) {
  364. return false;
  365. }
  366. }
  367. return true;
  368. }
  369. // Does not timeout or cross fifo boundaries
  370. // Will only work for transfers <= 64 bytes
  371. // TODO
  372. int USB_RecvControl(void* d, int len)
  373. {
  374. WaitOUT();
  375. Recv((u8*)d,len);
  376. ClearOUT();
  377. return len;
  378. }
  379. int SendInterfaces()
  380. {
  381. int total = 0;
  382. u8 interfaces = 0;
  383. #ifdef CDC_ENABLED
  384. total = CDC_GetInterface(&interfaces);
  385. #endif
  386. #ifdef HID_ENABLED
  387. total += HID_GetInterface(&interfaces);
  388. #endif
  389. return interfaces;
  390. }
  391. // Construct a dynamic configuration descriptor
  392. // This really needs dynamic endpoint allocation etc
  393. // TODO
  394. static
  395. bool SendConfiguration(int maxlen)
  396. {
  397. // Count and measure interfaces
  398. InitControl(0);
  399. int interfaces = SendInterfaces();
  400. ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces);
  401. // Now send them
  402. InitControl(maxlen);
  403. USB_SendControl(0,&config,sizeof(ConfigDescriptor));
  404. SendInterfaces();
  405. return true;
  406. }
  407. u8 _cdcComposite = 0;
  408. static
  409. bool SendDescriptor(Setup& setup)
  410. {
  411. u8 t = setup.wValueH;
  412. if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
  413. return SendConfiguration(setup.wLength);
  414. InitControl(setup.wLength);
  415. #ifdef HID_ENABLED
  416. if (HID_REPORT_DESCRIPTOR_TYPE == t)
  417. return HID_GetDescriptor(t);
  418. #endif
  419. const u8* desc_addr = 0;
  420. if (USB_DEVICE_DESCRIPTOR_TYPE == t)
  421. {
  422. if (setup.wLength == 8)
  423. _cdcComposite = 1;
  424. desc_addr = _cdcComposite ? (const u8*)&USB_DeviceDescriptorA : (const u8*)&USB_DeviceDescriptor;
  425. }
  426. else if (USB_STRING_DESCRIPTOR_TYPE == t)
  427. {
  428. if (setup.wValueL == 0) {
  429. desc_addr = (const u8*)&STRING_LANGUAGE;
  430. }
  431. else if (setup.wValueL == IPRODUCT) {
  432. return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT));
  433. }
  434. else if (setup.wValueL == IMANUFACTURER) {
  435. return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER));
  436. }
  437. else
  438. return false;
  439. }
  440. if (desc_addr == 0)
  441. return false;
  442. u8 desc_length = pgm_read_byte(desc_addr);
  443. USB_SendControl(TRANSFER_PGM,desc_addr,desc_length);
  444. return true;
  445. }
  446. // Endpoint 0 interrupt
  447. ISR(USB_COM_vect)
  448. {
  449. SetEP(0);
  450. if (!ReceivedSetupInt())
  451. return;
  452. Setup setup;
  453. Recv((u8*)&setup,8);
  454. ClearSetupInt();
  455. u8 requestType = setup.bmRequestType;
  456. if (requestType & REQUEST_DEVICETOHOST)
  457. WaitIN();
  458. else
  459. ClearIN();
  460. bool ok = true;
  461. if (REQUEST_STANDARD == (requestType & REQUEST_TYPE))
  462. {
  463. // Standard Requests
  464. u8 r = setup.bRequest;
  465. if (GET_STATUS == r)
  466. {
  467. Send8(0); // TODO
  468. Send8(0);
  469. }
  470. else if (CLEAR_FEATURE == r)
  471. {
  472. }
  473. else if (SET_FEATURE == r)
  474. {
  475. }
  476. else if (SET_ADDRESS == r)
  477. {
  478. WaitIN();
  479. UDADDR = setup.wValueL | (1<<ADDEN);
  480. }
  481. else if (GET_DESCRIPTOR == r)
  482. {
  483. ok = SendDescriptor(setup);
  484. }
  485. else if (SET_DESCRIPTOR == r)
  486. {
  487. ok = false;
  488. }
  489. else if (GET_CONFIGURATION == r)
  490. {
  491. Send8(1);
  492. }
  493. else if (SET_CONFIGURATION == r)
  494. {
  495. if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT))
  496. {
  497. InitEndpoints();
  498. _usbConfiguration = setup.wValueL;
  499. } else
  500. ok = false;
  501. }
  502. else if (GET_INTERFACE == r)
  503. {
  504. }
  505. else if (SET_INTERFACE == r)
  506. {
  507. }
  508. }
  509. else
  510. {
  511. InitControl(setup.wLength); // Max length of transfer
  512. ok = ClassInterfaceRequest(setup);
  513. }
  514. if (ok)
  515. ClearIN();
  516. else
  517. {
  518. Stall();
  519. }
  520. }
  521. void USB_Flush(u8 ep)
  522. {
  523. SetEP(ep);
  524. if (FifoByteCount())
  525. ReleaseTX();
  526. }
  527. // General interrupt
  528. ISR(USB_GEN_vect)
  529. {
  530. u8 udint = UDINT;
  531. UDINT = 0;
  532. // End of Reset
  533. if (udint & (1<<EORSTI))
  534. {
  535. InitEP(0,EP_TYPE_CONTROL,EP_SINGLE_64); // init ep0
  536. _usbConfiguration = 0; // not configured yet
  537. UEIENX = 1 << RXSTPE; // Enable interrupts for ep0
  538. }
  539. // Start of Frame - happens every millisecond so we use it for TX and RX LED one-shot timing, too
  540. if (udint & (1<<SOFI))
  541. {
  542. #ifdef CDC_ENABLED
  543. USB_Flush(CDC_TX); // Send a tx frame if found
  544. #endif
  545. // check whether the one-shot period has elapsed. if so, turn off the LED
  546. if (TxLEDPulse && !(--TxLEDPulse))
  547. TXLED0;
  548. if (RxLEDPulse && !(--RxLEDPulse))
  549. RXLED0;
  550. }
  551. }
  552. // VBUS or counting frames
  553. // Any frame counting?
  554. u8 USBConnected()
  555. {
  556. u8 f = UDFNUML;
  557. delay(3);
  558. return f != UDFNUML;
  559. }
  560. //=======================================================================
  561. //=======================================================================
  562. USBDevice_ USBDevice;
  563. USBDevice_::USBDevice_()
  564. {
  565. }
  566. void USBDevice_::attach()
  567. {
  568. _usbConfiguration = 0;
  569. UHWCON = 0x01; // power internal reg
  570. USBCON = (1<<USBE)|(1<<FRZCLK); // clock frozen, usb enabled
  571. #if F_CPU == 16000000UL
  572. PLLCSR = 0x12; // Need 16 MHz xtal
  573. #elif F_CPU == 8000000UL
  574. PLLCSR = 0x02; // Need 8 MHz xtal
  575. #endif
  576. while (!(PLLCSR & (1<<PLOCK))) // wait for lock pll
  577. ;
  578. // Some tests on specific versions of macosx (10.7.3), reported some
  579. // strange behaviuors when the board is reset using the serial
  580. // port touch at 1200 bps. This delay fixes this behaviour.
  581. delay(1);
  582. USBCON = ((1<<USBE)|(1<<OTGPADE)); // start USB clock
  583. UDIEN = (1<<EORSTE)|(1<<SOFE); // Enable interrupts for EOR (End of Reset) and SOF (start of frame)
  584. UDCON = 0; // enable attach resistor
  585. TX_RX_LED_INIT;
  586. }
  587. void USBDevice_::detach()
  588. {
  589. }
  590. // Check for interrupts
  591. // TODO: VBUS detection
  592. bool USBDevice_::configured()
  593. {
  594. return _usbConfiguration;
  595. }
  596. void USBDevice_::poll()
  597. {
  598. }
  599. #endif /* if defined(USBCON) */