USBCore.cpp 13 KB

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