]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - pjrc/usb.c
FIX: send last report when idle timeouts. (pjrc)
[max/tmk_keyboard.git] / pjrc / 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 <stdint.h>
25 #include <stdbool.h>
26 #include <avr/io.h>
27 #include <avr/pgmspace.h>
28 #include <avr/interrupt.h>
29 #include "usb.h"
30 #include "usb_keyboard.h"
31 #include "usb_mouse.h"
32 #include "usb_debug.h"
33 #include "usb_extra.h"
34 #include "print.h"
35 #include "util.h"
36
37
38 /**************************************************************************
39  *
40  *  Configurable Options
41  *
42  **************************************************************************/
43
44 // You can change these to give your code its own name.
45 #ifndef MANUFACTURER
46 #   define STR_MANUFACTURER     L"t.m.k."
47 #else
48 #   define STR_MANUFACTURER     LSTR(MANUFACTURER)
49 #endif
50 #ifndef PRODUCT
51 #   define STR_PRODUCT          L"t.m.k. keyboard"
52 #else
53 #   define STR_PRODUCT          LSTR(PRODUCT)
54 #endif
55
56
57 // Mac OS-X and Linux automatically load the correct drivers.  On
58 // Windows, even though the driver is supplied by Microsoft, an
59 // INF file is needed to load the driver.  These numbers need to
60 // match the INF file.
61 #ifndef VENDOR_ID
62 #   define VENDOR_ID            0xFEED
63 #endif
64
65 #ifndef PRODUCT_ID
66 #   define PRODUCT_ID           0xBABE
67 #endif
68
69
70 // USB devices are supposed to implment a halt feature, which is
71 // rarely (if ever) used.  If you comment this line out, the halt
72 // code will be removed, saving 102 bytes of space (gcc 4.3.0).
73 // This is not strictly USB compliant, but works with all major
74 // operating systems.
75 #define SUPPORT_ENDPOINT_HALT
76
77
78
79 /**************************************************************************
80  *
81  *  Endpoint Buffer Configuration
82  *
83  **************************************************************************/
84
85 #define ENDPOINT0_SIZE          32
86
87 bool remote_wakeup = false;
88 bool suspend = false;
89
90 // 0:control endpoint is enabled automatically by controller.
91 static const uint8_t PROGMEM endpoint_config_table[] = {
92         // enable, UECFG0X(type, direction), UECFG1X(size, bank, allocation)
93         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(KBD_SIZE)      | KBD_BUFFER,      // 1
94 #ifdef USB_MOUSE_ENABLE
95         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(MOUSE_SIZE)    | MOUSE_BUFFER,    // 2
96 #else
97         0,                                                                  // 2
98 #endif
99         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(DEBUG_TX_SIZE) | DEBUG_TX_BUFFER, // 3
100 #ifdef USB_EXTRA_ENABLE
101         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(EXTRA_SIZE)    | EXTRA_BUFFER,    // 4
102 #else
103         0,                                                                  // 4
104 #endif
105 #ifdef USB_NKRO_ENABLE
106         1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(KBD2_SIZE)     | KBD2_BUFFER,     // 5
107 #else
108         0,                                                                  // 5
109 #endif
110         0,                                                                  // 6
111 };
112
113
114 /**************************************************************************
115  *
116  *  Descriptor Data
117  *
118  **************************************************************************/
119
120 // Descriptors are the data that your computer reads when it auto-detects
121 // this USB device (called "enumeration" in USB lingo).  The most commonly
122 // changed items are editable at the top of this file.  Changing things
123 // in here should only be done by those who've read chapter 9 of the USB
124 // spec and relevant portions of any USB class specifications!
125
126
127 static uint8_t PROGMEM device_descriptor[] = {
128         18,                                     // bLength
129         1,                                      // bDescriptorType
130         0x00, 0x02,                             // bcdUSB
131         0,                                      // bDeviceClass
132         0,                                      // bDeviceSubClass
133         0,                                      // bDeviceProtocol
134         ENDPOINT0_SIZE,                         // bMaxPacketSize0
135         LSB(VENDOR_ID), MSB(VENDOR_ID),         // idVendor
136         LSB(PRODUCT_ID), MSB(PRODUCT_ID),       // idProduct
137         0x00, 0x01,                             // bcdDevice
138         1,                                      // iManufacturer
139         2,                                      // iProduct
140         0,                                      // iSerialNumber
141         1                                       // bNumConfigurations
142 };
143
144 // Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60
145 static uint8_t PROGMEM keyboard_hid_report_desc[] = {
146         0x05, 0x01,          // Usage Page (Generic Desktop),
147         0x09, 0x06,          // Usage (Keyboard),
148         0xA1, 0x01,          // Collection (Application),
149         0x75, 0x01,          //   Report Size (1),
150         0x95, 0x08,          //   Report Count (8),
151         0x05, 0x07,          //   Usage Page (Key Codes),
152         0x19, 0xE0,          //   Usage Minimum (224),
153         0x29, 0xE7,          //   Usage Maximum (231),
154         0x15, 0x00,          //   Logical Minimum (0),
155         0x25, 0x01,          //   Logical Maximum (1),
156         0x81, 0x02,          //   Input (Data, Variable, Absolute), ;Modifier byte
157         0x95, 0x01,          //   Report Count (1),
158         0x75, 0x08,          //   Report Size (8),
159         0x81, 0x03,          //   Input (Constant),                 ;Reserved byte
160         0x95, 0x05,          //   Report Count (5),
161         0x75, 0x01,          //   Report Size (1),
162         0x05, 0x08,          //   Usage Page (LEDs),
163         0x19, 0x01,          //   Usage Minimum (1),
164         0x29, 0x05,          //   Usage Maximum (5),
165         0x91, 0x02,          //   Output (Data, Variable, Absolute), ;LED report
166         0x95, 0x01,          //   Report Count (1),
167         0x75, 0x03,          //   Report Size (3),
168         0x91, 0x03,          //   Output (Constant),                 ;LED report padding
169         0x95, KBD_REPORT_KEYS,    //   Report Count (),
170         0x75, 0x08,          //   Report Size (8),
171         0x15, 0x00,          //   Logical Minimum (0),
172         0x25, 0xFF,          //   Logical Maximum(255),
173         0x05, 0x07,          //   Usage Page (Key Codes),
174         0x19, 0x00,          //   Usage Minimum (0),
175         0x29, 0xFF,          //   Usage Maximum (255),
176         0x81, 0x00,          //   Input (Data, Array),
177         0xc0                 // End Collection
178 };
179 #ifdef USB_NKRO_ENABLE
180 static uint8_t PROGMEM keyboard2_hid_report_desc[] = {
181         0x05, 0x01,                     // Usage Page (Generic Desktop),
182         0x09, 0x06,                     // Usage (Keyboard),
183         0xA1, 0x01,                     // Collection (Application),
184         // bitmap of modifiers
185         0x75, 0x01,                     //   Report Size (1),
186         0x95, 0x08,                     //   Report Count (8),
187         0x05, 0x07,                     //   Usage Page (Key Codes),
188         0x19, 0xE0,                     //   Usage Minimum (224),
189         0x29, 0xE7,                     //   Usage Maximum (231),
190         0x15, 0x00,                     //   Logical Minimum (0),
191         0x25, 0x01,                     //   Logical Maximum (1),
192         0x81, 0x02,                     //   Input (Data, Variable, Absolute), ;Modifier byte
193         // LED output report
194         0x95, 0x05,                     //   Report Count (5),
195         0x75, 0x01,                     //   Report Size (1),
196         0x05, 0x08,                     //   Usage Page (LEDs),
197         0x19, 0x01,                     //   Usage Minimum (1),
198         0x29, 0x05,                     //   Usage Maximum (5),
199         0x91, 0x02,                     //   Output (Data, Variable, Absolute),
200         0x95, 0x01,                     //   Report Count (1),
201         0x75, 0x03,                     //   Report Size (3),
202         0x91, 0x03,                     //   Output (Constant),
203         // bitmap of keys
204         0x95, KBD2_REPORT_KEYS*8,       //   Report Count (),
205         0x75, 0x01,                     //   Report Size (1),
206         0x15, 0x00,                     //   Logical Minimum (0),
207         0x25, 0x01,                     //   Logical Maximum(1),
208         0x05, 0x07,                     //   Usage Page (Key Codes),
209         0x19, 0x00,                     //   Usage Minimum (0),
210         0x29, KBD2_REPORT_KEYS*8-1,     //   Usage Maximum (),
211         0x81, 0x02,                     //   Input (Data, Variable, Absolute),
212         0xc0                            // End Collection
213 };
214 #endif
215
216 #ifdef USB_MOUSE_ENABLE
217 // Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
218 // http://www.microchip.com/forums/tm.aspx?high=&m=391435&mpage=1#391521
219 // http://www.keil.com/forum/15671/
220 // http://www.microsoft.com/whdc/device/input/wheel.mspx
221 static uint8_t PROGMEM mouse_hid_report_desc[] = {
222     0x05, 0x01,        // USAGE_PAGE (Generic Desktop)
223     0x09, 0x02,        // USAGE (Mouse)
224     0xa1, 0x01,        // COLLECTION (Application)
225     0x09, 0x02,        //   USAGE (Mouse)
226     0xa1, 0x02,        //   COLLECTION (Logical)
227     0x09, 0x01,        //     USAGE (Pointer)
228     0xa1, 0x00,        //     COLLECTION (Physical)
229                        // ------------------------------  Buttons
230     0x05, 0x09,        //       USAGE_PAGE (Button)
231     0x19, 0x01,        //       USAGE_MINIMUM (Button 1)
232     0x29, 0x05,        //       USAGE_MAXIMUM (Button 5)
233     0x15, 0x00,        //       LOGICAL_MINIMUM (0)
234     0x25, 0x01,        //       LOGICAL_MAXIMUM (1)
235     0x75, 0x01,        //       REPORT_SIZE (1)
236     0x95, 0x05,        //       REPORT_COUNT (5)
237     0x81, 0x02,        //       INPUT (Data,Var,Abs)
238                        // ------------------------------  Padding
239     0x75, 0x03,        //       REPORT_SIZE (3)
240     0x95, 0x01,        //       REPORT_COUNT (1)
241     0x81, 0x03,        //       INPUT (Cnst,Var,Abs)
242                        // ------------------------------  X,Y position
243     0x05, 0x01,        //       USAGE_PAGE (Generic Desktop)
244     0x09, 0x30,        //       USAGE (X)
245     0x09, 0x31,        //       USAGE (Y)
246     0x15, 0x81,        //       LOGICAL_MINIMUM (-127)
247     0x25, 0x7f,        //       LOGICAL_MAXIMUM (127)
248     0x75, 0x08,        //       REPORT_SIZE (8)
249     0x95, 0x02,        //       REPORT_COUNT (2)
250     0x81, 0x06,        //       INPUT (Data,Var,Rel)
251     0xa1, 0x02,        //       COLLECTION (Logical)
252                        // ------------------------------  Vertical wheel res multiplier
253     0x09, 0x48,        //         USAGE (Resolution Multiplier)
254     0x15, 0x00,        //         LOGICAL_MINIMUM (0)
255     0x25, 0x01,        //         LOGICAL_MAXIMUM (1)
256     0x35, 0x01,        //         PHYSICAL_MINIMUM (1)
257     0x45, 0x04,        //         PHYSICAL_MAXIMUM (4)
258     0x75, 0x02,        //         REPORT_SIZE (2)
259     0x95, 0x01,        //         REPORT_COUNT (1)
260     0xa4,              //         PUSH
261     0xb1, 0x02,        //         FEATURE (Data,Var,Abs)
262                        // ------------------------------  Vertical wheel
263     0x09, 0x38,        //         USAGE (Wheel)
264     0x15, 0x81,        //         LOGICAL_MINIMUM (-127)
265     0x25, 0x7f,        //         LOGICAL_MAXIMUM (127)
266     0x35, 0x00,        //         PHYSICAL_MINIMUM (0)        - reset physical
267     0x45, 0x00,        //         PHYSICAL_MAXIMUM (0)
268     0x75, 0x08,        //         REPORT_SIZE (8)
269     0x81, 0x06,        //         INPUT (Data,Var,Rel)
270     0xc0,              //       END_COLLECTION
271     0xa1, 0x02,        //       COLLECTION (Logical)
272                        // ------------------------------  Horizontal wheel res multiplier
273     0x09, 0x48,        //         USAGE (Resolution Multiplier)
274     0xb4,              //         POP
275     0xb1, 0x02,        //         FEATURE (Data,Var,Abs)
276                        // ------------------------------  Padding for Feature report
277     0x35, 0x00,        //         PHYSICAL_MINIMUM (0)        - reset physical
278     0x45, 0x00,        //         PHYSICAL_MAXIMUM (0)
279     0x75, 0x04,        //         REPORT_SIZE (4)
280     0xb1, 0x03,        //         FEATURE (Cnst,Var,Abs)
281                        // ------------------------------  Horizontal wheel
282     0x05, 0x0c,        //         USAGE_PAGE (Consumer Devices)
283     0x0a, 0x38, 0x02,  //         USAGE (AC Pan)
284     0x15, 0x81,        //         LOGICAL_MINIMUM (-127)
285     0x25, 0x7f,        //         LOGICAL_MAXIMUM (127)
286     0x75, 0x08,        //         REPORT_SIZE (8)
287     0x81, 0x06,        //         INPUT (Data,Var,Rel)
288     0xc0,              //       END_COLLECTION
289     0xc0,              //     END_COLLECTION
290     0xc0,              //   END_COLLECTION
291     0xc0               // END_COLLECTION
292 };
293 #endif
294
295 static uint8_t PROGMEM debug_hid_report_desc[] = {
296         0x06, 0x31, 0xFF,                       // Usage Page 0xFF31 (vendor defined)
297         0x09, 0x74,                             // Usage 0x74
298         0xA1, 0x53,                             // Collection 0x53
299         0x75, 0x08,                             // report size = 8 bits
300         0x15, 0x00,                             // logical minimum = 0
301         0x26, 0xFF, 0x00,                       // logical maximum = 255
302         0x95, DEBUG_TX_SIZE,                    // report count
303         0x09, 0x75,                             // usage
304         0x81, 0x02,                             // Input (array)
305         0xC0                                    // end collection
306 };
307
308 #ifdef USB_EXTRA_ENABLE
309 // audio controls & system controls
310 // http://www.microsoft.com/whdc/archive/w2kbd.mspx
311 static uint8_t PROGMEM extra_hid_report_desc[] = {
312     0x05, 0x0c,                    // USAGE_PAGE (Consumer Devices)
313     0x09, 0x01,                    // USAGE (Consumer Control)
314     0xa1, 0x01,                    // COLLECTION (Application)
315     0x85, 0x01,                    //   REPORT_ID (1)
316     0x09, 0xe9,                    //   USAGE (Volume Up)
317     0x09, 0xea,                    //   USAGE (Volume Down)
318     0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
319     0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
320     0x75, 0x01,                    //   REPORT_SIZE (1)
321     0x95, 0x02,                    //   REPORT_COUNT (2)
322     0x81, 0x02,                    //   INPUT (Data,Var,Abs)
323     0x09, 0xe2,                    //   USAGE (Mute)
324     0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
325     0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
326     0x75, 0x01,                    //   REPORT_SIZE (1)
327     0x95, 0x01,                    //   REPORT_COUNT (1)
328     0x81, 0x06,                    //   INPUT (Data,Var,Rel)
329     0x95, 0x05,                    //   REPORT_COUNT (5)
330     0x81, 0x07,                    //   INPUT (Cnst,Var,Abs)
331     0xc0,                          // END_COLLECTION
332
333     0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
334     0x09, 0x80,                    // USAGE (System Control)
335     0xa1, 0x01,                    // COLLECTION (Application)
336     0x85, 0x02,                    //   REPORT_ID (2)
337     0x19, 0x81,                    //   USAGE_MINIMUM (System Power Down)
338     0x29, 0x83,                    //   USAGE_MAXIMUM (System Wake Up)
339     0x95, 0x03,                    //   REPORT_COUNT (3)
340     0x81, 0x06,                    //   INPUT (Data,Var,Rel)
341     0x95, 0x05,                    //   REPORT_COUNT (5)
342     0x81, 0x07,                    //   INPUT (Cnst,Var,Rel)
343     0xc0                           // END_COLLECTION
344 };
345 #endif
346
347 #define KBD_HID_DESC_NUM                0
348 #define KBD_HID_DESC_OFFSET             (9+(9+9+7)*KBD_HID_DESC_NUM+9)
349
350 #ifdef USB_MOUSE_ENABLE
351 #   define MOUSE_HID_DESC_NUM           (KBD_HID_DESC_NUM + 1)
352 #   define MOUSE_HID_DESC_OFFSET        (9+(9+9+7)*MOUSE_HID_DESC_NUM+9)
353 #else
354 #   define MOUSE_HID_DESC_NUM           (KBD_HID_DESC_NUM + 0)
355 #endif
356
357 #define DEBUG_HID_DESC_NUM              (MOUSE_HID_DESC_NUM + 1)
358 #define DEBUG_HID_DESC_OFFSET           (9+(9+9+7)*DEBUG_HID_DESC_NUM+9)
359
360 #ifdef USB_EXTRA_ENABLE
361 #   define EXTRA_HID_DESC_NUM           (DEBUG_HID_DESC_NUM + 1)
362 #   define EXTRA_HID_DESC_OFFSET        (9+(9+9+7)*EXTRA_HID_DESC_NUM+9)
363 #else
364 #   define EXTRA_HID_DESC_NUM           (DEBUG_HID_DESC_NUM + 0)
365 #endif
366
367 #ifdef USB_NKRO_ENABLE
368 #   define KBD2_HID_DESC_NUM            (EXTRA_HID_DESC_NUM + 1)
369 #   define KBD2_HID_DESC_OFFSET         (9+(9+9+7)*EXTRA_HID_DESC_NUM+9)
370 #else
371 #   define KBD2_HID_DESC_NUM            (EXTRA_HID_DESC_NUM + 0)
372 #endif
373
374 #define NUM_INTERFACES                  (KBD2_HID_DESC_NUM + 1)
375 #define CONFIG1_DESC_SIZE               (9+(9+9+7)*NUM_INTERFACES)
376 static uint8_t PROGMEM config1_descriptor[CONFIG1_DESC_SIZE] = {
377         // configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
378         9,                                      // bLength;
379         2,                                      // bDescriptorType;
380         LSB(CONFIG1_DESC_SIZE),                 // wTotalLength
381         MSB(CONFIG1_DESC_SIZE),
382         NUM_INTERFACES,                         // bNumInterfaces
383         1,                                      // bConfigurationValue
384         0,                                      // iConfiguration
385         0xA0,                                   // bmAttributes
386         50,                                     // bMaxPower
387
388         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
389         9,                                      // bLength
390         4,                                      // bDescriptorType
391         KBD_INTERFACE,                          // bInterfaceNumber
392         0,                                      // bAlternateSetting
393         1,                                      // bNumEndpoints
394         0x03,                                   // bInterfaceClass (0x03 = HID)
395         0x01,                                   // bInterfaceSubClass (0x01 = Boot)
396         0x01,                                   // bInterfaceProtocol (0x01 = Keyboard)
397         0,                                      // iInterface
398         // HID descriptor, HID 1.11 spec, section 6.2.1
399         9,                                      // bLength
400         0x21,                                   // bDescriptorType
401         0x11, 0x01,                             // bcdHID
402         0,                                      // bCountryCode
403         1,                                      // bNumDescriptors
404         0x22,                                   // bDescriptorType
405         sizeof(keyboard_hid_report_desc),       // wDescriptorLength
406         0,
407         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
408         7,                                      // bLength
409         5,                                      // bDescriptorType
410         KBD_ENDPOINT | 0x80,                    // bEndpointAddress
411         0x03,                                   // bmAttributes (0x03=intr)
412         KBD_SIZE, 0,                            // wMaxPacketSize
413         10,                                     // bInterval
414
415 #ifdef USB_MOUSE_ENABLE
416         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
417         9,                                      // bLength
418         4,                                      // bDescriptorType
419         MOUSE_INTERFACE,                        // bInterfaceNumber
420         0,                                      // bAlternateSetting
421         1,                                      // bNumEndpoints
422         0x03,                                   // bInterfaceClass (0x03 = HID)
423         // ThinkPad T23 BIOS doesn't work with boot mouse.
424         0x00,                                   // bInterfaceSubClass (0x01 = Boot)
425         0x00,                                   // bInterfaceProtocol (0x02 = Mouse)
426 /*
427         0x01,                                   // bInterfaceSubClass (0x01 = Boot)
428         0x02,                                   // bInterfaceProtocol (0x02 = Mouse)
429 */
430         0,                                      // iInterface
431         // HID descriptor, HID 1.11 spec, section 6.2.1
432         9,                                      // bLength
433         0x21,                                   // bDescriptorType
434         0x11, 0x01,                             // bcdHID
435         0,                                      // bCountryCode
436         1,                                      // bNumDescriptors
437         0x22,                                   // bDescriptorType
438         sizeof(mouse_hid_report_desc),          // wDescriptorLength
439         0,
440         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
441         7,                                      // bLength
442         5,                                      // bDescriptorType
443         MOUSE_ENDPOINT | 0x80,                  // bEndpointAddress
444         0x03,                                   // bmAttributes (0x03=intr)
445         MOUSE_SIZE, 0,                          // wMaxPacketSize
446         1,                                      // bInterval
447 #endif
448
449         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
450         9,                                      // bLength
451         4,                                      // bDescriptorType
452         DEBUG_INTERFACE,                        // bInterfaceNumber
453         0,                                      // bAlternateSetting
454         1,                                      // bNumEndpoints
455         0x03,                                   // bInterfaceClass (0x03 = HID)
456         0x00,                                   // bInterfaceSubClass
457         0x00,                                   // bInterfaceProtocol
458         0,                                      // iInterface
459         // HID descriptor, HID 1.11 spec, section 6.2.1
460         9,                                      // bLength
461         0x21,                                   // bDescriptorType
462         0x11, 0x01,                             // bcdHID
463         0,                                      // bCountryCode
464         1,                                      // bNumDescriptors
465         0x22,                                   // bDescriptorType
466         sizeof(debug_hid_report_desc),          // wDescriptorLength
467         0,
468         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
469         7,                                      // bLength
470         5,                                      // bDescriptorType
471         DEBUG_TX_ENDPOINT | 0x80,               // bEndpointAddress
472         0x03,                                   // bmAttributes (0x03=intr)
473         DEBUG_TX_SIZE, 0,                       // wMaxPacketSize
474         1,                                      // bInterval
475
476 #ifdef USB_EXTRA_ENABLE
477         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
478         9,                                      // bLength
479         4,                                      // bDescriptorType
480         EXTRA_INTERFACE,                        // bInterfaceNumber
481         0,                                      // bAlternateSetting
482         1,                                      // bNumEndpoints
483         0x03,                                   // bInterfaceClass (0x03 = HID)
484         0x00,                                   // bInterfaceSubClass
485         0x00,                                   // bInterfaceProtocol
486         0,                                      // iInterface
487         // HID descriptor, HID 1.11 spec, section 6.2.1
488         9,                                      // bLength
489         0x21,                                   // bDescriptorType
490         0x11, 0x01,                             // bcdHID
491         0,                                      // bCountryCode
492         1,                                      // bNumDescriptors
493         0x22,                                   // bDescriptorType
494         sizeof(extra_hid_report_desc),          // wDescriptorLength
495         0,
496         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
497         7,                                      // bLength
498         5,                                      // bDescriptorType
499         EXTRA_ENDPOINT | 0x80,                  // bEndpointAddress
500         0x03,                                   // bmAttributes (0x03=intr)
501         EXTRA_SIZE, 0,                          // wMaxPacketSize
502         10,                                     // bInterval
503 #endif
504
505 #ifdef USB_NKRO_ENABLE
506         // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
507         9,                                      // bLength
508         4,                                      // bDescriptorType
509         KBD2_INTERFACE,                         // bInterfaceNumber
510         0,                                      // bAlternateSetting
511         1,                                      // bNumEndpoints
512         0x03,                                   // bInterfaceClass (0x03 = HID)
513         0x00,                                   // bInterfaceSubClass (0x01 = Boot)
514         0x00,                                   // bInterfaceProtocol (0x01 = Keyboard)
515         0,                                      // iInterface
516         // HID descriptor, HID 1.11 spec, section 6.2.1
517         9,                                      // bLength
518         0x21,                                   // bDescriptorType
519         0x11, 0x01,                             // bcdHID
520         0,                                      // bCountryCode
521         1,                                      // bNumDescriptors
522         0x22,                                   // bDescriptorType
523         sizeof(keyboard2_hid_report_desc),      // wDescriptorLength
524         0,
525         // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
526         7,                                      // bLength
527         5,                                      // bDescriptorType
528         KBD2_ENDPOINT | 0x80,                   // bEndpointAddress
529         0x03,                                   // bmAttributes (0x03=intr)
530         KBD2_SIZE, 0,                           // wMaxPacketSize
531         1,                                      // bInterval
532 #endif
533 };
534
535 // If you're desperate for a little extra code memory, these strings
536 // can be completely removed if iManufacturer, iProduct, iSerialNumber
537 // in the device desciptor are changed to zeros.
538 struct usb_string_descriptor_struct {
539         uint8_t bLength;
540         uint8_t bDescriptorType;
541         int16_t wString[];
542 };
543 static struct usb_string_descriptor_struct PROGMEM string0 = {
544         4,
545         3,
546         {0x0409}
547 };
548 static struct usb_string_descriptor_struct PROGMEM string1 = {
549         sizeof(STR_MANUFACTURER),
550         3,
551         STR_MANUFACTURER
552 };
553 static struct usb_string_descriptor_struct PROGMEM string2 = {
554         sizeof(STR_PRODUCT),
555         3,
556         STR_PRODUCT
557 };
558
559 // This table defines which descriptor data is sent for each specific
560 // request from the host (in wValue and wIndex).
561 static struct descriptor_list_struct {
562         uint16_t        wValue;     // descriptor type
563         uint16_t        wIndex;
564         const uint8_t   *addr;
565         uint8_t         length;
566 } PROGMEM descriptor_list[] = {
567         // DEVICE descriptor
568         {0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)},
569         // CONFIGURATION descriptor
570         {0x0200, 0x0000, config1_descriptor, sizeof(config1_descriptor)},
571         // HID/REPORT descriptors
572         {0x2100, KBD_INTERFACE, config1_descriptor+KBD_HID_DESC_OFFSET, 9},
573         {0x2200, KBD_INTERFACE, keyboard_hid_report_desc, sizeof(keyboard_hid_report_desc)},
574 #ifdef USB_MOUSE_ENABLE
575         {0x2100, MOUSE_INTERFACE, config1_descriptor+MOUSE_HID_DESC_OFFSET, 9},
576         {0x2200, MOUSE_INTERFACE, mouse_hid_report_desc, sizeof(mouse_hid_report_desc)},
577 #endif
578         {0x2100, DEBUG_INTERFACE, config1_descriptor+DEBUG_HID_DESC_OFFSET, 9},
579         {0x2200, DEBUG_INTERFACE, debug_hid_report_desc, sizeof(debug_hid_report_desc)},
580 #ifdef USB_EXTRA_ENABLE
581         {0x2100, EXTRA_INTERFACE, config1_descriptor+EXTRA_HID_DESC_OFFSET, 9},
582         {0x2200, EXTRA_INTERFACE, extra_hid_report_desc, sizeof(extra_hid_report_desc)},
583 #endif
584 #ifdef USB_NKRO_ENABLE
585         {0x2100, KBD2_INTERFACE, config1_descriptor+KBD2_HID_DESC_OFFSET, 9},
586         {0x2200, KBD2_INTERFACE, keyboard2_hid_report_desc, sizeof(keyboard2_hid_report_desc)},
587 #endif
588         // STRING descriptors
589         {0x0300, 0x0000, (const uint8_t *)&string0, 4},
590         {0x0301, 0x0409, (const uint8_t *)&string1, sizeof(STR_MANUFACTURER)},
591         {0x0302, 0x0409, (const uint8_t *)&string2, sizeof(STR_PRODUCT)}
592 };
593 #define NUM_DESC_LIST (sizeof(descriptor_list)/sizeof(struct descriptor_list_struct))
594
595
596 /**************************************************************************
597  *
598  *  Variables - these are the only non-stack RAM usage
599  *
600  **************************************************************************/
601
602 // zero when we are not configured, non-zero when enumerated
603 static volatile uint8_t usb_configuration=0;
604
605
606 /**************************************************************************
607  *
608  *  Public Functions - these are the API intended for the user
609  *
610  **************************************************************************/
611
612
613 // initialize USB
614 void usb_init(void)
615 {
616         HW_CONFIG();
617         USB_FREEZE();                           // enable USB
618         PLL_CONFIG();                           // config PLL
619         while (!(PLLCSR & (1<<PLOCK))) ;        // wait for PLL lock
620         USB_CONFIG();                           // start USB clock
621         UDCON = 0;                              // enable attach resistor
622         usb_configuration = 0;
623         UDIEN = (1<<EORSTE)|(1<<SOFE)|(1<<SUSPE);
624         sei();
625 }
626
627 // return 0 if the USB is not configured, or the configuration
628 // number selected by the HOST
629 uint8_t usb_configured(void)
630 {
631         return usb_configuration && !suspend;
632 }
633
634 void usb_remote_wakeup(void)
635 {
636     UDCON |= (1<<RMWKUP);
637 }
638
639
640
641 /**************************************************************************
642  *
643  *  Private Functions - not intended for general user consumption....
644  *
645  **************************************************************************/
646
647
648
649 // USB Device Interrupt - handle all device-level events
650 // the transmit buffer flushing is triggered by the start of frame
651 //
652 ISR(USB_GEN_vect)
653 {
654         uint8_t intbits, t, i;
655         static uint8_t div4=0;
656
657         intbits = UDINT;
658         UDINT = 0;
659         if (intbits & (1<<SUSPI)) {
660             suspend = true;
661         } else {
662             suspend = false;
663         }
664         if (intbits & (1<<EORSTI)) {
665                 UENUM = 0;
666                 UECONX = 1;
667                 UECFG0X = EP_TYPE_CONTROL;
668                 UECFG1X = EP_SIZE(ENDPOINT0_SIZE) | EP_SINGLE_BUFFER;
669                 UEIENX = (1<<RXSTPE);
670                 usb_configuration = 0;
671         }
672         if ((intbits & (1<<SOFI)) && usb_configuration) {
673                 t = debug_flush_timer;
674                 if (t) {
675                         debug_flush_timer = -- t;
676                         if (!t) {
677                                 UENUM = DEBUG_TX_ENDPOINT;
678                                 while ((UEINTX & (1<<RWAL))) {
679                                         UEDATX = 0;
680                                 }
681                                 UEINTX = 0x3A;
682                         }
683                 }
684                 if (usb_keyboard_idle_config && (++div4 & 3) == 0) {
685                         UENUM = KBD_ENDPOINT;
686                         if (UEINTX & (1<<RWAL)) {
687                                 usb_keyboard_idle_count++;
688                                 if (usb_keyboard_idle_count == usb_keyboard_idle_config) {
689                                         usb_keyboard_idle_count = 0;
690                                         UEDATX = keyboard_report_prev->mods;
691                                         UEDATX = 0;
692                                         uint8_t keys = usb_keyboard_protocol ? KBD_REPORT_KEYS : 6;
693                                         for (i=0; i<keys; i++) {
694                                                 UEDATX = keyboard_report_prev->keys[i];
695                                         }
696                                         UEINTX = 0x3A;
697                                 }
698                         }
699                 }
700         }
701 }
702
703
704
705 // Misc functions to wait for ready and send/receive packets
706 static inline void usb_wait_in_ready(void)
707 {
708         while (!(UEINTX & (1<<TXINI))) ;
709 }
710 static inline void usb_send_in(void)
711 {
712         UEINTX = ~(1<<TXINI);
713 }
714 static inline void usb_wait_receive_out(void)
715 {
716         while (!(UEINTX & (1<<RXOUTI))) ;
717 }
718 static inline void usb_ack_out(void)
719 {
720         UEINTX = ~(1<<RXOUTI);
721 }
722
723
724
725 // USB Endpoint Interrupt - endpoint 0 is handled here.  The
726 // other endpoints are manipulated by the user-callable
727 // functions, and the start-of-frame interrupt.
728 //
729 ISR(USB_COM_vect)
730 {
731         uint8_t intbits;
732         const uint8_t *list;
733         const uint8_t *cfg;
734         uint8_t i, n, len, en;
735         uint8_t bmRequestType;
736         uint8_t bRequest;
737         uint16_t wValue;
738         uint16_t wIndex;
739         uint16_t wLength;
740         uint16_t desc_val;
741         const uint8_t *desc_addr;
742         uint8_t desc_length;
743
744         UENUM = 0;
745         intbits = UEINTX;
746         if (intbits & (1<<RXSTPI)) {
747                 bmRequestType = UEDATX;
748                 bRequest = UEDATX;
749                 wValue = UEDATX;
750                 wValue |= (UEDATX << 8);
751                 wIndex = UEDATX;
752                 wIndex |= (UEDATX << 8);
753                 wLength = UEDATX;
754                 wLength |= (UEDATX << 8);
755                 UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
756                 if (bRequest == GET_DESCRIPTOR) {
757                         list = (const uint8_t *)descriptor_list;
758                         for (i=0; ; i++) {
759                                 if (i >= NUM_DESC_LIST) {
760                                         UECONX = (1<<STALLRQ)|(1<<EPEN);  //stall
761                                         return;
762                                 }
763                                 desc_val = pgm_read_word(list);
764                                 if (desc_val != wValue) {
765                                         list += sizeof(struct descriptor_list_struct);
766                                         continue;
767                                 }
768                                 list += 2;
769                                 desc_val = pgm_read_word(list);
770                                 if (desc_val != wIndex) {
771                                         list += sizeof(struct descriptor_list_struct)-2;
772                                         continue;
773                                 }
774                                 list += 2;
775                                 desc_addr = (const uint8_t *)pgm_read_word(list);
776                                 list += 2;
777                                 desc_length = pgm_read_byte(list);
778                                 break;
779                         }
780                         len = (wLength < 256) ? wLength : 255;
781                         if (len > desc_length) len = desc_length;
782                         do {
783                                 // wait for host ready for IN packet
784                                 do {
785                                         i = UEINTX;
786                                 } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
787                                 if (i & (1<<RXOUTI)) return;    // abort
788                                 // send IN packet
789                                 n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
790                                 for (i = n; i; i--) {
791                                         UEDATX = pgm_read_byte(desc_addr++);
792                                 }
793                                 len -= n;
794                                 usb_send_in();
795                         } while (len || n == ENDPOINT0_SIZE);
796                         return;
797                 }
798                 if (bRequest == SET_ADDRESS) {
799                         usb_send_in();
800                         usb_wait_in_ready();
801                         UDADDR = wValue | (1<<ADDEN);
802                         return;
803                 }
804                 if (bRequest == SET_CONFIGURATION && bmRequestType == 0) {
805                         usb_configuration = wValue;
806                         usb_send_in();
807                         cfg = endpoint_config_table;
808                         for (i=1; i<=6; i++) {
809                                 UENUM = i;
810                                 en = pgm_read_byte(cfg++);
811                                 if (en) {
812                                     UECONX = (1<<EPEN);
813                                     UECFG0X = pgm_read_byte(cfg++);
814                                     UECFG1X = pgm_read_byte(cfg++);
815                                 } else {
816                                     UECONX = 0;
817                                 }
818                         }
819                         UERST = 0x7E;
820                         UERST = 0;
821                         return;
822                 }
823                 if (bRequest == GET_CONFIGURATION && bmRequestType == 0x80) {
824                         usb_wait_in_ready();
825                         UEDATX = usb_configuration;
826                         usb_send_in();
827                         return;
828                 }
829
830                 if (bRequest == GET_STATUS) {
831                         usb_wait_in_ready();
832                         i = 0;
833                         #ifdef SUPPORT_ENDPOINT_HALT
834                         if (bmRequestType == 0x82) {
835                                 UENUM = wIndex;
836                                 if (UECONX & (1<<STALLRQ)) i = 1;
837                                 UENUM = 0;
838                         }
839                         #endif
840                         UEDATX = i;
841                         UEDATX = 0;
842                         usb_send_in();
843                         return;
844                 }
845                 if (bRequest == CLEAR_FEATURE || bRequest == SET_FEATURE) {
846 #ifdef SUPPORT_ENDPOINT_HALT
847                     if (bmRequestType == 0x02 && wValue == ENDPOINT_HALT) {
848                         i = wIndex & 0x7F;
849                         if (i >= 1 && i <= MAX_ENDPOINT) {
850                                 usb_send_in();
851                                 UENUM = i;
852                                 if (bRequest == SET_FEATURE) {
853                                         UECONX = (1<<STALLRQ)|(1<<EPEN);
854                                 } else {
855                                         UECONX = (1<<STALLRQC)|(1<<RSTDT)|(1<<EPEN);
856                                         UERST = (1 << i);
857                                         UERST = 0;
858                                 }
859                                 return;
860                         }
861                     }
862 #endif
863                     if (bmRequestType == 0x00 && wValue == DEVICE_REMOTE_WAKEUP) {
864                         if (bRequest == SET_FEATURE) {
865                             remote_wakeup = true;   
866                         } else {
867                             remote_wakeup = false;
868                         }
869                         usb_send_in();
870                         return;
871                     }
872                 }
873                 if (wIndex == KBD_INTERFACE) {
874                         if (bmRequestType == 0xA1) {
875                                 if (bRequest == HID_GET_REPORT) {
876                                         usb_wait_in_ready();
877                                         UEDATX = keyboard_report->mods;
878                                         UEDATX = 0;
879                                         for (i=0; i<6; i++) {
880                                                 UEDATX = keyboard_report->keys[i];
881                                         }
882                                         usb_send_in();
883                                         return;
884                                 }
885                                 if (bRequest == HID_GET_IDLE) {
886                                         usb_wait_in_ready();
887                                         UEDATX = usb_keyboard_idle_config;
888                                         usb_send_in();
889                                         return;
890                                 }
891                                 if (bRequest == HID_GET_PROTOCOL) {
892                                         usb_wait_in_ready();
893                                         UEDATX = usb_keyboard_protocol;
894                                         usb_send_in();
895                                         return;
896                                 }
897                         }
898                         if (bmRequestType == 0x21) {
899                                 if (bRequest == HID_SET_REPORT) {
900                                         usb_wait_receive_out();
901                                         usb_keyboard_leds = UEDATX;
902                                         usb_ack_out();
903                                         usb_send_in();
904                                         return;
905                                 }
906                                 if (bRequest == HID_SET_IDLE) {
907                                         usb_keyboard_idle_config = (wValue >> 8);
908                                         usb_keyboard_idle_count = 0;
909                                         //usb_wait_in_ready();
910                                         usb_send_in();
911                                         return;
912                                 }
913                                 if (bRequest == HID_SET_PROTOCOL) {
914                                         usb_keyboard_protocol = wValue;
915                                         //usb_wait_in_ready();
916                                         usb_send_in();
917                                         return;
918                                 }
919                         }
920                 }
921 #ifdef USB_MOUSE_ENABLE
922                 if (wIndex == MOUSE_INTERFACE) {
923                         if (bmRequestType == 0xA1) {
924                                 if (bRequest == HID_GET_REPORT) {
925                                     if (wValue == HID_REPORT_INPUT) {
926                                         usb_wait_in_ready();
927                                         UEDATX = 0;
928                                         UEDATX = 0;
929                                         UEDATX = 0;
930                                         UEDATX = 0;
931                                         usb_send_in();
932                                         return;
933                                     }
934                                     if (wValue == HID_REPORT_FEATURE) {
935                                         usb_wait_in_ready();
936                                         UEDATX = 0x05;
937                                         usb_send_in();
938                                         return;
939                                     }
940                                 }
941                                 if (bRequest == HID_GET_PROTOCOL) {
942                                         usb_wait_in_ready();
943                                         UEDATX = usb_mouse_protocol;
944                                         usb_send_in();
945                                         return;
946                                 }
947                         }
948                         if (bmRequestType == 0x21) {
949                                 if (bRequest == HID_SET_PROTOCOL) {
950                                         usb_mouse_protocol = wValue;
951                                         usb_send_in();
952                                         return;
953                                 }
954                         }
955                 }
956 #endif
957                 if (wIndex == DEBUG_INTERFACE) {
958                         if (bRequest == HID_GET_REPORT && bmRequestType == 0xA1) {
959                                 len = wLength;
960                                 do {
961                                         // wait for host ready for IN packet
962                                         do {
963                                                 i = UEINTX;
964                                         } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
965                                         if (i & (1<<RXOUTI)) return;    // abort
966                                         // send IN packet
967                                         n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
968                                         for (i = n; i; i--) {
969                                                 UEDATX = 0;
970                                         }
971                                         len -= n;
972                                         usb_send_in();
973                                 } while (len || n == ENDPOINT0_SIZE);
974                                 return;
975                         }
976                 }
977         }
978         UECONX = (1<<STALLRQ) | (1<<EPEN);      // stall
979 }