]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/pjrcUSB/avr/usb_keyboard_serial.c
Adding McHCK flash reload function and some cleanup.
[kiibohd-controller.git] / Output / pjrcUSB / avr / usb_keyboard_serial.c
1 /* USB Keyboard and CDC Serial Device for Teensy USB Development Board
2  * Copyright (c) 2009 PJRC.COM, LLC
3  * Modifications by Jacob Alexander (2011-2014)
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to deal
7  * in the Software without restriction, including without limitation the rights
8  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9  * copies of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21  * THE SOFTWARE.
22  */
23
24
25 // Local Includes
26 #include "usb_keyboard_serial.h"
27
28
29 // ----- Variables -----
30
31 // zero when we are not configured, non-zero when enumerated
32 static volatile uint8_t usb_configuration = 0;
33
34 // the time remaining before we transmit any partially full
35 // packet, or send a zero length packet.
36 static volatile uint8_t transmit_flush_timer = 0;
37 static uint8_t transmit_previous_timeout = 0;
38
39 // serial port settings (baud rate, control signals, etc) set
40 // by the PC.  These are ignored, but kept in RAM.
41 static uint8_t cdc_line_coding[7] = {0x00, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x08};
42 static uint8_t cdc_line_rtsdtr = 0;
43
44
45
46 // ----- USB Keyboard Functions -----
47
48 // Sends normal keyboard out to host
49 // NOTE: Make sure to match the descriptor
50 void usb_keyboard_toHost()
51 {
52         uint8_t i;
53
54         // Modifiers
55         UEDATX = USBKeys_Modifiers;
56
57         // Normal Keys
58         for ( i = 0; i < 6; i++)
59         {
60                 UEDATX = USBKeys_Array[i];
61         }
62         UEINTX = 0x3A;
63 }
64
65 // Sends NKRO keyboard out to host
66 // NOTE: Make sure to match the descriptor
67 void usb_nkrokeyboard_toHost()
68 {
69         uint8_t i;
70
71         // Modifiers
72         /*
73         UEDATX = 0x02;
74         UEDATX = USBKeys_Modifiers;
75         UEINTX = 0x3A;
76         */
77
78         // Media Keys
79         UEDATX = 0x03;
80         UEDATX = 0;
81         UEINTX = 0x3A;
82
83         // Normal Keys
84         UEDATX = 0x04;
85         for ( i = 0; i < 6; i++)
86         {
87                 UEDATX = USBKeys_Array[i];
88         }
89         UEINTX = 0x3A;
90 }
91
92 // send the contents of USBKeys_Array and USBKeys_Modifiers
93 int8_t usb_keyboard_send()
94 {
95         uint8_t intr_state, timeout;
96
97         intr_state = SREG;
98         timeout = UDFNUML + 50;
99
100         // Ready to transmit keypresses?
101         do
102         {
103                 SREG = intr_state;
104
105                 // has the USB gone offline? or exceeded timeout?
106                 if ( !usb_configuration || UDFNUML == timeout )
107                         return -1;
108
109                 // get ready to try checking again
110                 intr_state = SREG;
111                 cli();
112
113                 // If not using Boot protocol, send NKRO
114                 UENUM = USBKeys_Protocol ? KEYBOARD_NKRO_ENDPOINT : KEYBOARD_ENDPOINT;
115         } while ( !( UEINTX & (1 << RWAL) ) );
116
117         // Send normal keyboard interrupt packet(s)
118         switch ( USBKeys_Protocol )
119         {
120         }
121         usb_keyboard_toHost();
122
123         USBKeys_Idle_Count = 0;
124         SREG = intr_state;
125         return 0;
126 }
127
128
129
130 // ----- USB Virtual Serial Port (CDC) Functions -----
131
132 // get the next character, or -1 if nothing received
133 int16_t usb_serial_getchar(void)
134 {
135         uint8_t c, intr_state;
136
137         // interrupts are disabled so these functions can be
138         // used from the main program or interrupt context,
139         // even both in the same program!
140         intr_state = SREG;
141         cli();
142         if (!usb_configuration) {
143                 SREG = intr_state;
144                 return -1;
145         }
146         UENUM = CDC_RX_ENDPOINT;
147         retry:
148         c = UEINTX;
149         if (!(c & (1<<RWAL))) {
150                 // no data in buffer
151                 if (c & (1<<RXOUTI)) {
152                         UEINTX = 0x6B;
153                         goto retry;
154                 }
155                 SREG = intr_state;
156                 return -2;
157         }
158         // take one byte out of the buffer
159         c = UEDATX;
160         // if buffer completely used, release it
161         if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
162         SREG = intr_state;
163         return c;
164 }
165
166 // number of bytes available in the receive buffer
167 uint8_t usb_serial_available(void)
168 {
169         uint8_t n=0, i, intr_state;
170
171         intr_state = SREG;
172         cli();
173         if (usb_configuration) {
174                 UENUM = CDC_RX_ENDPOINT;
175                 n = UEBCLX;
176                 if (!n) {
177                         i = UEINTX;
178                         if (i & (1<<RXOUTI) && !(i & (1<<RWAL))) UEINTX = 0x6B;
179                 }
180         }
181         SREG = intr_state;
182         return n;
183 }
184
185 // discard any buffered input
186 void usb_serial_flush_input(void)
187 {
188         uint8_t intr_state;
189
190         if (usb_configuration) {
191                 intr_state = SREG;
192                 cli();
193                 UENUM = CDC_RX_ENDPOINT;
194                 while ((UEINTX & (1<<RWAL))) {
195                         UEINTX = 0x6B;
196                 }
197                 SREG = intr_state;
198         }
199 }
200
201 // transmit a character.  0 returned on success, -1 on error
202 int8_t usb_serial_putchar(uint8_t c)
203 {
204         uint8_t timeout, intr_state;
205
206         // if we're not online (enumerated and configured), error
207         if (!usb_configuration) return -1;
208         // interrupts are disabled so these functions can be
209         // used from the main program or interrupt context,
210         // even both in the same program!
211         intr_state = SREG;
212         cli();
213         UENUM = CDC_TX_ENDPOINT;
214         // if we gave up due to timeout before, don't wait again
215         if (transmit_previous_timeout) {
216                 if (!(UEINTX & (1<<RWAL))) {
217                         SREG = intr_state;
218                         return -1;
219                 }
220                 transmit_previous_timeout = 0;
221         }
222         // wait for the FIFO to be ready to accept data
223         timeout = UDFNUML + TRANSMIT_TIMEOUT;
224         while (1) {
225                 // are we ready to transmit?
226                 if (UEINTX & (1<<RWAL)) break;
227                 SREG = intr_state;
228                 // have we waited too long?  This happens if the user
229                 // is not running an application that is listening
230                 if (UDFNUML == timeout) {
231                         transmit_previous_timeout = 1;
232                         return -1;
233                 }
234                 // has the USB gone offline?
235                 if (!usb_configuration) return -1;
236                 // get ready to try checking again
237                 intr_state = SREG;
238                 cli();
239                 UENUM = CDC_TX_ENDPOINT;
240         }
241         // actually write the byte into the FIFO
242         UEDATX = c;
243         // if this completed a packet, transmit it now!
244         if (!(UEINTX & (1<<RWAL))) UEINTX = 0x3A;
245         transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
246         SREG = intr_state;
247         return 0;
248 }
249
250
251 // transmit a character, but do not wait if the buffer is full,
252 //   0 returned on success, -1 on buffer full or error
253 int8_t usb_serial_putchar_nowait(uint8_t c)
254 {
255         uint8_t intr_state;
256
257         if (!usb_configuration) return -1;
258         intr_state = SREG;
259         cli();
260         UENUM = CDC_TX_ENDPOINT;
261         if (!(UEINTX & (1<<RWAL))) {
262                 // buffer is full
263                 SREG = intr_state;
264                 return -2;
265         }
266         // actually write the byte into the FIFO
267         UEDATX = c;
268                 // if this completed a packet, transmit it now!
269         if (!(UEINTX & (1<<RWAL))) UEINTX = 0x3A;
270         transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
271         SREG = intr_state;
272         return 0;
273 }
274
275 // transmit a buffer.
276 //  0 returned on success, -1 on error
277 // This function is optimized for speed!  Each call takes approx 6.1 us overhead
278 // plus 0.25 us per byte.  12 Mbit/sec USB has 8.67 us per-packet overhead and
279 // takes 0.67 us per byte.  If called with 64 byte packet-size blocks, this function
280 // can transmit at full USB speed using 43% CPU time.  The maximum theoretical speed
281 // is 19 packets per USB frame, or 1216 kbytes/sec.  However, bulk endpoints have the
282 // lowest priority, so any other USB devices will likely reduce the speed.  Speed
283 // can also be limited by how quickly the PC-based software reads data, as the host
284 // controller in the PC will not allocate bandwitdh without a pending read request.
285 // (thanks to Victor Suarez for testing and feedback and initial code)
286
287 int8_t usb_serial_write(const char *buffer, uint16_t size)
288 {
289         uint8_t timeout, intr_state, write_size;
290
291         // if we're not online (enumerated and configured), error
292         if (!usb_configuration) return -1;
293         // interrupts are disabled so these functions can be
294         // used from the main program or interrupt context,
295         // even both in the same program!
296         intr_state = SREG;
297         cli();
298         UENUM = CDC_TX_ENDPOINT;
299         // if we gave up due to timeout before, don't wait again
300         /*
301         if (transmit_previous_timeout) {
302                 if (!(UEINTX & (1<<RWAL))) {
303                         SREG = intr_state;
304                         return -2;
305                 }
306                 transmit_previous_timeout = 0;
307         }
308         */
309         // each iteration of this loop transmits a packet
310         while (size) {
311                 // wait for the FIFO to be ready to accept data
312                 timeout = UDFNUML + TRANSMIT_TIMEOUT;
313                 while (1) {
314                         // are we ready to transmit?
315                         if (UEINTX & (1<<RWAL)) break;
316                         SREG = intr_state;
317                         // have we waited too long?  This happens if the user
318                         // is not running an application that is listening
319                         if (UDFNUML == timeout) {
320                                 transmit_previous_timeout = 1;
321                                 return -3;
322                         }
323                         // has the USB gone offline?
324                         if (!usb_configuration) return -4;
325                         // get ready to try checking again
326                         intr_state = SREG;
327                         cli();
328                         UENUM = CDC_TX_ENDPOINT;
329                 }
330
331                 // compute how many bytes will fit into the next packet
332                 write_size = CDC_TX_SIZE - UEBCLX;
333                 if (write_size > size) write_size = size;
334                 size -= write_size;
335
336                 // write the packet
337                 switch (write_size) {
338                         #if (CDC_TX_SIZE == 64)
339                         case 64: UEDATX = *buffer++;
340                         case 63: UEDATX = *buffer++;
341                         case 62: UEDATX = *buffer++;
342                         case 61: UEDATX = *buffer++;
343                         case 60: UEDATX = *buffer++;
344                         case 59: UEDATX = *buffer++;
345                         case 58: UEDATX = *buffer++;
346                         case 57: UEDATX = *buffer++;
347                         case 56: UEDATX = *buffer++;
348                         case 55: UEDATX = *buffer++;
349                         case 54: UEDATX = *buffer++;
350                         case 53: UEDATX = *buffer++;
351                         case 52: UEDATX = *buffer++;
352                         case 51: UEDATX = *buffer++;
353                         case 50: UEDATX = *buffer++;
354                         case 49: UEDATX = *buffer++;
355                         case 48: UEDATX = *buffer++;
356                         case 47: UEDATX = *buffer++;
357                         case 46: UEDATX = *buffer++;
358                         case 45: UEDATX = *buffer++;
359                         case 44: UEDATX = *buffer++;
360                         case 43: UEDATX = *buffer++;
361                         case 42: UEDATX = *buffer++;
362                         case 41: UEDATX = *buffer++;
363                         case 40: UEDATX = *buffer++;
364                         case 39: UEDATX = *buffer++;
365                         case 38: UEDATX = *buffer++;
366                         case 37: UEDATX = *buffer++;
367                         case 36: UEDATX = *buffer++;
368                         case 35: UEDATX = *buffer++;
369                         case 34: UEDATX = *buffer++;
370                         case 33: UEDATX = *buffer++;
371                         #endif
372                         #if (CDC_TX_SIZE >= 32)
373                         case 32: UEDATX = *buffer++;
374                         case 31: UEDATX = *buffer++;
375                         case 30: UEDATX = *buffer++;
376                         case 29: UEDATX = *buffer++;
377                         case 28: UEDATX = *buffer++;
378                         case 27: UEDATX = *buffer++;
379                         case 26: UEDATX = *buffer++;
380                         case 25: UEDATX = *buffer++;
381                         case 24: UEDATX = *buffer++;
382                         case 23: UEDATX = *buffer++;
383                         case 22: UEDATX = *buffer++;
384                         case 21: UEDATX = *buffer++;
385                         case 20: UEDATX = *buffer++;
386                         case 19: UEDATX = *buffer++;
387                         case 18: UEDATX = *buffer++;
388                         case 17: UEDATX = *buffer++;
389                         #endif
390                         #if (CDC_TX_SIZE >= 16)
391                         case 16: UEDATX = *buffer++;
392                         case 15: UEDATX = *buffer++;
393                         case 14: UEDATX = *buffer++;
394                         case 13: UEDATX = *buffer++;
395                         case 12: UEDATX = *buffer++;
396                         case 11: UEDATX = *buffer++;
397                         case 10: UEDATX = *buffer++;
398                         case  9: UEDATX = *buffer++;
399                         #endif
400                         case  8: UEDATX = *buffer++;
401                         case  7: UEDATX = *buffer++;
402                         case  6: UEDATX = *buffer++;
403                         case  5: UEDATX = *buffer++;
404                         case  4: UEDATX = *buffer++;
405                         case  3: UEDATX = *buffer++;
406                         case  2: UEDATX = *buffer++;
407                         default:
408                         case  1: UEDATX = *buffer++;
409                         case  0: break;
410                 }
411                 // if this completed a packet, transmit it now!
412                 if (!(UEINTX & (1<<RWAL))) UEINTX = 0x3A;
413                 transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
414                 SREG = intr_state;
415         }
416         return 0;
417 }
418
419 // immediately transmit any buffered output.
420 // This doesn't actually transmit the data - that is impossible!
421 // USB devices only transmit when the host allows, so the best
422 // we can do is release the FIFO buffer for when the host wants it
423 void usb_serial_flush_output(void)
424 {
425         uint8_t intr_state;
426
427         intr_state = SREG;
428         cli();
429         if (transmit_flush_timer) {
430                 UENUM = CDC_TX_ENDPOINT;
431                 UEINTX = 0x3A;
432                 transmit_flush_timer = 0;
433         }
434         SREG = intr_state;
435 }
436
437 // functions to read the various async serial settings.  These
438 // aren't actually used by USB at all (communication is always
439 // at full USB speed), but they are set by the host so we can
440 // set them properly if we're converting the USB to a real serial
441 // communication
442 uint32_t usb_serial_get_baud(void)
443 {
444         uint32_t *baud = (uint32_t*)cdc_line_coding;
445         return *baud;
446 }
447 uint8_t usb_serial_get_stopbits(void)
448 {
449         return cdc_line_coding[4];
450 }
451 uint8_t usb_serial_get_paritytype(void)
452 {
453         return cdc_line_coding[5];
454 }
455 uint8_t usb_serial_get_numbits(void)
456 {
457         return cdc_line_coding[6];
458 }
459 uint8_t usb_serial_get_control(void)
460 {
461         return cdc_line_rtsdtr;
462 }
463
464 // write the control signals, DCD, DSR, RI, etc
465 // There is no CTS signal.  If software on the host has transmitted
466 // data to you but you haven't been calling the getchar function,
467 // it remains buffered (either here or on the host) and can not be
468 // lost because you weren't listening at the right time, like it
469 // would in real serial communication.
470 int8_t usb_serial_set_control(uint8_t signals)
471 {
472         uint8_t intr_state;
473
474         intr_state = SREG;
475         cli();
476         if (!usb_configuration) {
477                 // we're not enumerated/configured
478                 SREG = intr_state;
479                 return -1;
480         }
481
482         UENUM = CDC_ACM_ENDPOINT;
483         if (!(UEINTX & (1<<RWAL))) {
484                 // unable to write
485                 // TODO; should this try to abort the previously
486                 // buffered message??
487                 SREG = intr_state;
488                 return -1;
489         }
490         UEDATX = 0xA1;
491         UEDATX = 0x20;
492         UEDATX = 0;
493         UEDATX = 0;
494         UEDATX = 0; // 0 seems to work nicely.  what if this is 1??
495         UEDATX = 0;
496         UEDATX = 1;
497         UEDATX = 0;
498         UEDATX = signals;
499         UEINTX = 0x3A;
500         SREG = intr_state;
501         return 0;
502 }
503
504
505
506 // ----- General USB Functions -----
507
508 // Set the avr into firmware reload mode
509 void usb_device_reload()
510 {
511         cli();
512         // Disable watchdog, if enabled
513         // Disable all peripherals
514
515         UDCON = 1;
516         USBCON = (1 << FRZCLK);  // Disable USB
517         UCSR1B = 0;
518         _delay_ms( 5 );
519
520 #if defined(__AVR_AT90USB162__)                // Teensy 1.0
521         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0;
522         TIMSK0 = 0; TIMSK1 = 0; UCSR1B = 0;
523         DDRB = 0; DDRC = 0; DDRD = 0;
524         PORTB = 0; PORTC = 0; PORTD = 0;
525         asm volatile("jmp 0x3E00");
526 #elif defined(__AVR_ATmega32U4__)              // Teensy 2.0
527         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
528         TIMSK0 = 0; TIMSK1 = 0; TIMSK3 = 0; TIMSK4 = 0; UCSR1B = 0; TWCR = 0;
529         DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; TWCR = 0;
530         PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
531         asm volatile("jmp 0x7E00");
532 #elif defined(__AVR_AT90USB646__)              // Teensy++ 1.0
533         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
534         TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
535         DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
536         PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
537         asm volatile("jmp 0xFC00");
538 #elif defined(__AVR_AT90USB1286__)             // Teensy++ 2.0
539         EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
540         TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
541         DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
542         PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
543         asm volatile("jmp 0x1FC00");
544 #endif
545 }
546
547
548 // WDT Setup for software reset the chip
549 void wdt_init(void)
550 {
551         MCUSR = 0;
552         wdt_disable();
553 }
554
555
556 // initialize USB
557 void usb_init(void)
558 {
559         HW_CONFIG();
560         USB_FREEZE();                           // enable USB
561         PLL_CONFIG();                           // config PLL
562         while (!(PLLCSR & (1<<PLOCK))) ;        // wait for PLL lock
563         USB_CONFIG();                           // start USB clock
564         UDCON = 0;                              // enable attach resistor
565         usb_configuration = 0;
566         UDIEN = (1<<EORSTE) | (1<<SOFE);
567         sei();
568
569         // Disable watchdog timer after possible software reset
570         //wdt_init(); // XXX Not working...seems to be ok without this, not sure though
571 }
572
573 // return 0 if the USB is not configured, or the configuration
574 // number selected by the HOST
575 uint8_t usb_configured()
576 {
577         return usb_configuration;
578 }
579
580 // USB Device Interrupt - handle all device-level events
581 // the transmit buffer flushing is triggered by the start of frame
582 //
583 ISR( USB_GEN_vect )
584 {
585         uint8_t intbits, t_cdc;
586
587         intbits = UDINT;
588         UDINT = 0;
589         if ( intbits & (1 << EORSTI) )
590         {
591                 UENUM = 0;
592                 UECONX = 1;
593                 UECFG0X = EP_TYPE_CONTROL;
594                 UECFG1X = EP_SIZE(ENDPOINT0_SIZE) | EP_SINGLE_BUFFER;
595                 UEIENX = (1 << RXSTPE);
596                 usb_configuration = 0;
597                 cdc_line_rtsdtr = 0;
598         }
599         if ( (intbits & (1 << SOFI)) && usb_configuration )
600         {
601                 t_cdc = transmit_flush_timer;
602                 if ( t_cdc )
603                 {
604                         transmit_flush_timer = --t_cdc;
605                         if ( !t_cdc )
606                         {
607                                 UENUM = CDC_TX_ENDPOINT;
608                                 UEINTX = 0x3A;
609                         }
610                 }
611                 static uint8_t div4 = 0;
612                 if ( USBKeys_Idle_Config && (++div4 & 3) == 0 )
613                 {
614                         USBKeys_Idle_Count++;
615                         if ( USBKeys_Idle_Count == USBKeys_Idle_Config )
616                         {
617                                 // XXX TODO Is this even used? If so, when? -Jacob
618                                 // From hasu's code, this section looks like it could fix the Mac SET_IDLE problem
619                                 // Send normal keyboard interrupt packet(s)
620                                 //usb_keyboard_toHost();
621                         }
622                 }
623         }
624 }
625
626
627
628 // Misc functions to wait for ready and send/receive packets
629 static inline void usb_wait_in_ready(void)
630 {
631         while (!(UEINTX & (1<<TXINI))) ;
632 }
633 static inline void usb_send_in(void)
634 {
635         UEINTX = ~(1<<TXINI);
636 }
637 static inline void usb_wait_receive_out(void)
638 {
639         while (!(UEINTX & (1<<RXOUTI))) ;
640 }
641 static inline void usb_ack_out(void)
642 {
643         UEINTX = ~(1<<RXOUTI);
644 }
645
646
647
648 // USB Endpoint Interrupt - endpoint 0 is handled here.  The
649 // other endpoints are manipulated by the user-callable
650 // functions, and the start-of-frame interrupt.
651 //
652 ISR(USB_COM_vect)
653 {
654         uint8_t intbits;
655         const uint8_t *list;
656         const uint8_t *cfg;
657         uint8_t i, n, len, en;
658         uint8_t *p;
659         uint8_t bmRequestType;
660         uint8_t bRequest;
661         uint16_t wValue;
662         uint16_t wIndex;
663         uint16_t wLength;
664         uint16_t desc_val;
665         const uint8_t *desc_addr;
666         uint8_t desc_length;
667
668         UENUM = 0;
669         intbits = UEINTX;
670         if (intbits & (1<<RXSTPI)) {
671                 bmRequestType = UEDATX;
672                 bRequest = UEDATX;
673                 wValue = UEDATX;
674                 wValue |= (UEDATX << 8);
675                 wIndex = UEDATX;
676                 wIndex |= (UEDATX << 8);
677                 wLength = UEDATX;
678                 wLength |= (UEDATX << 8);
679                 UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
680
681                 if ( bRequest == GET_DESCRIPTOR )
682                 {
683                         list = (const uint8_t *)descriptor_list;
684                         for ( i = 0; ; i++ )
685                         {
686                                 if ( i >= NUM_DESC_LIST )
687                                 {
688                                         UECONX = (1 << STALLRQ) | (1 << EPEN);  //stall
689                                         return;
690                                 }
691                                 desc_val = pgm_read_word(list);
692                                 if ( desc_val != wValue )
693                                 {
694                                         list += sizeof( struct descriptor_list_struct );
695                                         continue;
696                                 }
697                                 list += 2;
698                                 desc_val = pgm_read_word(list);
699                                 if ( desc_val != wIndex )
700                                 {
701                                         list += sizeof(struct descriptor_list_struct) - 2;
702                                         continue;
703                                 }
704                                 list += 2;
705                                 desc_addr = (const uint8_t *)pgm_read_word(list);
706                                 list += 2;
707                                 desc_length = pgm_read_byte(list);
708                                 break;
709                         }
710                         len = (wLength < 256) ? wLength : 255;
711                         if (len > desc_length) len = desc_length;
712                         do {
713                                 // wait for host ready for IN packet
714                                 do {
715                                         i = UEINTX;
716                                 } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
717                                 if (i & (1<<RXOUTI)) return;    // abort
718                                 // send IN packet
719                                 n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
720                                 for (i = n; i; i--) {
721                                         UEDATX = pgm_read_byte(desc_addr++);
722                                 }
723                                 len -= n;
724                                 usb_send_in();
725                         } while (len || n == ENDPOINT0_SIZE);
726                         return;
727                 }
728
729                 if (bRequest == SET_ADDRESS) {
730                         usb_send_in();
731                         usb_wait_in_ready();
732                         UDADDR = wValue | (1<<ADDEN);
733                         return;
734                 }
735
736                 if ( bRequest == SET_CONFIGURATION && bmRequestType == 0 )
737                 {
738                         usb_configuration = wValue;
739                         cdc_line_rtsdtr = 0;
740                         transmit_flush_timer = 0;
741                         usb_send_in();
742                         cfg = endpoint_config_table;
743                         // Setup each of the 6 additional endpoints (0th already configured)
744                         for ( i = 1; i < 6; i++ )
745                         {
746                                 UENUM = i;
747                                 en = pgm_read_byte(cfg++);
748                                 UECONX = en;
749                                 if (en)
750                                 {
751                                         UECFG0X = pgm_read_byte(cfg++);
752                                         UECFG1X = pgm_read_byte(cfg++);
753                                 }
754                         }
755                         UERST = 0x7E;
756                         UERST = 0;
757                         return;
758                 }
759
760                 if (bRequest == GET_CONFIGURATION && bmRequestType == 0x80) {
761                         usb_wait_in_ready();
762                         UEDATX = usb_configuration;
763                         usb_send_in();
764                         return;
765                 }
766
767                 //if ( wIndex == KEYBOARD_INTERFACE )
768                 if ( wIndex == KEYBOARD_INTERFACE || wIndex == KEYBOARD_NKRO_INTERFACE )
769                 {
770                         if ( bmRequestType == 0xA1)
771                         {
772                                 if ( bRequest == HID_GET_REPORT )
773                                 {
774                                         usb_wait_in_ready();
775
776                                         // XXX TODO Is this even used? If so, when? -Jacob
777                                         // Send normal keyboard interrupt packet(s)
778                                         //usb_keyboard_toHost();
779
780                                         usb_send_in();
781                                         return;
782                                 }
783                                 if ( bRequest == HID_GET_IDLE )
784                                 {
785                                         usb_wait_in_ready();
786                                         UEDATX = USBKeys_Idle_Config;
787                                         usb_send_in();
788                                         return;
789                                 }
790                                 if ( bRequest == HID_GET_PROTOCOL )
791                                 {
792                                         usb_wait_in_ready();
793                                         UEDATX = USBKeys_Protocol;
794                                         usb_send_in();
795                                         return;
796                                 }
797                         USBKeys_Protocol = bRequest;
798                         }
799                         if ( bmRequestType == 0x21 )
800                         {
801                                 if ( bRequest == HID_SET_REPORT )
802                                 {
803                                         usb_wait_receive_out();
804                                         USBKeys_LEDs = UEDATX;
805                                         usb_ack_out();
806                                         usb_send_in();
807                                         return;
808                                 }
809                                 if ( bRequest == HID_SET_IDLE )
810                                 {
811                                         USBKeys_Idle_Config = (wValue >> 8);
812                                         USBKeys_Idle_Count = 0;
813                                         //usb_wait_in_ready();
814                                         usb_send_in();
815                                         return;
816                                 }
817                                 if ( bRequest == HID_SET_PROTOCOL )
818                                 {
819                                         USBKeys_Protocol = wValue; // 0 - Boot Mode, 1 - NKRO Mode
820                                         //usb_wait_in_ready();
821                                         usb_send_in();
822                                         return;
823                                 }
824                         }
825                 }
826
827                 if (bRequest == CDC_GET_LINE_CODING && bmRequestType == 0xA1) {
828                         usb_wait_in_ready();
829                         p = cdc_line_coding;
830                         for (i=0; i<7; i++) {
831                                 UEDATX = *p++;
832                         }
833                         usb_send_in();
834                         return;
835                 }
836
837                 if (bRequest == CDC_SET_LINE_CODING && bmRequestType == 0x21) {
838                         usb_wait_receive_out();
839                         p = cdc_line_coding;
840                         for (i=0; i<7; i++) {
841                                 *p++ = UEDATX;
842                         }
843                         usb_ack_out();
844                         usb_send_in();
845                         return;
846                 }
847
848                 if (bRequest == CDC_SET_CONTROL_LINE_STATE && bmRequestType == 0x21) {
849                         cdc_line_rtsdtr = wValue;
850                         usb_wait_in_ready();
851                         usb_send_in();
852                         return;
853                 }
854
855                 if (bRequest == GET_STATUS) {
856                         usb_wait_in_ready();
857                         i = 0;
858                         if (bmRequestType == 0x82) {
859                                 UENUM = wIndex;
860                                 if (UECONX & (1<<STALLRQ)) i = 1;
861                                 UENUM = 0;
862                         }
863                         UEDATX = i;
864                         UEDATX = 0;
865                         usb_send_in();
866                         return;
867                 }
868
869                 if ((bRequest == CLEAR_FEATURE || bRequest == SET_FEATURE)
870                   && bmRequestType == 0x02 && wValue == 0) {
871                         i = wIndex & 0x7F;
872                         if (i >= 1 && i <= MAX_ENDPOINT) {
873                                 usb_send_in();
874                                 UENUM = i;
875                                 if (bRequest == SET_FEATURE) {
876                                         UECONX = (1<<STALLRQ)|(1<<EPEN);
877                                 } else {
878                                         UECONX = (1<<STALLRQC)|(1<<RSTDT)|(1<<EPEN);
879                                         UERST = (1 << i);
880                                         UERST = 0;
881                                 }
882                                 return;
883                         }
884                 }
885         }
886         UECONX = (1 << STALLRQ) | (1 << EPEN);  // stall
887 }
888