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