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