]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - usb.c
f5905f2ee470a0a07b057d4bb7a4a7d3e5c232c5
[max/tmk_keyboard.git] / usb.c
1 /* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
2  * http://www.pjrc.com/teensy/usb_keyboard.html
3  * Copyright (c) 2009 PJRC.COM, LLC
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 #include <avr/io.h>
25 #include <avr/pgmspace.h>
26 #include <avr/interrupt.h>
27 #include "usb.h"
28 #include "usb_keyboard.h"
29 #include "usb_mouse.h"
30 #include "usb_debug.h"
31 #include "print.h"
32
33
34 /**************************************************************************
35  *
36  *  Configurable Options
37  *
38  **************************************************************************/
39
40 // You can change these to give your code its own name.
41 #define STR_MANUFACTURER        L"t.m.k."
42 #define STR_PRODUCT             L"t.m.k. keyboard"
43
44
45 // Mac OS-X and Linux automatically load the correct drivers.  On
46 // Windows, even though the driver is supplied by Microsoft, an
47 // INF file is needed to load the driver.  These numbers need to
48 // match the INF file.
49 #define VENDOR_ID               0xFEED
50 #define PRODUCT_ID              0xCAFE
51
52
53 // USB devices are supposed to implment a halt feature, which is
54 // rarely (if ever) used.  If you comment this line out, the halt
55 // code will be removed, saving 102 bytes of space (gcc 4.3.0).
56 // This is not strictly USB compliant, but works with all major
57 // operating systems.
58 #define SUPPORT_ENDPOINT_HALT
59
60
61
62 /**************************************************************************
63  *
64  *  Endpoint Buffer Configuration
65  *
66  **************************************************************************/
67
68 #define ENDPOINT0_SIZE          32
69
70 // 0:control endpoint is enabled automatically by controller.
71 static const uint8_t PROGMEM endpoint_config_table[] = {
72         // enable, UECFG0X(type, direction), UECFG1X(size, bank, allocation)
73         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(KEYBOARD_SIZE) | KEYBOARD_BUFFER, // 1
74         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(MOUSE_SIZE)    | MOUSE_BUFFER,    // 2
75         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(DEBUG_TX_SIZE) | DEBUG_TX_BUFFER, // 3
76         0, // 4
77         0, // 5
78         0, // 6
79 };
80
81
82 /**************************************************************************
83  *
84  *  Descriptor Data
85  *
86  **************************************************************************/
87
88 // Descriptors are the data that your computer reads when it auto-detects
89 // this USB device (called "enumeration" in USB lingo).  The most commonly
90 // changed items are editable at the top of this file.  Changing things
91 // in here should only be done by those who've read chapter 9 of the USB
92 // spec and relevant portions of any USB class specifications!
93
94
95 static uint8_t PROGMEM device_descriptor[] = {
96         18,                                     // bLength
97         1,                                      // bDescriptorType
98         0x00, 0x02,                             // bcdUSB
99         0,                                      // bDeviceClass
100         0,                                      // bDeviceSubClass
101         0,                                      // bDeviceProtocol
102         ENDPOINT0_SIZE,                         // bMaxPacketSize0
103         LSB(VENDOR_ID), MSB(VENDOR_ID),         // idVendor
104         LSB(PRODUCT_ID), MSB(PRODUCT_ID),       // idProduct
105         0x00, 0x01,                             // bcdDevice
106         1,                                      // iManufacturer
107         2,                                      // iProduct
108         0,                                      // iSerialNumber
109         1                                       // bNumConfigurations
110 };
111
112 // Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60
113 static uint8_t PROGMEM keyboard_hid_report_desc[] = {
114         0x05, 0x01,          // Usage Page (Generic Desktop),
115         0x09, 0x06,          // Usage (Keyboard),
116         0xA1, 0x01,          // Collection (Application),
117         0x75, 0x01,          //   Report Size (1),
118         0x95, 0x08,          //   Report Count (8),
119         0x05, 0x07,          //   Usage Page (Key Codes),
120         0x19, 0xE0,          //   Usage Minimum (224),
121         0x29, 0xE7,          //   Usage Maximum (231),
122         0x15, 0x00,          //   Logical Minimum (0),
123         0x25, 0x01,          //   Logical Maximum (1),
124         0x81, 0x02,          //   Input (Data, Variable, Absolute), ;Modifier byte
125         0x95, 0x01,          //   Report Count (1),
126         0x75, 0x08,          //   Report Size (8),
127         0x81, 0x03,          //   Input (Constant),                 ;Reserved byte
128         0x95, 0x05,          //   Report Count (5),
129         0x75, 0x01,          //   Report Size (1),
130         0x05, 0x08,          //   Usage Page (LEDs),
131         0x19, 0x01,          //   Usage Minimum (1),
132         0x29, 0x05,          //   Usage Maximum (5),
133         0x91, 0x02,          //   Output (Data, Variable, Absolute), ;LED report
134         0x95, 0x01,          //   Report Count (1),
135         0x75, 0x03,          //   Report Size (3),
136         0x91, 0x03,          //   Output (Constant),                 ;LED report padding
137         0x95, 0x06,          //   Report Count (6),
138         0x75, 0x08,          //   Report Size (8),
139         0x15, 0x00,          //   Logical Minimum (0),
140         0x25, 0x68,          //   Logical Maximum(104),
141         0x05, 0x07,          //   Usage Page (Key Codes),
142         0x19, 0x00,          //   Usage Minimum (0),
143         0x29, 0x68,          //   Usage Maximum (104),
144         0x81, 0x00,          //   Input (Data, Array),
145         0xc0                 // End Collection
146 };
147
148 // Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
149 // http://www.microchip.com/forums/tm.aspx?high=&m=391435&mpage=1#391521
150 // http://www.keil.com/forum/15671/
151 // http://www.microsoft.com/whdc/device/input/wheel.mspx
152 static uint8_t PROGMEM mouse_hid_report_desc[] = {
153     0x05, 0x01,        // USAGE_PAGE (Generic Desktop)
154     0x09, 0x02,        // USAGE (Mouse)
155     0xa1, 0x01,        // COLLECTION (Application)
156     0x09, 0x02,        //   USAGE (Mouse)
157     0xa1, 0x02,        //   COLLECTION (Logical)
158     0x09, 0x01,        //     USAGE (Pointer)
159     0xa1, 0x00,        //     COLLECTION (Physical)
160                        // ------------------------------  Buttons
161     0x05, 0x09,        //       USAGE_PAGE (Button)
162     0x19, 0x01,        //       USAGE_MINIMUM (Button 1)
163     0x29, 0x05,        //       USAGE_MAXIMUM (Button 5)
164     0x15, 0x00,        //       LOGICAL_MINIMUM (0)
165     0x25, 0x01,        //       LOGICAL_MAXIMUM (1)
166     0x75, 0x01,        //       REPORT_SIZE (1)
167     0x95, 0x05,        //       REPORT_COUNT (5)
168     0x81, 0x02,        //       INPUT (Data,Var,Abs)
169                        // ------------------------------  Padding
170     0x75, 0x03,        //       REPORT_SIZE (3)
171     0x95, 0x01,        //       REPORT_COUNT (1)
172     0x81, 0x03,        //       INPUT (Cnst,Var,Abs)
173                        // ------------------------------  X,Y position
174     0x05, 0x01,        //       USAGE_PAGE (Generic Desktop)
175     0x09, 0x30,        //       USAGE (X)
176     0x09, 0x31,        //       USAGE (Y)
177     0x15, 0x81,        //       LOGICAL_MINIMUM (-127)
178     0x25, 0x7f,        //       LOGICAL_MAXIMUM (127)
179     0x75, 0x08,        //       REPORT_SIZE (8)
180     0x95, 0x02,        //       REPORT_COUNT (2)
181     0x81, 0x06,        //       INPUT (Data,Var,Rel)
182     0xa1, 0x02,        //       COLLECTION (Logical)
183                        // ------------------------------  Vertical wheel res multiplier
184     0x09, 0x48,        //         USAGE (Resolution Multiplier)
185     0x15, 0x00,        //         LOGICAL_MINIMUM (0)
186     0x25, 0x01,        //         LOGICAL_MAXIMUM (1)
187     0x35, 0x01,        //         PHYSICAL_MINIMUM (1)
188     0x45, 0x04,        //         PHYSICAL_MAXIMUM (4)
189     0x75, 0x02,        //         REPORT_SIZE (2)
190     0x95, 0x01,        //         REPORT_COUNT (1)
191     0xa4,              //         PUSH
192     0xb1, 0x02,        //         FEATURE (Data,Var,Abs)
193                        // ------------------------------  Vertical wheel
194     0x09, 0x38,        //         USAGE (Wheel)
195     0x15, 0x81,        //         LOGICAL_MINIMUM (-127)
196     0x25, 0x7f,        //         LOGICAL_MAXIMUM (127)
197     0x35, 0x00,        //         PHYSICAL_MINIMUM (0)        - reset physical
198     0x45, 0x00,        //         PHYSICAL_MAXIMUM (0)
199     0x75, 0x08,        //         REPORT_SIZE (8)
200     0x81, 0x06,        //         INPUT (Data,Var,Rel)
201     0xc0,              //       END_COLLECTION
202     0xa1, 0x02,        //       COLLECTION (Logical)
203                        // ------------------------------  Horizontal wheel res multiplier
204     0x09, 0x48,        //         USAGE (Resolution Multiplier)
205     0xb4,              //         POP
206     0xb1, 0x02,        //         FEATURE (Data,Var,Abs)
207                        // ------------------------------  Padding for Feature report
208     0x35, 0x00,        //         PHYSICAL_MINIMUM (0)        - reset physical
209     0x45, 0x00,        //         PHYSICAL_MAXIMUM (0)
210     0x75, 0x04,        //         REPORT_SIZE (4)
211     0xb1, 0x03,        //         FEATURE (Cnst,Var,Abs)
212                        // ------------------------------  Horizontal wheel
213     0x05, 0x0c,        //         USAGE_PAGE (Consumer Devices)
214     0x0a, 0x38, 0x02,  //         USAGE (AC Pan)
215     0x15, 0x81,        //         LOGICAL_MINIMUM (-127)
216     0x25, 0x7f,        //         LOGICAL_MAXIMUM (127)
217     0x75, 0x08,        //         REPORT_SIZE (8)
218     0x81, 0x06,        //         INPUT (Data,Var,Rel)
219     0xc0,              //       END_COLLECTION
220     0xc0,              //     END_COLLECTION
221     0xc0,              //   END_COLLECTION
222     0xc0               // END_COLLECTION
223 };
224
225 static uint8_t PROGMEM debug_hid_report_desc[] = {
226         0x06, 0x31, 0xFF,                       // Usage Page 0xFF31 (vendor defined)
227         0x09, 0x74,                             // Usage 0x74
228         0xA1, 0x53,                             // Collection 0x53
229         0x75, 0x08,                             // report size = 8 bits
230         0x15, 0x00,                             // logical minimum = 0
231         0x26, 0xFF, 0x00,                       // logical maximum = 255
232         0x95, DEBUG_TX_SIZE,                    // report count
233         0x09, 0x75,                             // usage
234         0x81, 0x02,                             // Input (array)
235         0xC0                                    // end collection
236 };
237
238 #define CONFIG1_DESC_SIZE        (9+(9+9+7)+(9+9+7)+(9+9+7))
239 #define KEYBOARD_HID_DESC_OFFSET (9+9)
240 #define MOUSE_HID_DESC_OFFSET    (9+(9+9+7)+9)
241 #define DEBUG_HID_DESC_OFFSET    (9+(9+9+7)+(9+9+7)+9)
242 static uint8_t PROGMEM config1_descriptor[CONFIG1_DESC_SIZE] = {
243         // configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
244         9,                                      // bLength;
245         2,                                      // bDescriptorType;
246         LSB(CONFIG1_DESC_SIZE),                 // wTotalLength
247         MSB(CONFIG1_DESC_SIZE),
248         3,                                      // bNumInterfaces
249         1,                                      // bConfigurationValue
250         0,                                      // iConfiguration
251         0xC0,                                   // bmAttributes
252         50,                                     // bMaxPower
253
254         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
255         9,                                      // bLength
256         4,                                      // bDescriptorType
257         KEYBOARD_INTERFACE,                     // bInterfaceNumber
258         0,                                      // bAlternateSetting
259         1,                                      // bNumEndpoints
260         0x03,                                   // bInterfaceClass (0x03 = HID)
261         0x01,                                   // bInterfaceSubClass (0x01 = Boot)
262         0x01,                                   // bInterfaceProtocol (0x01 = Keyboard)
263         0,                                      // iInterface
264         // HID descriptor, HID 1.11 spec, section 6.2.1
265         9,                                      // bLength
266         0x21,                                   // bDescriptorType
267         0x11, 0x01,                             // bcdHID
268         0,                                      // bCountryCode
269         1,                                      // bNumDescriptors
270         0x22,                                   // bDescriptorType
271         sizeof(keyboard_hid_report_desc),       // wDescriptorLength
272         0,
273         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
274         7,                                      // bLength
275         5,                                      // bDescriptorType
276         KEYBOARD_ENDPOINT | 0x80,               // bEndpointAddress
277         0x03,                                   // bmAttributes (0x03=intr)
278         KEYBOARD_SIZE, 0,                       // wMaxPacketSize
279         1,                                      // bInterval
280
281         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
282         9,                                      // bLength
283         4,                                      // bDescriptorType
284         MOUSE_INTERFACE,                        // bInterfaceNumber
285         0,                                      // bAlternateSetting
286         1,                                      // bNumEndpoints
287         0x03,                                   // bInterfaceClass (0x03 = HID)
288         0x01,                                   // bInterfaceSubClass (0x01 = Boot)
289         0x02,                                   // bInterfaceProtocol (0x02 = Mouse)
290         0,                                      // iInterface
291         // HID descriptor, HID 1.11 spec, section 6.2.1
292         9,                                      // bLength
293         0x21,                                   // bDescriptorType
294         0x11, 0x01,                             // bcdHID
295         0,                                      // bCountryCode
296         1,                                      // bNumDescriptors
297         0x22,                                   // bDescriptorType
298         sizeof(mouse_hid_report_desc),          // wDescriptorLength
299         0,
300         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
301         7,                                      // bLength
302         5,                                      // bDescriptorType
303         MOUSE_ENDPOINT | 0x80,                  // bEndpointAddress
304         0x03,                                   // bmAttributes (0x03=intr)
305         MOUSE_SIZE, 0,                          // wMaxPacketSize
306         1,                                      // bInterval
307
308         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
309         9,                                      // bLength
310         4,                                      // bDescriptorType
311         DEBUG_INTERFACE,                        // bInterfaceNumber
312         0,                                      // bAlternateSetting
313         1,                                      // bNumEndpoints
314         0x03,                                   // bInterfaceClass (0x03 = HID)
315         0x00,                                   // bInterfaceSubClass
316         0x00,                                   // bInterfaceProtocol
317         0,                                      // iInterface
318         // HID descriptor, HID 1.11 spec, section 6.2.1
319         9,                                      // bLength
320         0x21,                                   // bDescriptorType
321         0x11, 0x01,                             // bcdHID
322         0,                                      // bCountryCode
323         1,                                      // bNumDescriptors
324         0x22,                                   // bDescriptorType
325         sizeof(debug_hid_report_desc),          // wDescriptorLength
326         0,
327         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
328         7,                                      // bLength
329         5,                                      // bDescriptorType
330         DEBUG_TX_ENDPOINT | 0x80,               // bEndpointAddress
331         0x03,                                   // bmAttributes (0x03=intr)
332         DEBUG_TX_SIZE, 0,                       // wMaxPacketSize
333         1                                       // bInterval
334 };
335
336 // If you're desperate for a little extra code memory, these strings
337 // can be completely removed if iManufacturer, iProduct, iSerialNumber
338 // in the device desciptor are changed to zeros.
339 struct usb_string_descriptor_struct {
340         uint8_t bLength;
341         uint8_t bDescriptorType;
342         int16_t wString[];
343 };
344 static struct usb_string_descriptor_struct PROGMEM string0 = {
345         4,
346         3,
347         {0x0409}
348 };
349 static struct usb_string_descriptor_struct PROGMEM string1 = {
350         sizeof(STR_MANUFACTURER),
351         3,
352         STR_MANUFACTURER
353 };
354 static struct usb_string_descriptor_struct PROGMEM string2 = {
355         sizeof(STR_PRODUCT),
356         3,
357         STR_PRODUCT
358 };
359
360 // This table defines which descriptor data is sent for each specific
361 // request from the host (in wValue and wIndex).
362 static struct descriptor_list_struct {
363         uint16_t        wValue;     // descriptor type
364         uint16_t        wIndex;
365         const uint8_t   *addr;
366         uint8_t         length;
367 } PROGMEM descriptor_list[] = {
368         // DEVICE descriptor
369         {0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)},
370         // CONFIGURATION descriptor
371         {0x0200, 0x0000, config1_descriptor, sizeof(config1_descriptor)},
372         // HID REPORT
373         {0x2200, KEYBOARD_INTERFACE, keyboard_hid_report_desc, sizeof(keyboard_hid_report_desc)},
374         {0x2100, KEYBOARD_INTERFACE, config1_descriptor+KEYBOARD_HID_DESC_OFFSET, 9},
375         // HID REPORT
376         {0x2200, MOUSE_INTERFACE, mouse_hid_report_desc, sizeof(mouse_hid_report_desc)},
377         {0x2100, MOUSE_INTERFACE, config1_descriptor+MOUSE_HID_DESC_OFFSET, 9},
378         // HID REPORT
379         {0x2200, DEBUG_INTERFACE, debug_hid_report_desc, sizeof(debug_hid_report_desc)},
380         {0x2100, DEBUG_INTERFACE, config1_descriptor+DEBUG_HID_DESC_OFFSET, 9},
381         // STRING descriptor
382         {0x0300, 0x0000, (const uint8_t *)&string0, 4},
383         {0x0301, 0x0409, (const uint8_t *)&string1, sizeof(STR_MANUFACTURER)},
384         {0x0302, 0x0409, (const uint8_t *)&string2, sizeof(STR_PRODUCT)}
385 };
386 #define NUM_DESC_LIST (sizeof(descriptor_list)/sizeof(struct descriptor_list_struct))
387
388
389 /**************************************************************************
390  *
391  *  Variables - these are the only non-stack RAM usage
392  *
393  **************************************************************************/
394
395 // zero when we are not configured, non-zero when enumerated
396 static volatile uint8_t usb_configuration=0;
397
398
399 /**************************************************************************
400  *
401  *  Public Functions - these are the API intended for the user
402  *
403  **************************************************************************/
404
405
406 // initialize USB
407 void usb_init(void)
408 {
409         HW_CONFIG();
410         USB_FREEZE();                           // enable USB
411         PLL_CONFIG();                           // config PLL
412         while (!(PLLCSR & (1<<PLOCK))) ;        // wait for PLL lock
413         USB_CONFIG();                           // start USB clock
414         UDCON = 0;                              // enable attach resistor
415         usb_configuration = 0;
416         UDIEN = (1<<EORSTE)|(1<<SOFE);
417         sei();
418 }
419
420 // return 0 if the USB is not configured, or the configuration
421 // number selected by the HOST
422 uint8_t usb_configured(void)
423 {
424         return usb_configuration;
425 }
426
427
428
429 /**************************************************************************
430  *
431  *  Private Functions - not intended for general user consumption....
432  *
433  **************************************************************************/
434
435
436
437 // USB Device Interrupt - handle all device-level events
438 // the transmit buffer flushing is triggered by the start of frame
439 //
440 ISR(USB_GEN_vect)
441 {
442         uint8_t intbits, t, i;
443         static uint8_t div4=0;
444
445         intbits = UDINT;
446         UDINT = 0;
447         if (intbits & (1<<EORSTI)) {
448                 UENUM = 0;
449                 UECONX = 1;
450                 UECFG0X = EP_TYPE_CONTROL;
451                 UECFG1X = EP_SIZE(ENDPOINT0_SIZE) | EP_SINGLE_BUFFER;
452                 UEIENX = (1<<RXSTPE);
453                 usb_configuration = 0;
454         }
455         if ((intbits & (1<<SOFI)) && usb_configuration) {
456                 t = debug_flush_timer;
457                 if (t) {
458                         debug_flush_timer = -- t;
459                         if (!t) {
460                                 UENUM = DEBUG_TX_ENDPOINT;
461                                 while ((UEINTX & (1<<RWAL))) {
462                                         UEDATX = 0;
463                                 }
464                                 UEINTX = 0x3A;
465                         }
466                 }
467                 if (keyboard_idle_config && (++div4 & 3) == 0) {
468                         UENUM = KEYBOARD_ENDPOINT;
469                         if (UEINTX & (1<<RWAL)) {
470                                 keyboard_idle_count++;
471                                 if (keyboard_idle_count == keyboard_idle_config) {
472                                         keyboard_idle_count = 0;
473                                         UEDATX = keyboard_modifier_keys;
474                                         UEDATX = 0;
475                                         for (i=0; i<6; i++) {
476                                                 UEDATX = keyboard_keys[i];
477                                         }
478                                         UEINTX = 0x3A;
479                                 }
480                         }
481                 }
482         }
483 }
484
485
486
487 // Misc functions to wait for ready and send/receive packets
488 static inline void usb_wait_in_ready(void)
489 {
490         while (!(UEINTX & (1<<TXINI))) ;
491 }
492 static inline void usb_send_in(void)
493 {
494         UEINTX = ~(1<<TXINI);
495 }
496 static inline void usb_wait_receive_out(void)
497 {
498         while (!(UEINTX & (1<<RXOUTI))) ;
499 }
500 static inline void usb_ack_out(void)
501 {
502         UEINTX = ~(1<<RXOUTI);
503 }
504
505
506
507 // USB Endpoint Interrupt - endpoint 0 is handled here.  The
508 // other endpoints are manipulated by the user-callable
509 // functions, and the start-of-frame interrupt.
510 //
511 ISR(USB_COM_vect)
512 {
513         uint8_t intbits;
514         const uint8_t *list;
515         const uint8_t *cfg;
516         uint8_t i, n, len, en;
517         uint8_t bmRequestType;
518         uint8_t bRequest;
519         uint16_t wValue;
520         uint16_t wIndex;
521         uint16_t wLength;
522         uint16_t desc_val;
523         const uint8_t *desc_addr;
524         uint8_t desc_length;
525
526         UENUM = 0;
527         intbits = UEINTX;
528         if (intbits & (1<<RXSTPI)) {
529                 bmRequestType = UEDATX;
530                 bRequest = UEDATX;
531                 wValue = UEDATX;
532                 wValue |= (UEDATX << 8);
533                 wIndex = UEDATX;
534                 wIndex |= (UEDATX << 8);
535                 wLength = UEDATX;
536                 wLength |= (UEDATX << 8);
537                 UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
538                 if (bRequest == GET_DESCRIPTOR) {
539                         list = (const uint8_t *)descriptor_list;
540                         for (i=0; ; i++) {
541                                 if (i >= NUM_DESC_LIST) {
542                                         UECONX = (1<<STALLRQ)|(1<<EPEN);  //stall
543                                         return;
544                                 }
545                                 desc_val = pgm_read_word(list);
546                                 if (desc_val != wValue) {
547                                         list += sizeof(struct descriptor_list_struct);
548                                         continue;
549                                 }
550                                 list += 2;
551                                 desc_val = pgm_read_word(list);
552                                 if (desc_val != wIndex) {
553                                         list += sizeof(struct descriptor_list_struct)-2;
554                                         continue;
555                                 }
556                                 list += 2;
557                                 desc_addr = (const uint8_t *)pgm_read_word(list);
558                                 list += 2;
559                                 desc_length = pgm_read_byte(list);
560                                 break;
561                         }
562                         len = (wLength < 256) ? wLength : 255;
563                         if (len > desc_length) len = desc_length;
564                         do {
565                                 // wait for host ready for IN packet
566                                 do {
567                                         i = UEINTX;
568                                 } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
569                                 if (i & (1<<RXOUTI)) return;    // abort
570                                 // send IN packet
571                                 n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
572                                 for (i = n; i; i--) {
573                                         UEDATX = pgm_read_byte(desc_addr++);
574                                 }
575                                 len -= n;
576                                 usb_send_in();
577                         } while (len || n == ENDPOINT0_SIZE);
578                         return;
579                 }
580                 if (bRequest == SET_ADDRESS) {
581                         usb_send_in();
582                         usb_wait_in_ready();
583                         UDADDR = wValue | (1<<ADDEN);
584                         return;
585                 }
586                 if (bRequest == SET_CONFIGURATION && bmRequestType == 0) {
587                         usb_configuration = wValue;
588                         usb_send_in();
589                         cfg = endpoint_config_table;
590                         for (i=1; i<=6; i++) {
591                                 UENUM = i;
592                                 en = pgm_read_byte(cfg++);
593                                 UECONX = en;
594                                 if (en) {
595                                         UECFG0X = pgm_read_byte(cfg++);
596                                         UECFG1X = pgm_read_byte(cfg++);
597                                 }
598                         }
599                         UERST = 0x7E;
600                         UERST = 0;
601                         return;
602                 }
603                 if (bRequest == GET_CONFIGURATION && bmRequestType == 0x80) {
604                         usb_wait_in_ready();
605                         UEDATX = usb_configuration;
606                         usb_send_in();
607                         return;
608                 }
609
610                 if (bRequest == GET_STATUS) {
611                         usb_wait_in_ready();
612                         i = 0;
613                         #ifdef SUPPORT_ENDPOINT_HALT
614                         if (bmRequestType == 0x82) {
615                                 UENUM = wIndex;
616                                 if (UECONX & (1<<STALLRQ)) i = 1;
617                                 UENUM = 0;
618                         }
619                         #endif
620                         UEDATX = i;
621                         UEDATX = 0;
622                         usb_send_in();
623                         return;
624                 }
625                 #ifdef SUPPORT_ENDPOINT_HALT
626                 if ((bRequest == CLEAR_FEATURE || bRequest == SET_FEATURE)
627                   && bmRequestType == 0x02 && wValue == 0) {
628                         i = wIndex & 0x7F;
629                         if (i >= 1 && i <= MAX_ENDPOINT) {
630                                 usb_send_in();
631                                 UENUM = i;
632                                 if (bRequest == SET_FEATURE) {
633                                         UECONX = (1<<STALLRQ)|(1<<EPEN);
634                                 } else {
635                                         UECONX = (1<<STALLRQC)|(1<<RSTDT)|(1<<EPEN);
636                                         UERST = (1 << i);
637                                         UERST = 0;
638                                 }
639                                 return;
640                         }
641                 }
642                 #endif
643                 if (wIndex == KEYBOARD_INTERFACE) {
644                         if (bmRequestType == 0xA1) {
645                                 if (bRequest == HID_GET_REPORT) {
646                                         usb_wait_in_ready();
647                                         UEDATX = keyboard_modifier_keys;
648                                         UEDATX = 0;
649                                         for (i=0; i<6; i++) {
650                                                 UEDATX = keyboard_keys[i];
651                                         }
652                                         usb_send_in();
653                                         return;
654                                 }
655                                 if (bRequest == HID_GET_IDLE) {
656                                         usb_wait_in_ready();
657                                         UEDATX = keyboard_idle_config;
658                                         usb_send_in();
659                                         return;
660                                 }
661                                 if (bRequest == HID_GET_PROTOCOL) {
662                                         usb_wait_in_ready();
663                                         UEDATX = keyboard_protocol;
664                                         usb_send_in();
665                                         return;
666                                 }
667                         }
668                         if (bmRequestType == 0x21) {
669                                 if (bRequest == HID_SET_REPORT) {
670                                         usb_wait_receive_out();
671                                         keyboard_leds = UEDATX;
672                                         usb_ack_out();
673                                         usb_send_in();
674                                         return;
675                                 }
676                                 if (bRequest == HID_SET_IDLE) {
677                                         keyboard_idle_config = (wValue >> 8);
678                                         keyboard_idle_count = 0;
679                                         //usb_wait_in_ready();
680                                         usb_send_in();
681                                         return;
682                                 }
683                                 if (bRequest == HID_SET_PROTOCOL) {
684                                         keyboard_protocol = wValue;
685                                         //usb_wait_in_ready();
686                                         usb_send_in();
687                                         return;
688                                 }
689                         }
690                 }
691                 if (wIndex == MOUSE_INTERFACE) {
692                         if (bmRequestType == 0xA1) {
693                                 if (bRequest == HID_GET_REPORT) {
694                                     if (wValue == HID_REPORT_INPUT) {
695                                         usb_wait_in_ready();
696                                         UEDATX = mouse_buttons;
697                                         UEDATX = 0;
698                                         UEDATX = 0;
699                                         UEDATX = 0;
700                                         usb_send_in();
701                                         return;
702                                     }
703                                     if (wValue == HID_REPORT_FEATURE) {
704                                         usb_wait_in_ready();
705                                         UEDATX = 0x05;
706                                         usb_send_in();
707                                         return;
708                                     }
709                                 }
710                                 if (bRequest == HID_GET_PROTOCOL) {
711                                         usb_wait_in_ready();
712                                         UEDATX = mouse_protocol;
713                                         usb_send_in();
714                                         return;
715                                 }
716                         }
717                         if (bmRequestType == 0x21) {
718                                 if (bRequest == HID_SET_PROTOCOL) {
719                                         mouse_protocol = wValue;
720                                         usb_send_in();
721                                         return;
722                                 }
723                         }
724                 }
725                 if (wIndex == DEBUG_INTERFACE) {
726                         if (bRequest == HID_GET_REPORT && bmRequestType == 0xA1) {
727                                 len = wLength;
728                                 do {
729                                         // wait for host ready for IN packet
730                                         do {
731                                                 i = UEINTX;
732                                         } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
733                                         if (i & (1<<RXOUTI)) return;    // abort
734                                         // send IN packet
735                                         n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
736                                         for (i = n; i; i--) {
737                                                 UEDATX = 0;
738                                         }
739                                         len -= n;
740                                         usb_send_in();
741                                 } while (len || n == ENDPOINT0_SIZE);
742                                 return;
743                         }
744                 }
745         }
746         UECONX = (1<<STALLRQ) | (1<<EPEN);      // stall
747 }