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