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