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