Index

auto-plow / 83d2e4a

A wheelchair motor-propelled battery-powered ESP32-driven remote control snow plow.

Latest Commit

{#}TimeHashSubjectAuthor#(+)(-)GPG?
630 Nov 2018 18:364a63c8cInclude Arduino core filesJoshua18580N

Blob @ auto-plow / include / arduino / USBCore.cpp

text/plain19916 bytesdownload 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
28volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */
29volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */
30
31//==================================================================
32//==================================================================
33
34extern const u16 STRING_LANGUAGE[] PROGMEM;
35extern const u8 STRING_PRODUCT[] PROGMEM;
36extern const u8 STRING_MANUFACTURER[] PROGMEM;
37extern const DeviceDescriptor USB_DeviceDescriptorIAD PROGMEM;
38
39const 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
49const 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
66const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER;
67
68
69#define DEVICE_CLASS 0x02
70
71// DEVICE DESCRIPTOR
72const DeviceDescriptor USB_DeviceDescriptorIAD =
73 D_DEVICE(0xEF,0x02,0x01,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,ISERIAL,1);
74
75//==================================================================
76//==================================================================
77
78volatile u8 _usbConfiguration = 0;
79volatile u8 _usbCurrentStatus = 0; // meaning of bits see usb_20.pdf, Figure 9-4. Information Returned by a GetStatus() Request to a Device
80volatile u8 _usbSuspendState = 0; // copy of UDINT to check SUSPI and WAKEUPI bits
81
82static inline void WaitIN(void)
83{
84 while (!(UEINTX & (1<<TXINI)))
85 ;
86}
87
88static inline void ClearIN(void)
89{
90 UEINTX = ~(1<<TXINI);
91}
92
93static inline void WaitOUT(void)
94{
95 while (!(UEINTX & (1<<RXOUTI)))
96 ;
97}
98
99static inline u8 WaitForINOrOUT()
100{
101 while (!(UEINTX & ((1<<TXINI)|(1<<RXOUTI))))
102 ;
103 return (UEINTX & (1<<RXOUTI)) == 0;
104}
105
106static inline void ClearOUT(void)
107{
108 UEINTX = ~(1<<RXOUTI);
109}
110
111static 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
120static inline u8 Recv8()
121{
122 RXLED1; // light the RX LED
123 RxLEDPulse = TX_RX_LED_PULSE_MS;
124
125 return UEDATX;
126}
127
128static inline void Send8(u8 d)
129{
130 UEDATX = d;
131}
132
133static inline void SetEP(u8 ep)
134{
135 UENUM = ep;
136}
137
138static inline u8 FifoByteCount()
139{
140 return UEBCLX;
141}
142
143static inline u8 ReceivedSetupInt()
144{
145 return UEINTX & (1<<RXSTPI);
146}
147
148static inline void ClearSetupInt()
149{
150 UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
151}
152
153static inline void Stall()
154{
155 UECONX = (1<<STALLRQ) | (1<<EPEN);
156}
157
158static inline u8 ReadWriteAllowed()
159{
160 return UEINTX & (1<<RWAL);
161}
162
163static inline u8 Stalled()
164{
165 return UEINTX & (1<<STALLEDI);
166}
167
168static inline u8 FifoFree()
169{
170 return UEINTX & (1<<FIFOCON);
171}
172
173static 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
178static 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
183static inline u8 FrameNumber()
184{
185 return UDFNUML;
186}
187
188//==================================================================
189//==================================================================
190
191u8 USBGetConfiguration(void)
192{
193 return _usbConfiguration;
194}
195
196#define USB_RECV_TIMEOUT
197class LockEP
198{
199 u8 _sreg;
200public:
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
213u8 USB_Available(u8 ep)
214{
215 LockEP lock(ep);
216 return FifoByteCount();
217}
218
219// Non Blocking receive
220// Return number of bytes read
221int 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
240int 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
249u8 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
258int 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
328u8 _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
343static
344void InitEP(u8 index, u8 type, u8 size)
345{
346 UENUM = index;
347 UECONX = (1<<EPEN);
348 UECFG0X = type;
349 UECFG1X = size;
350}
351
352static
353void 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
373static
374bool 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
387static int _cmark;
388static int _cend;
389void InitControl(int end)
390{
391 SetEP(0);
392 _cmark = 0;
393 _cend = end;
394}
395
396static
397bool 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
412int 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
429static 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
444int 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
465static 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
481static
482bool 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
496static
497bool SendDescriptor(USBSetup& setup)
498{
499 int ret;
500 u8 t = setup.wValueH;
501 if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
502 return SendConfiguration(setup.wLength);
503
504 InitControl(setup.wLength);
505#ifdef PLUGGABLE_USB_ENABLED
506 ret = PluggableUSB().getDescriptor(setup);
507 if (ret != 0) {
508 return (ret > 0 ? true : false);
509 }
510#endif
511
512 const u8* desc_addr = 0;
513 if (USB_DEVICE_DESCRIPTOR_TYPE == t)
514 {
515 desc_addr = (const u8*)&USB_DeviceDescriptorIAD;
516 }
517 else if (USB_STRING_DESCRIPTOR_TYPE == t)
518 {
519 if (setup.wValueL == 0) {
520 desc_addr = (const u8*)&STRING_LANGUAGE;
521 }
522 else if (setup.wValueL == IPRODUCT) {
523 return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT), TRANSFER_PGM);
524 }
525 else if (setup.wValueL == IMANUFACTURER) {
526 return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER), TRANSFER_PGM);
527 }
528 else if (setup.wValueL == ISERIAL) {
529#ifdef PLUGGABLE_USB_ENABLED
530 char name[ISERIAL_MAX_LEN];
531 PluggableUSB().getShortName(name);
532 return USB_SendStringDescriptor((uint8_t*)name, strlen(name), 0);
533#endif
534 }
535 else
536 return false;
537 }
538
539 if (desc_addr == 0)
540 return false;
541 u8 desc_length = pgm_read_byte(desc_addr);
542
543 USB_SendControl(TRANSFER_PGM,desc_addr,desc_length);
544 return true;
545}
546
547// Endpoint 0 interrupt
548ISR(USB_COM_vect)
549{
550 SetEP(0);
551 if (!ReceivedSetupInt())
552 return;
553
554 USBSetup setup;
555 Recv((u8*)&setup,8);
556 ClearSetupInt();
557
558 u8 requestType = setup.bmRequestType;
559 if (requestType & REQUEST_DEVICETOHOST)
560 WaitIN();
561 else
562 ClearIN();
563
564 bool ok = true;
565 if (REQUEST_STANDARD == (requestType & REQUEST_TYPE))
566 {
567 // Standard Requests
568 u8 r = setup.bRequest;
569 u16 wValue = setup.wValueL | (setup.wValueH << 8);
570 if (GET_STATUS == r)
571 {
572 if (requestType == (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_DEVICE))
573 {
574 Send8(_usbCurrentStatus);
575 Send8(0);
576 }
577 else
578 {
579 // TODO: handle the HALT state of an endpoint here
580 // see "Figure 9-6. Information Returned by a GetStatus() Request to an Endpoint" in usb_20.pdf for more information
581 Send8(0);
582 Send8(0);
583 }
584 }
585 else if (CLEAR_FEATURE == r)
586 {
587 if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
588 && (wValue == DEVICE_REMOTE_WAKEUP))
589 {
590 _usbCurrentStatus &= ~FEATURE_REMOTE_WAKEUP_ENABLED;
591 }
592 }
593 else if (SET_FEATURE == r)
594 {
595 if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
596 && (wValue == DEVICE_REMOTE_WAKEUP))
597 {
598 _usbCurrentStatus |= FEATURE_REMOTE_WAKEUP_ENABLED;
599 }
600 }
601 else if (SET_ADDRESS == r)
602 {
603 WaitIN();
604 UDADDR = setup.wValueL | (1<<ADDEN);
605 }
606 else if (GET_DESCRIPTOR == r)
607 {
608 ok = SendDescriptor(setup);
609 }
610 else if (SET_DESCRIPTOR == r)
611 {
612 ok = false;
613 }
614 else if (GET_CONFIGURATION == r)
615 {
616 Send8(1);
617 }
618 else if (SET_CONFIGURATION == r)
619 {
620 if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT))
621 {
622 InitEndpoints();
623 _usbConfiguration = setup.wValueL;
624 } else
625 ok = false;
626 }
627 else if (GET_INTERFACE == r)
628 {
629 }
630 else if (SET_INTERFACE == r)
631 {
632 }
633 }
634 else
635 {
636 InitControl(setup.wLength); // Max length of transfer
637 ok = ClassInterfaceRequest(setup);
638 }
639
640 if (ok)
641 ClearIN();
642 else
643 {
644 Stall();
645 }
646}
647
648void USB_Flush(u8 ep)
649{
650 SetEP(ep);
651 if (FifoByteCount())
652 ReleaseTX();
653}
654
655static inline void USB_ClockDisable()
656{
657#if defined(OTGPADE)
658 USBCON = (USBCON & ~(1<<OTGPADE)) | (1<<FRZCLK); // freeze clock and disable VBUS Pad
659#else // u2 Series
660 USBCON = (1 << FRZCLK); // freeze clock
661#endif
662 PLLCSR &= ~(1<<PLLE); // stop PLL
663}
664
665static inline void USB_ClockEnable()
666{
667#if defined(UHWCON)
668 UHWCON |= (1<<UVREGE); // power internal reg
669#endif
670 USBCON = (1<<USBE) | (1<<FRZCLK); // clock frozen, usb enabled
671
672// ATmega32U4
673#if defined(PINDIV)
674#if F_CPU == 16000000UL
675 PLLCSR |= (1<<PINDIV); // Need 16 MHz xtal
676#elif F_CPU == 8000000UL
677 PLLCSR &= ~(1<<PINDIV); // Need 8 MHz xtal
678#else
679#error "Clock rate of F_CPU not supported"
680#endif
681
682#elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__) || defined(__AVR_ATmega32U2__) || defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega8U2__)
683 // for the u2 Series the datasheet is confusing. On page 40 its called PINDIV and on page 290 its called PLLP0
684#if F_CPU == 16000000UL
685 // Need 16 MHz xtal
686 PLLCSR |= (1 << PLLP0);
687#elif F_CPU == 8000000UL
688 // Need 8 MHz xtal
689 PLLCSR &= ~(1 << PLLP0);
690#endif
691
692// AT90USB646, AT90USB647, AT90USB1286, AT90USB1287
693#elif defined(PLLP2)
694#if F_CPU == 16000000UL
695#if defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB1287__)
696 // For Atmel AT90USB128x only. Do not use with Atmel AT90USB64x.
697 PLLCSR = (PLLCSR & ~(1<<PLLP1)) | ((1<<PLLP2) | (1<<PLLP0)); // Need 16 MHz xtal
698#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__)
699 // For AT90USB64x only. Do not use with AT90USB128x.
700 PLLCSR = (PLLCSR & ~(1<<PLLP0)) | ((1<<PLLP2) | (1<<PLLP1)); // Need 16 MHz xtal
701#else
702#error "USB Chip not supported, please defined method of USB PLL initialization"
703#endif
704#elif F_CPU == 8000000UL
705 // for Atmel AT90USB128x and AT90USB64x
706 PLLCSR = (PLLCSR & ~(1<<PLLP2)) | ((1<<PLLP1) | (1<<PLLP0)); // Need 8 MHz xtal
707#else
708#error "Clock rate of F_CPU not supported"
709#endif
710#else
711#error "USB Chip not supported, please defined method of USB PLL initialization"
712#endif
713
714 PLLCSR |= (1<<PLLE);
715 while (!(PLLCSR & (1<<PLOCK))) // wait for lock pll
716 {
717 }
718
719 // Some tests on specific versions of macosx (10.7.3), reported some
720 // strange behaviors when the board is reset using the serial
721 // port touch at 1200 bps. This delay fixes this behavior.
722 delay(1);
723#if defined(OTGPADE)
724 USBCON = (USBCON & ~(1<<FRZCLK)) | (1<<OTGPADE); // start USB clock, enable VBUS Pad
725#else
726 USBCON &= ~(1 << FRZCLK); // start USB clock
727#endif
728
729#if defined(RSTCPU)
730#if defined(LSM)
731 UDCON &= ~((1<<RSTCPU) | (1<<LSM) | (1<<RMWKUP) | (1<<DETACH)); // enable attach resistor, set full speed mode
732#else // u2 Series
733 UDCON &= ~((1 << RSTCPU) | (1 << RMWKUP) | (1 << DETACH)); // enable attach resistor, set full speed mode
734#endif
735#else
736 // AT90USB64x and AT90USB128x don't have RSTCPU
737 UDCON &= ~((1<<LSM) | (1<<RMWKUP) | (1<<DETACH)); // enable attach resistor, set full speed mode
738#endif
739}
740
741// General interrupt
742ISR(USB_GEN_vect)
743{
744 u8 udint = UDINT;
745 UDINT &= ~((1<<EORSTI) | (1<<SOFI)); // clear the IRQ flags for the IRQs which are handled here, except WAKEUPI and SUSPI (see below)
746
747 // End of Reset
748 if (udint & (1<<EORSTI))
749 {
750 InitEP(0,EP_TYPE_CONTROL,EP_SINGLE_64); // init ep0
751 _usbConfiguration = 0; // not configured yet
752 UEIENX = 1 << RXSTPE; // Enable interrupts for ep0
753 }
754
755 // Start of Frame - happens every millisecond so we use it for TX and RX LED one-shot timing, too
756 if (udint & (1<<SOFI))
757 {
758 USB_Flush(CDC_TX); // Send a tx frame if found
759
760 // check whether the one-shot period has elapsed. if so, turn off the LED
761 if (TxLEDPulse && !(--TxLEDPulse))
762 TXLED0;
763 if (RxLEDPulse && !(--RxLEDPulse))
764 RXLED0;
765 }
766
767 // the WAKEUPI interrupt is triggered as soon as there are non-idle patterns on the data
768 // lines. Thus, the WAKEUPI interrupt can occur even if the controller is not in the "suspend" mode.
769 // Therefore the we enable it only when USB is suspended
770 if (udint & (1<<WAKEUPI))
771 {
772 UDIEN = (UDIEN & ~(1<<WAKEUPE)) | (1<<SUSPE); // Disable interrupts for WAKEUP and enable interrupts for SUSPEND
773
774 //TODO
775 // WAKEUPI shall be cleared by software (USB clock inputs must be enabled before).
776 //USB_ClockEnable();
777 UDINT &= ~(1<<WAKEUPI);
778 _usbSuspendState = (_usbSuspendState & ~(1<<SUSPI)) | (1<<WAKEUPI);
779 }
780 else if (udint & (1<<SUSPI)) // only one of the WAKEUPI / SUSPI bits can be active at time
781 {
782 UDIEN = (UDIEN & ~(1<<SUSPE)) | (1<<WAKEUPE); // Disable interrupts for SUSPEND and enable interrupts for WAKEUP
783
784 //TODO
785 //USB_ClockDisable();
786
787 UDINT &= ~((1<<WAKEUPI) | (1<<SUSPI)); // clear any already pending WAKEUP IRQs and the SUSPI request
788 _usbSuspendState = (_usbSuspendState & ~(1<<WAKEUPI)) | (1<<SUSPI);
789 }
790}
791
792// VBUS or counting frames
793// Any frame counting?
794u8 USBConnected()
795{
796 u8 f = UDFNUML;
797 delay(3);
798 return f != UDFNUML;
799}
800
801//=======================================================================
802//=======================================================================
803
804USBDevice_ USBDevice;
805
806USBDevice_::USBDevice_()
807{
808}
809
810void USBDevice_::attach()
811{
812 _usbConfiguration = 0;
813 _usbCurrentStatus = 0;
814 _usbSuspendState = 0;
815 USB_ClockEnable();
816
817 UDINT &= ~((1<<WAKEUPI) | (1<<SUSPI)); // clear already pending WAKEUP / SUSPEND requests
818 UDIEN = (1<<EORSTE) | (1<<SOFE) | (1<<SUSPE); // Enable interrupts for EOR (End of Reset), SOF (start of frame) and SUSPEND
819
820 TX_RX_LED_INIT;
821}
822
823void USBDevice_::detach()
824{
825}
826
827// Check for interrupts
828// TODO: VBUS detection
829bool USBDevice_::configured()
830{
831 return _usbConfiguration;
832}
833
834void USBDevice_::poll()
835{
836}
837
838bool USBDevice_::wakeupHost()
839{
840 // clear any previous wakeup request which might have been set but could be processed at that time
841 // e.g. because the host was not suspended at that time
842 UDCON &= ~(1 << RMWKUP);
843
844 if(!(UDCON & (1 << RMWKUP))
845 && (_usbSuspendState & (1<<SUSPI))
846 && (_usbCurrentStatus & FEATURE_REMOTE_WAKEUP_ENABLED))
847 {
848 // This short version will only work, when the device has not been suspended. Currently the
849 // Arduino core doesn't handle SUSPEND at all, so this is ok.
850 USB_ClockEnable();
851 UDCON |= (1 << RMWKUP); // send the wakeup request
852 return true;
853 }
854
855 return false;
856}
857
858#endif /* if defined(USBCON) */
859