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