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