Debian Codegraph @

cores/arduino/USBCore.cpp

raw
1
2
3 /* Copyright (c) 2010, Peter Barrett
4 ** Sleep/Wakeup support added by Michael Dreher
5 **
6 ** Permission to use, copy, modify, and/or distribute this software for
7 ** any purpose with or without fee is hereby granted, provided that the
8 ** above copyright notice and this permission notice appear in all copies.
9 **
10 ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
11 ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
12 ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
13 ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
14 ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
15 ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
16 ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
17 ** SOFTWARE.
18 */
19
20 #include "USBAPI.h"
21 #include "PluggableUSB.h"
22 #include <stdlib.h>
23
24 #if defined(USBCON)
25
26 /** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */
27 #define TX_RX_LED_PULSE_MS 100
28 volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */
29 volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */
30
31 //==================================================================
32 //==================================================================
33
34 extern const u16 STRING_LANGUAGE[] PROGMEM;
35 extern const u8 STRING_PRODUCT[] PROGMEM;
36 extern const u8 STRING_MANUFACTURER[] PROGMEM;
37 extern const DeviceDescriptor USB_DeviceDescriptorIAD PROGMEM;
38
39 const u16 STRING_LANGUAGE[2] = {
40 (3<<8) | (2+2),
41 0x0409 // English
42 };
43
44 #ifndef USB_PRODUCT
45 // If no product is provided, use USB IO Board
46 #define USB_PRODUCT "USB IO Board"
47 #endif
48
49 const u8 STRING_PRODUCT[] PROGMEM = USB_PRODUCT;
50
51 #if USB_VID == 0x2341
52 # if defined(USB_MANUFACTURER)
53 # undef USB_MANUFACTURER
54 # endif
55 # define USB_MANUFACTURER "Arduino LLC"
56 #elif USB_VID == 0x1b4f
57 # if defined(USB_MANUFACTURER)
58 # undef USB_MANUFACTURER
59 # endif
60 # define USB_MANUFACTURER "SparkFun"
61 #elif !defined(USB_MANUFACTURER)
62 // Fall through to unknown if no manufacturer name was provided in a macro
63 # define USB_MANUFACTURER "Unknown"
64 #endif
65
66 const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER;
67
68
69 #define DEVICE_CLASS 0x02
70
71 // DEVICE DESCRIPTOR
72
73 #ifdef CDC_ENABLED
74 const DeviceDescriptor USB_DeviceDescriptorIAD =
75 D_DEVICE(0xEF,0x02,0x01,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,ISERIAL,1);
76 #else // CDC_DISABLED
77 // The default descriptor uses USB class OxEF, subclass 0x02 with protocol 1
78 // which means "Interface Association Descriptor" - that's needed for the CDC,
79 // but doesn't make much sense as a default for custom devices when CDC is disabled.
80 // (0x00 means "Use class information in the Interface Descriptors" which should be generally ok)
81 const DeviceDescriptor USB_DeviceDescriptorIAD =
82 D_DEVICE(0x00,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,ISERIAL,1);
83 #endif
84
85 //==================================================================
86 //==================================================================
87
88 volatile u8 _usbConfiguration = 0;
89 volatile u8 _usbCurrentStatus = 0; // meaning of bits see usb_20.pdf, Figure 9-4. Information Returned by a GetStatus() Request to a Device
90 volatile u8 _usbSuspendState = 0; // copy of UDINT to check SUSPI and WAKEUPI bits
91
92 static inline void WaitIN(void)
93 {
94 while (!(UEINTX & (1<<TXINI)))
95 ;
96 }
97
98 static inline void ClearIN(void)
99 {
100 UEINTX = ~(1<<TXINI);
101 }
102
103 static inline void WaitOUT(void)
104 {
105 while (!(UEINTX & (1<<RXOUTI)))
106 ;
107 }
108
109 static inline u8 WaitForINOrOUT()
110 {
111 while (!(UEINTX & ((1<<TXINI)|(1<<RXOUTI))))
112 ;
113 return (UEINTX & (1<<RXOUTI)) == 0;
114 }
115
116 static inline void ClearOUT(void)
117 {
118 UEINTX = ~(1<<RXOUTI);
119 }
120
121 static inline void Recv(volatile u8* data, u8 count)
122 {
123 while (count--)
124 *data++ = UEDATX;
125
126 RXLED1; // light the RX LED
127 RxLEDPulse = TX_RX_LED_PULSE_MS;
128 }
129
130 static inline u8 Recv8()
131 {
132 RXLED1; // light the RX LED
133 RxLEDPulse = TX_RX_LED_PULSE_MS;
134
135 return UEDATX;
136 }
137
138 static inline void Send8(u8 d)
139 {
140 UEDATX = d;
141 }
142
143 static inline void SetEP(u8 ep)
144 {
145 UENUM = ep;
146 }
147
148 static inline u8 FifoByteCount()
149 {
150 return UEBCLX;
151 }
152
153 static inline u8 ReceivedSetupInt()
154 {
155 return UEINTX & (1<<RXSTPI);
156 }
157
158 static inline void ClearSetupInt()
159 {
160 UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
161 }
162
163 static inline void Stall()
164 {
165 UECONX = (1<<STALLRQ) | (1<<EPEN);
166 }
167
168 static inline u8 ReadWriteAllowed()
169 {
170 return UEINTX & (1<<RWAL);
171 }
172
173 static inline u8 Stalled()
174 {
175 return UEINTX & (1<<STALLEDI);
176 }
177
178 static inline u8 FifoFree()
179 {
180 return UEINTX & (1<<FIFOCON);
181 }
182
183 static inline void ReleaseRX()
184 {
185 UEINTX = 0x6B; // FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1
186 }
187
188 static inline void ReleaseTX()
189 {
190 UEINTX = 0x3A; // FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0
191 }
192
193 static inline u8 FrameNumber()
194 {
195 return UDFNUML;
196 }
197
198 //==================================================================
199 //==================================================================
200
201 u8 USBGetConfiguration(void)
202 {
203 return _usbConfiguration;
204 }
205
206 #define USB_RECV_TIMEOUT
207 class LockEP
208 {
209 u8 _sreg;
210 public:
211 LockEP(u8 ep) : _sreg(SREG)
212 {
213 cli();
214 SetEP(ep & 7);
215 }
216 ~LockEP()
217 {
218 SREG = _sreg;
219 }
220 };
221
222 // Number of bytes, assumes a rx endpoint
223 u8 USB_Available(u8 ep)
224 {
225 LockEP lock(ep);
226 return FifoByteCount();
227 }
228
229 // Non Blocking receive
230 // Return number of bytes read
231 int USB_Recv(u8 ep, void* d, int len)
232 {
233 if (!_usbConfiguration || len < 0)
234 return -1;
235
236 LockEP lock(ep);
237 u8 n = FifoByteCount();
238 len = min(n,len);
239 n = len;
240 u8* dst = (u8*)d;
241 while (n--)
242 *dst++ = Recv8();
243 if (len && !FifoByteCount()) // release empty buffer
244 ReleaseRX();
245
246 return len;
247 }
248
249 // Recv 1 byte if ready
250 int USB_Recv(u8 ep)
251 {
252 u8 c;
253 if (USB_Recv(ep,&c,1) != 1)
254 return -1;
255 return c;
256 }
257
258 // Space in send EP
259 u8 USB_SendSpace(u8 ep)
260 {
261 LockEP lock(ep);
262 if (!ReadWriteAllowed())
263 return 0;
264 return USB_EP_SIZE - FifoByteCount();
265 }
266
267 // Blocking Send of data to an endpoint
268 int USB_Send(u8 ep, const void* d, int len)
269 {
270 if (!_usbConfiguration)
271 return -1;
272
273 if (_usbSuspendState & (1<<SUSPI)) {
274 //send a remote wakeup
275 UDCON |= (1 << RMWKUP);
276 }
277
278 int r = len;
279 const u8* data = (const u8*)d;
280 u8 timeout = 250; // 250ms timeout on send? TODO
281 bool sendZlp = false;
282
283 while (len || sendZlp)
284 {
285 u8 n = USB_SendSpace(ep);
286 if (n == 0)
287 {
288 if (!(--timeout))
289 return -1;
290 delay(1);
291 continue;
292 }
293
294 if (n > len) {
295 n = len;
296 }
297
298 {
299 LockEP lock(ep);
300 // Frame may have been released by the SOF interrupt handler
301 if (!ReadWriteAllowed())
302 continue;
303
304 len -= n;
305 if (ep & TRANSFER_ZERO)
306 {
307 while (n--)
308 Send8(0);
309 }
310 else if (ep & TRANSFER_PGM)
311 {
312 while (n--)
313 Send8(pgm_read_byte(data++));
314 }
315 else
316 {
317 while (n--)
318 Send8(*data++);
319 }
320
321 if (sendZlp) {
322 ReleaseTX();
323 sendZlp = false;
324 } else if (!ReadWriteAllowed()) { // ...release if buffer is full...
325 ReleaseTX();
326 if (len == 0) sendZlp = true;
327 } else if ((len == 0) && (ep & TRANSFER_RELEASE)) { // ...or if forced with TRANSFER_RELEASE
328 // XXX: TRANSFER_RELEASE is never used can be removed?
329 ReleaseTX();
330 }
331 }
332 }
333 TXLED1; // light the TX LED
334 TxLEDPulse = TX_RX_LED_PULSE_MS;
335 return r;
336 }
337
338 u8 _initEndpoints[USB_ENDPOINTS] =
339 {
340 0, // Control Endpoint
341
342 #ifdef CDC_ENABLED
343 EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM
344 EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT
345 EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN
346 #endif
347
348 // Following endpoints are automatically initialized to 0
349 };
350
351 #define EP_SINGLE_64 0x32 // EP0
352 #define EP_DOUBLE_64 0x36 // Other endpoints
353 #define EP_SINGLE_16 0x12
354
355 static
356 void InitEP(u8 index, u8 type, u8 size)
357 {
358 UENUM = index;
359 UECONX = (1<<EPEN);
360 UECFG0X = type;
361 UECFG1X = size;
362 }
363
364 static
365 void InitEndpoints()
366 {
367 for (u8 i = 1; i < sizeof(_initEndpoints) && _initEndpoints[i] != 0; i++)
368 {
369 UENUM = i;
370 UECONX = (1<<EPEN);
371 UECFG0X = _initEndpoints[i];
372 #if USB_EP_SIZE == 16
373 UECFG1X = EP_SINGLE_16;
374 #elif USB_EP_SIZE == 64
375 UECFG1X = EP_DOUBLE_64;
376 #else
377 #error Unsupported value for USB_EP_SIZE
378 #endif
379 }
380 UERST = 0x7E; // And reset them
381 UERST = 0;
382 }
383
384 // Handle CLASS_INTERFACE requests
385 static
386 bool ClassInterfaceRequest(USBSetup& setup)
387 {
388 #ifdef CDC_ENABLED
389 u8 i = setup.wIndex;
390
391 if (CDC_ACM_INTERFACE == i)
392 return CDC_Setup(setup);
393 #endif
394
395 #ifdef PLUGGABLE_USB_ENABLED
396 return PluggableUSB().setup(setup);
397 #endif
398 return false;
399 }
400
401 static int _cmark;
402 static int _cend;
403 void InitControl(int end)
404 {
405 SetEP(0);
406 _cmark = 0;
407 _cend = end;
408 }
409
410 static
411 bool SendControl(u8 d)
412 {
413 if (_cmark < _cend)
414 {
415 if (!WaitForINOrOUT())
416 return false;
417 Send8(d);
418 if (!((_cmark + 1) & 0x3F))
419 ClearIN(); // Fifo is full, release this packet
420 }
421 _cmark++;
422 return true;
423 }
424
425 // Clipped by _cmark/_cend
426 int USB_SendControl(u8 flags, const void* d, int len)
427 {
428 int sent = len;
429 const u8* data = (const u8*)d;
430 bool pgm = flags & TRANSFER_PGM;
431 while (len--)
432 {
433 u8 c = pgm ? pgm_read_byte(data++) : *data++;
434 if (!SendControl(c))
435 return -1;
436 }
437 return sent;
438 }
439
440 // Send a USB descriptor string. The string is stored in PROGMEM as a
441 // plain ASCII string but is sent out as UTF-16 with the correct 2-byte
442 // prefix
443 static bool USB_SendStringDescriptor(const u8*string_P, u8 string_len, uint8_t flags) {
444 SendControl(2 + string_len * 2);
445 SendControl(3);
446 bool pgm = flags & TRANSFER_PGM;
447 for(u8 i = 0; i < string_len; i++) {
448 bool r = SendControl(pgm ? pgm_read_byte(&string_P[i]) : string_P[i]);
449 r &= SendControl(0); // high byte
450 if(!r) {
451 return false;
452 }
453 }
454 return true;
455 }
456
457 // Does not timeout or cross fifo boundaries
458 int USB_RecvControl(void* d, int len)
459 {
460 auto length = len;
461 while(length)
462 {
463 // Dont receive more than the USB Control EP has to offer
464 // Use fixed 64 because control EP always have 64 bytes even on 16u2.
465 auto recvLength = length;
466 if(recvLength > 64){
467 recvLength = 64;
468 }
469
470 // Write data to fit to the end (not the beginning) of the array
471 WaitOUT();
472 Recv((u8*)d + len - length, recvLength);
473 ClearOUT();
474 length -= recvLength;
475 }
476 return len;
477 }
478
479 static u8 SendInterfaces()
480 {
481 u8 interfaces = 0;
482
483 #ifdef CDC_ENABLED
484 CDC_GetInterface(&interfaces);
485 #endif
486
487 #ifdef PLUGGABLE_USB_ENABLED
488 PluggableUSB().getInterface(&interfaces);
489 #endif
490
491 return interfaces;
492 }
493
494 // Construct a dynamic configuration descriptor
495 // This really needs dynamic endpoint allocation etc
496 // TODO
497 static
498 bool SendConfiguration(int maxlen)
499 {
500 // Count and measure interfaces
501 InitControl(0);
502 u8 interfaces = SendInterfaces();
503 ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces);
504
505 // Now send them
506 InitControl(maxlen);
507 USB_SendControl(0,&config,sizeof(ConfigDescriptor));
508 SendInterfaces();
509 return true;
510 }
511
512 static
513 bool SendDescriptor(USBSetup& setup)
514 {
515 u8 t = setup.wValueH;
516 if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
517 return SendConfiguration(setup.wLength);
518
519 InitControl(setup.wLength);
520 #ifdef PLUGGABLE_USB_ENABLED
521 int ret = PluggableUSB().getDescriptor(setup);
522 if (ret != 0) {
523 return (ret > 0 ? true : false);
524 }
525 #endif
526
527 const u8* desc_addr = 0;
528 if (USB_DEVICE_DESCRIPTOR_TYPE == t)
529 {
530 desc_addr = (const u8*)&USB_DeviceDescriptorIAD;
531 }
532 else if (USB_STRING_DESCRIPTOR_TYPE == t)
533 {
534 if (setup.wValueL == 0) {
535 desc_addr = (const u8*)&STRING_LANGUAGE;
536 }
537 else if (setup.wValueL == IPRODUCT) {
538 return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT), TRANSFER_PGM);
539 }
540 else if (setup.wValueL == IMANUFACTURER) {
541 return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER), TRANSFER_PGM);
542 }
543 else if (setup.wValueL == ISERIAL) {
544 #ifdef PLUGGABLE_USB_ENABLED
545 char name[ISERIAL_MAX_LEN];
546 PluggableUSB().getShortName(name);
547 return USB_SendStringDescriptor((uint8_t*)name, strlen(name), 0);
548 #endif
549 }
550 else
551 return false;
552 }
553
554 if (desc_addr == 0)
555 return false;
556 u8 desc_length = pgm_read_byte(desc_addr);
557
558 USB_SendControl(TRANSFER_PGM,desc_addr,desc_length);
559 return true;
560 }
561
562 // Endpoint 0 interrupt
563 ISR(USB_COM_vect)
564 {
565 SetEP(0);
566 if (!ReceivedSetupInt())
567 return;
568
569 USBSetup setup;
570 Recv((u8*)&setup,8);
571 ClearSetupInt();
572
573 u8 requestType = setup.bmRequestType;
574 if (requestType & REQUEST_DEVICETOHOST)
575 WaitIN();
576 else
577 ClearIN();
578
579 bool ok = true;
580 if (REQUEST_STANDARD == (requestType & REQUEST_TYPE))
581 {
582 // Standard Requests
583 u8 r = setup.bRequest;
584 u16 wValue = setup.wValueL | (setup.wValueH << 8);
585 if (GET_STATUS == r)
586 {
587 if (requestType == (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_DEVICE))
588 {
589 Send8(_usbCurrentStatus);
590 Send8(0);
591 }
592 else
593 {
594 // TODO: handle the HALT state of an endpoint here
595 // see "Figure 9-6. Information Returned by a GetStatus() Request to an Endpoint" in usb_20.pdf for more information
596 Send8(0);
597 Send8(0);
598 }
599 }
600 else if (CLEAR_FEATURE == r)
601 {
602 if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
603 && (wValue == DEVICE_REMOTE_WAKEUP))
604 {
605 _usbCurrentStatus &= ~FEATURE_REMOTE_WAKEUP_ENABLED;
606 }
607 }
608 else if (SET_FEATURE == r)
609 {
610 if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
611 && (wValue == DEVICE_REMOTE_WAKEUP))
612 {
613 _usbCurrentStatus |= FEATURE_REMOTE_WAKEUP_ENABLED;
614 }
615 }
616 else if (SET_ADDRESS == r)
617 {
618 WaitIN();
619 UDADDR = setup.wValueL | (1<<ADDEN);
620 }
621 else if (GET_DESCRIPTOR == r)
622 {
623 ok = SendDescriptor(setup);
624 }
625 else if (SET_DESCRIPTOR == r)
626 {
627 ok = false;
628 }
629 else if (GET_CONFIGURATION == r)
630 {
631 Send8(1);
632 }
633 else if (SET_CONFIGURATION == r)
634 {
635 if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT))
636 {
637 InitEndpoints();
638 _usbConfiguration = setup.wValueL;
639 } else
640 ok = false;
641 }
642 else if (GET_INTERFACE == r)
643 {
644 }
645 else if (SET_INTERFACE == r)
646 {
647 }
648 }
649 else
650 {
651 InitControl(setup.wLength); // Max length of transfer
652 ok = ClassInterfaceRequest(setup);
653 }
654
655 if (ok)
656 ClearIN();
657 else
658 {
659 Stall();
660 }
661 }
662
663 void USB_Flush(u8 ep)
664 {
665 SetEP(ep);
666 if (FifoByteCount())
667 ReleaseTX();
668 }
669
670 static inline void USB_ClockDisable()
671 {
672 #if defined(OTGPADE)
673 USBCON = (USBCON & ~(1<<OTGPADE)) | (1<<FRZCLK); // freeze clock and disable VBUS Pad
674 #else // u2 Series
675 USBCON = (1 << FRZCLK); // freeze clock
676 #endif
677 PLLCSR &= ~(1<<PLLE); // stop PLL
678 }
679
680 static inline void USB_ClockEnable()
681 {
682 #if defined(UHWCON)
683 UHWCON |= (1<<UVREGE); // power internal reg
684 #endif
685 USBCON = (1<<USBE) | (1<<FRZCLK); // clock frozen, usb enabled
686
687 // ATmega32U4
688 #if defined(PINDIV)
689 #if F_CPU == 16000000UL
690 PLLCSR |= (1<<PINDIV); // Need 16 MHz xtal
691 #elif F_CPU == 8000000UL
692 PLLCSR &= ~(1<<PINDIV); // Need 8 MHz xtal
693 #else
694 #error "Clock rate of F_CPU not supported"
695 #endif
696
697 #elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__) || defined(__AVR_ATmega32U2__) || defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega8U2__)
698 // for the u2 Series the datasheet is confusing. On page 40 its called PINDIV and on page 290 its called PLLP0
699 #if F_CPU == 16000000UL
700 // Need 16 MHz xtal
701 PLLCSR |= (1 << PLLP0);
702 #elif F_CPU == 8000000UL
703 // Need 8 MHz xtal
704 PLLCSR &= ~(1 << PLLP0);
705 #endif
706
707 // AT90USB646, AT90USB647, AT90USB1286, AT90USB1287
708 #elif defined(PLLP2)
709 #if F_CPU == 16000000UL
710 #if defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB1287__)
711 // For Atmel AT90USB128x only. Do not use with Atmel AT90USB64x.
712 PLLCSR = (PLLCSR & ~(1<<PLLP1)) | ((1<<PLLP2) | (1<<PLLP0)); // Need 16 MHz xtal
713 #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__)
714 // For AT90USB64x only. Do not use with AT90USB128x.
715 PLLCSR = (PLLCSR & ~(1<<PLLP0)) | ((1<<PLLP2) | (1<<PLLP1)); // Need 16 MHz xtal
716 #else
717 #error "USB Chip not supported, please defined method of USB PLL initialization"
718 #endif
719 #elif F_CPU == 8000000UL
720 // for Atmel AT90USB128x and AT90USB64x
721 PLLCSR = (PLLCSR & ~(1<<PLLP2)) | ((1<<PLLP1) | (1<<PLLP0)); // Need 8 MHz xtal
722 #else
723 #error "Clock rate of F_CPU not supported"
724 #endif
725 #else
726 #error "USB Chip not supported, please defined method of USB PLL initialization"
727 #endif
728
729 PLLCSR |= (1<<PLLE);
730 while (!(PLLCSR & (1<<PLOCK))) // wait for lock pll
731 {
732 }
733
734 // Some tests on specific versions of macosx (10.7.3), reported some
735 // strange behaviors when the board is reset using the serial
736 // port touch at 1200 bps. This delay fixes this behavior.
737 delay(1);
738 #if defined(OTGPADE)
739 USBCON = (USBCON & ~(1<<FRZCLK)) | (1<<OTGPADE); // start USB clock, enable VBUS Pad
740 #else
741 USBCON &= ~(1 << FRZCLK); // start USB clock
742 #endif
743
744 #if defined(RSTCPU)
745 #if defined(LSM)
746 UDCON &= ~((1<<RSTCPU) | (1<<LSM) | (1<<RMWKUP) | (1<<DETACH)); // enable attach resistor, set full speed mode
747 #else // u2 Series
748 UDCON &= ~((1 << RSTCPU) | (1 << RMWKUP) | (1 << DETACH)); // enable attach resistor, set full speed mode
749 #endif
750 #else
751 // AT90USB64x and AT90USB128x don't have RSTCPU
752 UDCON &= ~((1<<LSM) | (1<<RMWKUP) | (1<<DETACH)); // enable attach resistor, set full speed mode
753 #endif
754 }
755
756 // General interrupt
757 ISR(USB_GEN_vect)
758 {
759 u8 udint = UDINT;
760 UDINT &= ~((1<<EORSTI) | (1<<SOFI)); // clear the IRQ flags for the IRQs which are handled here, except WAKEUPI and SUSPI (see below)
761
762 // End of Reset
763 if (udint & (1<<EORSTI))
764 {
765 InitEP(0,EP_TYPE_CONTROL,EP_SINGLE_64); // init ep0
766 _usbConfiguration = 0; // not configured yet
767 UEIENX = 1 << RXSTPE; // Enable interrupts for ep0
768 }
769
770 // Start of Frame - happens every millisecond so we use it for TX and RX LED one-shot timing, too
771 if (udint & (1<<SOFI))
772 {
773 USB_Flush(CDC_TX); // Send a tx frame if found
774
775 // check whether the one-shot period has elapsed. if so, turn off the LED
776 if (TxLEDPulse && !(--TxLEDPulse))
777 TXLED0;
778 if (RxLEDPulse && !(--RxLEDPulse))
779 RXLED0;
780 }
781
782 // the WAKEUPI interrupt is triggered as soon as there are non-idle patterns on the data
783 // lines. Thus, the WAKEUPI interrupt can occur even if the controller is not in the "suspend" mode.
784 // Therefore the we enable it only when USB is suspended
785 if (udint & (1<<WAKEUPI))
786 {
787 UDIEN = (UDIEN & ~(1<<WAKEUPE)) | (1<<SUSPE); // Disable interrupts for WAKEUP and enable interrupts for SUSPEND
788
789 //TODO
790 // WAKEUPI shall be cleared by software (USB clock inputs must be enabled before).
791 //USB_ClockEnable();
792 UDINT &= ~(1<<WAKEUPI);
793 _usbSuspendState = (_usbSuspendState & ~(1<<SUSPI)) | (1<<WAKEUPI);
794 }
795 else if (udint & (1<<SUSPI)) // only one of the WAKEUPI / SUSPI bits can be active at time
796 {
797 UDIEN = (UDIEN & ~(1<<SUSPE)) | (1<<WAKEUPE); // Disable interrupts for SUSPEND and enable interrupts for WAKEUP
798
799 //TODO
800 //USB_ClockDisable();
801
802 UDINT &= ~((1<<WAKEUPI) | (1<<SUSPI)); // clear any already pending WAKEUP IRQs and the SUSPI request
803 _usbSuspendState = (_usbSuspendState & ~(1<<WAKEUPI)) | (1<<SUSPI);
804 }
805 }
806
807 // VBUS or counting frames
808 // Any frame counting?
809 u8 USBConnected()
810 {
811 u8 f = UDFNUML;
812 delay(3);
813 return f != UDFNUML;
814 }
815
816 //=======================================================================
817 //=======================================================================
818
819 USBDevice_ USBDevice;
820
821 USBDevice_::USBDevice_()
822 {
823 }
824
825 void USBDevice_::attach()
826 {
827 _usbConfiguration = 0;
828 _usbCurrentStatus = 0;
829 _usbSuspendState = 0;
830 USB_ClockEnable();
831
832 UDINT &= ~((1<<WAKEUPI) | (1<<SUSPI)); // clear already pending WAKEUP / SUSPEND requests
833 UDIEN = (1<<EORSTE) | (1<<SOFE) | (1<<SUSPE); // Enable interrupts for EOR (End of Reset), SOF (start of frame) and SUSPEND
834
835 TX_RX_LED_INIT;
836 }
837
838 void USBDevice_::detach()
839 {
840 }
841
842 // Check for interrupts
843 // TODO: VBUS detection
844 bool USBDevice_::configured()
845 {
846 return _usbConfiguration;
847 }
848
849 void USBDevice_::poll()
850 {
851 }
852
853 bool USBDevice_::wakeupHost()
854 {
855 // clear any previous wakeup request which might have been set but could be processed at that time
856 // e.g. because the host was not suspended at that time
857 UDCON &= ~(1 << RMWKUP);
858
859 if(!(UDCON & (1 << RMWKUP))
860 && (_usbSuspendState & (1<<SUSPI))
861 && (_usbCurrentStatus & FEATURE_REMOTE_WAKEUP_ENABLED))
862 {
863 // This short version will only work, when the device has not been suspended. Currently the
864 // Arduino core doesn't handle SUSPEND at all, so this is ok.
865 USB_ClockEnable();
866 UDCON |= (1 << RMWKUP); // send the wakeup request
867 return true;
868 }
869
870 return false;
871 }
872
873 bool USBDevice_::isSuspended()
874 {
875 return (_usbSuspendState & (1 << SUSPI));
876 }
877
878
879 #endif /* if defined(USBCON) */