]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/chibios/usb_main.c
Merge branch 'master' of github.com:jackhumbert/qmk_firmware
[qmk_firmware.git] / tmk_core / protocol / chibios / usb_main.c
1 /*
2  * (c) 2015 flabberast <s3+flabbergast@sdfeu.org>
3  *
4  * Based on the following work:
5  *  - Guillaume Duc's raw hid example (MIT License)
6  *    https://github.com/guiduc/usb-hid-chibios-example
7  *  - PJRC Teensy examples (MIT License)
8  *    https://www.pjrc.com/teensy/usb_keyboard.html
9  *  - hasu's TMK keyboard code (GPL v2 and some code Modified BSD)
10  *    https://github.com/tmk/tmk_keyboard/
11  *  - ChibiOS demo code (Apache 2.0 License)
12  *    http://www.chibios.org
13  *
14  * Since some GPL'd code is used, this work is licensed under
15  * GPL v2 or later.
16  */
17
18 #include "ch.h"
19 #include "hal.h"
20
21 #include "usb_main.h"
22
23 #include "host.h"
24 #include "debug.h"
25 #include "suspend.h"
26 #ifdef SLEEP_LED_ENABLE
27 #include "sleep_led.h"
28 #include "led.h"
29 #endif
30
31 /* ---------------------------------------------------------
32  *       Global interface variables and declarations
33  * ---------------------------------------------------------
34  */
35
36 uint8_t keyboard_idle __attribute__((aligned(2))) = 0;
37 uint8_t keyboard_protocol __attribute__((aligned(2))) = 1;
38 uint16_t keyboard_led_stats __attribute__((aligned(2))) = 0;
39 volatile uint16_t keyboard_idle_count = 0;
40 static virtual_timer_t keyboard_idle_timer;
41 static void keyboard_idle_timer_cb(void *arg);
42 #ifdef NKRO_ENABLE
43 extern bool keyboard_nkro;
44 #endif /* NKRO_ENABLE */
45
46 report_keyboard_t keyboard_report_sent = {{0}};
47 #ifdef MOUSE_ENABLE
48 report_mouse_t mouse_report_blank = {0};
49 #endif /* MOUSE_ENABLE */
50 #ifdef EXTRAKEY_ENABLE
51 uint8_t extra_report_blank[3] = {0};
52 #endif /* EXTRAKEY_ENABLE */
53
54 #ifdef CONSOLE_ENABLE
55 /* The emission buffers queue */
56 output_buffers_queue_t console_buf_queue;
57 static uint8_t console_queue_buffer[BQ_BUFFER_SIZE(CONSOLE_QUEUE_CAPACITY, CONSOLE_EPSIZE)];
58
59 static virtual_timer_t console_flush_timer;
60 void console_queue_onotify(io_buffers_queue_t *bqp);
61 static void console_flush_cb(void *arg);
62 #endif /* CONSOLE_ENABLE */
63
64 /* ---------------------------------------------------------
65  *            Descriptors and USB driver objects
66  * ---------------------------------------------------------
67  */
68
69 /* HID specific constants */
70 #define USB_DESCRIPTOR_HID 0x21
71 #define USB_DESCRIPTOR_HID_REPORT 0x22
72 #define HID_GET_REPORT 0x01
73 #define HID_GET_IDLE 0x02
74 #define HID_GET_PROTOCOL 0x03
75 #define HID_SET_REPORT 0x09
76 #define HID_SET_IDLE 0x0A
77 #define HID_SET_PROTOCOL 0x0B
78
79 /* USB Device Descriptor */
80 static const uint8_t usb_device_descriptor_data[] = {
81   USB_DESC_DEVICE(0x0200,      // bcdUSB (1.1)
82                   0,           // bDeviceClass (defined in later in interface)
83                   0,           // bDeviceSubClass
84                   0,           // bDeviceProtocol
85                   64,          // bMaxPacketSize (64 bytes) (the driver didn't work with 32)
86                   VENDOR_ID,   // idVendor
87                   PRODUCT_ID,  // idProduct
88                   DEVICE_VER,      // bcdDevice
89                   1,           // iManufacturer
90                   2,           // iProduct
91                   3,           // iSerialNumber
92                   1)           // bNumConfigurations
93 };
94
95 /* Device Descriptor wrapper */
96 static const USBDescriptor usb_device_descriptor = {
97   sizeof usb_device_descriptor_data,
98   usb_device_descriptor_data
99 };
100
101 /*
102  * HID Report Descriptor
103  *
104  * See "Device Class Definition for Human Interface Devices (HID)"
105  * (http://www.usb.org/developers/hidpage/HID1_11.pdf) for the
106  * detailed descrition of all the fields
107  */
108
109 /* Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60 */
110 static const uint8_t keyboard_hid_report_desc_data[] = {
111   0x05, 0x01,                // Usage Page (Generic Desktop),
112   0x09, 0x06,                // Usage (Keyboard),
113   0xA1, 0x01,                // Collection (Application),
114   0x75, 0x01,                //   Report Size (1),
115   0x95, 0x08,                //   Report Count (8),
116   0x05, 0x07,                //   Usage Page (Key Codes),
117   0x19, 0xE0,                //   Usage Minimum (224),
118   0x29, 0xE7,                //   Usage Maximum (231),
119   0x15, 0x00,                //   Logical Minimum (0),
120   0x25, 0x01,                //   Logical Maximum (1),
121   0x81, 0x02,                //   Input (Data, Variable, Absolute), ;Modifier byte
122   0x95, 0x01,                //   Report Count (1),
123   0x75, 0x08,                //   Report Size (8),
124   0x81, 0x03,                //   Input (Constant),                 ;Reserved byte
125   0x95, 0x05,                //   Report Count (5),
126   0x75, 0x01,                //   Report Size (1),
127   0x05, 0x08,                //   Usage Page (LEDs),
128   0x19, 0x01,                //   Usage Minimum (1),
129   0x29, 0x05,                //   Usage Maximum (5),
130   0x91, 0x02,                //   Output (Data, Variable, Absolute), ;LED report
131   0x95, 0x01,                //   Report Count (1),
132   0x75, 0x03,                //   Report Size (3),
133   0x91, 0x03,                //   Output (Constant),                 ;LED report padding
134   0x95, KBD_REPORT_KEYS,          //   Report Count (),
135   0x75, 0x08,                //   Report Size (8),
136   0x15, 0x00,                //   Logical Minimum (0),
137   0x25, 0xFF,                //   Logical Maximum(255),
138   0x05, 0x07,                //   Usage Page (Key Codes),
139   0x19, 0x00,                //   Usage Minimum (0),
140   0x29, 0xFF,                //   Usage Maximum (255),
141   0x81, 0x00,                //   Input (Data, Array),
142   0xc0                       // End Collection
143 };
144 /* wrapper */
145 static const USBDescriptor keyboard_hid_report_descriptor = {
146   sizeof keyboard_hid_report_desc_data,
147   keyboard_hid_report_desc_data
148 };
149
150 #ifdef NKRO_ENABLE
151 static const uint8_t nkro_hid_report_desc_data[] = {
152   0x05, 0x01,                           // Usage Page (Generic Desktop),
153   0x09, 0x06,                           // Usage (Keyboard),
154   0xA1, 0x01,                           // Collection (Application),
155   // bitmap of modifiers
156   0x75, 0x01,                           //   Report Size (1),
157   0x95, 0x08,                           //   Report Count (8),
158   0x05, 0x07,                           //   Usage Page (Key Codes),
159   0x19, 0xE0,                           //   Usage Minimum (224),
160   0x29, 0xE7,                           //   Usage Maximum (231),
161   0x15, 0x00,                           //   Logical Minimum (0),
162   0x25, 0x01,                           //   Logical Maximum (1),
163   0x81, 0x02,                           //   Input (Data, Variable, Absolute), ;Modifier byte
164   // LED output report
165   0x95, 0x05,                           //   Report Count (5),
166   0x75, 0x01,                           //   Report Size (1),
167   0x05, 0x08,                           //   Usage Page (LEDs),
168   0x19, 0x01,                           //   Usage Minimum (1),
169   0x29, 0x05,                           //   Usage Maximum (5),
170   0x91, 0x02,                           //   Output (Data, Variable, Absolute),
171   0x95, 0x01,                           //   Report Count (1),
172   0x75, 0x03,                           //   Report Size (3),
173   0x91, 0x03,                           //   Output (Constant),
174   // bitmap of keys
175   0x95, NKRO_REPORT_KEYS * 8,           //   Report Count (),
176   0x75, 0x01,                           //   Report Size (1),
177   0x15, 0x00,                           //   Logical Minimum (0),
178   0x25, 0x01,                           //   Logical Maximum(1),
179   0x05, 0x07,                           //   Usage Page (Key Codes),
180   0x19, 0x00,                           //   Usage Minimum (0),
181   0x29, NKRO_REPORT_KEYS * 8 - 1,       //   Usage Maximum (),
182   0x81, 0x02,                           //   Input (Data, Variable, Absolute),
183   0xc0                                  // End Collection
184 };
185 /* wrapper */
186 static const USBDescriptor nkro_hid_report_descriptor = {
187   sizeof nkro_hid_report_desc_data,
188   nkro_hid_report_desc_data
189 };
190 #endif /* NKRO_ENABLE */
191
192 #ifdef MOUSE_ENABLE
193 /* Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
194  * http://www.microchip.com/forums/tm.aspx?high=&m=391435&mpage=1#391521
195  * http://www.keil.com/forum/15671/
196  * http://www.microsoft.com/whdc/device/input/wheel.mspx */
197 static const uint8_t mouse_hid_report_desc_data[] = {
198   /* mouse */
199   0x05, 0x01,                      // USAGE_PAGE (Generic Desktop)
200   0x09, 0x02,                      // USAGE (Mouse)
201   0xa1, 0x01,                      // COLLECTION (Application)
202   //0x85, REPORT_ID_MOUSE,         //   REPORT_ID (1)
203   0x09, 0x01,                      //   USAGE (Pointer)
204   0xa1, 0x00,                      //   COLLECTION (Physical)
205                                    // ----------------------------  Buttons
206   0x05, 0x09,                      //     USAGE_PAGE (Button)
207   0x19, 0x01,                      //     USAGE_MINIMUM (Button 1)
208   0x29, 0x05,                      //     USAGE_MAXIMUM (Button 5)
209   0x15, 0x00,                      //     LOGICAL_MINIMUM (0)
210   0x25, 0x01,                      //     LOGICAL_MAXIMUM (1)
211   0x75, 0x01,                      //     REPORT_SIZE (1)
212   0x95, 0x05,                      //     REPORT_COUNT (5)
213   0x81, 0x02,                      //     INPUT (Data,Var,Abs)
214   0x75, 0x03,                      //     REPORT_SIZE (3)
215   0x95, 0x01,                      //     REPORT_COUNT (1)
216   0x81, 0x03,                      //     INPUT (Cnst,Var,Abs)
217                                    // ----------------------------  X,Y position
218   0x05, 0x01,                      //     USAGE_PAGE (Generic Desktop)
219   0x09, 0x30,                      //     USAGE (X)
220   0x09, 0x31,                      //     USAGE (Y)
221   0x15, 0x81,                      //     LOGICAL_MINIMUM (-127)
222   0x25, 0x7f,                      //     LOGICAL_MAXIMUM (127)
223   0x75, 0x08,                      //     REPORT_SIZE (8)
224   0x95, 0x02,                      //     REPORT_COUNT (2)
225   0x81, 0x06,                      //     INPUT (Data,Var,Rel)
226                                    // ----------------------------  Vertical wheel
227   0x09, 0x38,                      //     USAGE (Wheel)
228   0x15, 0x81,                      //     LOGICAL_MINIMUM (-127)
229   0x25, 0x7f,                      //     LOGICAL_MAXIMUM (127)
230   0x35, 0x00,                      //     PHYSICAL_MINIMUM (0)        - reset physical
231   0x45, 0x00,                      //     PHYSICAL_MAXIMUM (0)
232   0x75, 0x08,                      //     REPORT_SIZE (8)
233   0x95, 0x01,                      //     REPORT_COUNT (1)
234   0x81, 0x06,                      //     INPUT (Data,Var,Rel)
235                                    // ----------------------------  Horizontal wheel
236   0x05, 0x0c,                      //     USAGE_PAGE (Consumer Devices)
237   0x0a, 0x38, 0x02,                //     USAGE (AC Pan)
238   0x15, 0x81,                      //     LOGICAL_MINIMUM (-127)
239   0x25, 0x7f,                      //     LOGICAL_MAXIMUM (127)
240   0x75, 0x08,                      //     REPORT_SIZE (8)
241   0x95, 0x01,                      //     REPORT_COUNT (1)
242   0x81, 0x06,                      //     INPUT (Data,Var,Rel)
243   0xc0,                            //   END_COLLECTION
244   0xc0,                            // END_COLLECTION
245 };
246 /* wrapper */
247 static const USBDescriptor mouse_hid_report_descriptor = {
248   sizeof mouse_hid_report_desc_data,
249   mouse_hid_report_desc_data
250 };
251 #endif /* MOUSE_ENABLE */
252
253 #ifdef CONSOLE_ENABLE
254 static const uint8_t console_hid_report_desc_data[] = {
255   0x06, 0x31, 0xFF, // Usage Page 0xFF31 (vendor defined)
256   0x09, 0x74,       // Usage 0x74
257   0xA1, 0x53,       // Collection 0x53
258   0x75, 0x08,       // report size = 8 bits
259   0x15, 0x00,       // logical minimum = 0
260   0x26, 0xFF, 0x00, // logical maximum = 255
261   0x95, CONSOLE_EPSIZE, // report count
262   0x09, 0x75,       // usage
263   0x81, 0x02,       // Input (array)
264   0xC0              // end collection
265 };
266 /* wrapper */
267 static const USBDescriptor console_hid_report_descriptor = {
268   sizeof console_hid_report_desc_data,
269   console_hid_report_desc_data
270 };
271 #endif /* CONSOLE_ENABLE */
272
273 #ifdef EXTRAKEY_ENABLE
274 /* audio controls & system controls
275  * http://www.microsoft.com/whdc/archive/w2kbd.mspx */
276 static const uint8_t extra_hid_report_desc_data[] = {
277   /* system control */
278   0x05, 0x01,                      // USAGE_PAGE (Generic Desktop)
279   0x09, 0x80,                      // USAGE (System Control)
280   0xa1, 0x01,                      // COLLECTION (Application)
281   0x85, REPORT_ID_SYSTEM,          //   REPORT_ID (2)
282   0x15, 0x01,                      //   LOGICAL_MINIMUM (0x1)
283   0x25, 0xb7,                      //   LOGICAL_MAXIMUM (0xb7)
284   0x19, 0x01,                      //   USAGE_MINIMUM (0x1)
285   0x29, 0xb7,                      //   USAGE_MAXIMUM (0xb7)
286   0x75, 0x10,                      //   REPORT_SIZE (16)
287   0x95, 0x01,                      //   REPORT_COUNT (1)
288   0x81, 0x00,                      //   INPUT (Data,Array,Abs)
289   0xc0,                            // END_COLLECTION
290   /* consumer */
291   0x05, 0x0c,                      // USAGE_PAGE (Consumer Devices)
292   0x09, 0x01,                      // USAGE (Consumer Control)
293   0xa1, 0x01,                      // COLLECTION (Application)
294   0x85, REPORT_ID_CONSUMER,        //   REPORT_ID (3)
295   0x15, 0x01,                      //   LOGICAL_MINIMUM (0x1)
296   0x26, 0x9c, 0x02,                //   LOGICAL_MAXIMUM (0x29c)
297   0x19, 0x01,                      //   USAGE_MINIMUM (0x1)
298   0x2a, 0x9c, 0x02,                //   USAGE_MAXIMUM (0x29c)
299   0x75, 0x10,                      //   REPORT_SIZE (16)
300   0x95, 0x01,                      //   REPORT_COUNT (1)
301   0x81, 0x00,                      //   INPUT (Data,Array,Abs)
302   0xc0,                            // END_COLLECTION
303 };
304 /* wrapper */
305 static const USBDescriptor extra_hid_report_descriptor = {
306   sizeof extra_hid_report_desc_data,
307   extra_hid_report_desc_data
308 };
309 #endif /* EXTRAKEY_ENABLE */
310
311
312 /*
313  * Configuration Descriptor tree for a HID device
314  *
315  * The HID Specifications version 1.11 require the following order:
316  * - Configuration Descriptor
317  * - Interface Descriptor
318  * - HID Descriptor
319  * - Endpoints Descriptors
320  */
321 #define KBD_HID_DESC_NUM                0
322 #define KBD_HID_DESC_OFFSET             (9 + (9 + 9 + 7) * KBD_HID_DESC_NUM + 9)
323
324 #ifdef MOUSE_ENABLE
325 #   define MOUSE_HID_DESC_NUM           (KBD_HID_DESC_NUM + 1)
326 #   define MOUSE_HID_DESC_OFFSET        (9 + (9 + 9 + 7) * MOUSE_HID_DESC_NUM + 9)
327 #else /* MOUSE_ENABLE */
328 #   define MOUSE_HID_DESC_NUM           (KBD_HID_DESC_NUM + 0)
329 #endif /* MOUSE_ENABLE */
330
331 #ifdef CONSOLE_ENABLE
332 #define CONSOLE_HID_DESC_NUM            (MOUSE_HID_DESC_NUM + 1)
333 #define CONSOLE_HID_DESC_OFFSET         (9 + (9 + 9 + 7) * CONSOLE_HID_DESC_NUM + 9)
334 #else /* CONSOLE_ENABLE */
335 #   define CONSOLE_HID_DESC_NUM         (MOUSE_HID_DESC_NUM + 0)
336 #endif /* CONSOLE_ENABLE */
337
338 #ifdef EXTRAKEY_ENABLE
339 #   define EXTRA_HID_DESC_NUM           (CONSOLE_HID_DESC_NUM + 1)
340 #   define EXTRA_HID_DESC_OFFSET        (9 + (9 + 9 + 7) * EXTRA_HID_DESC_NUM + 9)
341 #else /* EXTRAKEY_ENABLE */
342 #   define EXTRA_HID_DESC_NUM           (CONSOLE_HID_DESC_NUM + 0)
343 #endif /* EXTRAKEY_ENABLE */
344
345 #ifdef NKRO_ENABLE
346 #   define NKRO_HID_DESC_NUM            (EXTRA_HID_DESC_NUM + 1)
347 #   define NKRO_HID_DESC_OFFSET         (9 + (9 + 9 + 7) * EXTRA_HID_DESC_NUM + 9)
348 #else /* NKRO_ENABLE */
349 #   define NKRO_HID_DESC_NUM            (EXTRA_HID_DESC_NUM + 0)
350 #endif /* NKRO_ENABLE */
351
352 #define NUM_INTERFACES                  (NKRO_HID_DESC_NUM + 1)
353 #define CONFIG1_DESC_SIZE               (9 + (9 + 9 + 7) * NUM_INTERFACES)
354
355 static const uint8_t hid_configuration_descriptor_data[] = {
356   /* Configuration Descriptor (9 bytes) USB spec 9.6.3, page 264-266, Table 9-10 */
357   USB_DESC_CONFIGURATION(CONFIG1_DESC_SIZE, // wTotalLength
358                          NUM_INTERFACES,    // bNumInterfaces
359                          1,    // bConfigurationValue
360                          0,    // iConfiguration
361                          0xA0, // bmAttributes (RESERVED|REMOTEWAKEUP)
362                          50),  // bMaxPower (50mA)
363
364   /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
365   USB_DESC_INTERFACE(KBD_INTERFACE,        // bInterfaceNumber
366                      0,        // bAlternateSetting
367                      1,        // bNumEndpoints
368                      0x03,     // bInterfaceClass: HID
369                      0x01,     // bInterfaceSubClass: Boot
370                      0x01,     // bInterfaceProtocol: Keyboard
371                      0),       // iInterface
372
373   /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
374   USB_DESC_BYTE(9),            // bLength
375   USB_DESC_BYTE(0x21),         // bDescriptorType (HID class)
376   USB_DESC_BCD(0x0111),        // bcdHID: HID version 1.11
377   USB_DESC_BYTE(0),            // bCountryCode
378   USB_DESC_BYTE(1),            // bNumDescriptors
379   USB_DESC_BYTE(0x22),         // bDescriptorType (report desc)
380   USB_DESC_WORD(sizeof(keyboard_hid_report_desc_data)), // wDescriptorLength
381
382   /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
383   USB_DESC_ENDPOINT(KBD_ENDPOINT | 0x80,  // bEndpointAddress
384                     0x03,      // bmAttributes (Interrupt)
385                     KBD_EPSIZE,// wMaxPacketSize
386                     10),       // bInterval
387
388   #ifdef MOUSE_ENABLE
389   /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
390   USB_DESC_INTERFACE(MOUSE_INTERFACE,   // bInterfaceNumber
391                      0,        // bAlternateSetting
392                      1,        // bNumEndpoints
393                      0x03,     // bInterfaceClass (0x03 = HID)
394                      // ThinkPad T23 BIOS doesn't work with boot mouse.
395                      0x00,     // bInterfaceSubClass (0x01 = Boot)
396                      0x00,     // bInterfaceProtocol (0x02 = Mouse)
397                      /*
398                         0x01,      // bInterfaceSubClass (0x01 = Boot)
399                         0x02,      // bInterfaceProtocol (0x02 = Mouse)
400                       */
401                      0),        // iInterface
402
403   /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
404   USB_DESC_BYTE(9),            // bLength
405   USB_DESC_BYTE(0x21),         // bDescriptorType (HID class)
406   USB_DESC_BCD(0x0111),        // bcdHID: HID version 1.11
407   USB_DESC_BYTE(0),            // bCountryCode
408   USB_DESC_BYTE(1),            // bNumDescriptors
409   USB_DESC_BYTE(0x22),         // bDescriptorType (report desc)
410   USB_DESC_WORD(sizeof(mouse_hid_report_desc_data)), // wDescriptorLength
411
412   /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
413   USB_DESC_ENDPOINT(MOUSE_ENDPOINT | 0x80,  // bEndpointAddress
414                     0x03,      // bmAttributes (Interrupt)
415                     MOUSE_EPSIZE,  // wMaxPacketSize
416                     1),        // bInterval
417   #endif /* MOUSE_ENABLE */
418
419   #ifdef CONSOLE_ENABLE
420   /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
421   USB_DESC_INTERFACE(CONSOLE_INTERFACE, // bInterfaceNumber
422                      0,        // bAlternateSetting
423                      1,        // bNumEndpoints
424                      0x03,     // bInterfaceClass: HID
425                      0x00,     // bInterfaceSubClass: None
426                      0x00,     // bInterfaceProtocol: None
427                      0),       // iInterface
428
429   /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
430   USB_DESC_BYTE(9),            // bLength
431   USB_DESC_BYTE(0x21),         // bDescriptorType (HID class)
432   USB_DESC_BCD(0x0111),        // bcdHID: HID version 1.11
433   USB_DESC_BYTE(0),            // bCountryCode
434   USB_DESC_BYTE(1),            // bNumDescriptors
435   USB_DESC_BYTE(0x22),         // bDescriptorType (report desc)
436   USB_DESC_WORD(sizeof(console_hid_report_desc_data)), // wDescriptorLength
437
438   /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
439   USB_DESC_ENDPOINT(CONSOLE_ENDPOINT | 0x80,  // bEndpointAddress
440                     0x03,      // bmAttributes (Interrupt)
441                     CONSOLE_EPSIZE, // wMaxPacketSize
442                     1),        // bInterval
443   #endif /* CONSOLE_ENABLE */
444
445   #ifdef EXTRAKEY_ENABLE
446   /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
447   USB_DESC_INTERFACE(EXTRA_INTERFACE, // bInterfaceNumber
448                      0,        // bAlternateSetting
449                      1,        // bNumEndpoints
450                      0x03,     // bInterfaceClass: HID
451                      0x00,     // bInterfaceSubClass: None
452                      0x00,     // bInterfaceProtocol: None
453                      0),       // iInterface
454
455   /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
456   USB_DESC_BYTE(9),            // bLength
457   USB_DESC_BYTE(0x21),         // bDescriptorType (HID class)
458   USB_DESC_BCD(0x0111),        // bcdHID: HID version 1.11
459   USB_DESC_BYTE(0),            // bCountryCode
460   USB_DESC_BYTE(1),            // bNumDescriptors
461   USB_DESC_BYTE(0x22),         // bDescriptorType (report desc)
462   USB_DESC_WORD(sizeof(extra_hid_report_desc_data)), // wDescriptorLength
463
464   /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
465   USB_DESC_ENDPOINT(EXTRA_ENDPOINT | 0x80,  // bEndpointAddress
466                     0x03,      // bmAttributes (Interrupt)
467                     EXTRA_EPSIZE, // wMaxPacketSize
468                     10),       // bInterval
469   #endif /* EXTRAKEY_ENABLE */
470
471   #ifdef NKRO_ENABLE
472   /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
473   USB_DESC_INTERFACE(NKRO_INTERFACE, // bInterfaceNumber
474                      0,        // bAlternateSetting
475                      1,        // bNumEndpoints
476                      0x03,     // bInterfaceClass: HID
477                      0x00,     // bInterfaceSubClass: None
478                      0x00,     // bInterfaceProtocol: None
479                      0),       // iInterface
480
481   /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
482   USB_DESC_BYTE(9),            // bLength
483   USB_DESC_BYTE(0x21),         // bDescriptorType (HID class)
484   USB_DESC_BCD(0x0111),        // bcdHID: HID version 1.11
485   USB_DESC_BYTE(0),            // bCountryCode
486   USB_DESC_BYTE(1),            // bNumDescriptors
487   USB_DESC_BYTE(0x22),         // bDescriptorType (report desc)
488   USB_DESC_WORD(sizeof(nkro_hid_report_desc_data)), // wDescriptorLength
489
490   /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
491   USB_DESC_ENDPOINT(NKRO_ENDPOINT | 0x80,  // bEndpointAddress
492                     0x03,      // bmAttributes (Interrupt)
493                     NKRO_EPSIZE, // wMaxPacketSize
494                     1),       // bInterval
495   #endif /* NKRO_ENABLE */
496 };
497
498 /* Configuration Descriptor wrapper */
499 static const USBDescriptor hid_configuration_descriptor = {
500   sizeof hid_configuration_descriptor_data,
501   hid_configuration_descriptor_data
502 };
503
504 /* wrappers */
505 #define HID_DESCRIPTOR_SIZE 9
506 static const USBDescriptor keyboard_hid_descriptor = {
507   HID_DESCRIPTOR_SIZE,
508   &hid_configuration_descriptor_data[KBD_HID_DESC_OFFSET]
509 };
510 #ifdef MOUSE_ENABLE
511 static const USBDescriptor mouse_hid_descriptor = {
512   HID_DESCRIPTOR_SIZE,
513   &hid_configuration_descriptor_data[MOUSE_HID_DESC_OFFSET]
514 };
515 #endif /* MOUSE_ENABLE */
516 #ifdef CONSOLE_ENABLE
517 static const USBDescriptor console_hid_descriptor = {
518   HID_DESCRIPTOR_SIZE,
519   &hid_configuration_descriptor_data[CONSOLE_HID_DESC_OFFSET]
520 };
521 #endif /* CONSOLE_ENABLE */
522 #ifdef EXTRAKEY_ENABLE
523 static const USBDescriptor extra_hid_descriptor = {
524   HID_DESCRIPTOR_SIZE,
525   &hid_configuration_descriptor_data[EXTRA_HID_DESC_OFFSET]
526 };
527 #endif /* EXTRAKEY_ENABLE */
528 #ifdef NKRO_ENABLE
529 static const USBDescriptor nkro_hid_descriptor = {
530   HID_DESCRIPTOR_SIZE,
531   &hid_configuration_descriptor_data[NKRO_HID_DESC_OFFSET]
532 };
533 #endif /* NKRO_ENABLE */
534
535
536 /* U.S. English language identifier */
537 static const uint8_t usb_string_langid[] = {
538   USB_DESC_BYTE(4),                        // bLength
539   USB_DESC_BYTE(USB_DESCRIPTOR_STRING),    // bDescriptorType
540   USB_DESC_WORD(0x0409)                    // wLANGID (U.S. English)
541 };
542
543 /* ugly ugly hack */
544 #define PP_NARG(...) \
545          PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
546 #define PP_NARG_(...) \
547          PP_ARG_N(__VA_ARGS__)
548 #define PP_ARG_N( \
549           _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
550          _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
551          _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
552          _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
553          _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
554          _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
555          _61,_62,_63,N,...) N
556 #define PP_RSEQ_N() \
557          63,62,61,60,                   \
558          59,58,57,56,55,54,53,52,51,50, \
559          49,48,47,46,45,44,43,42,41,40, \
560          39,38,37,36,35,34,33,32,31,30, \
561          29,28,27,26,25,24,23,22,21,20, \
562          19,18,17,16,15,14,13,12,11,10, \
563          9,8,7,6,5,4,3,2,1,0
564
565 /* Vendor string = manufacturer */
566 static const uint8_t usb_string_vendor[] = {
567   USB_DESC_BYTE(PP_NARG(USBSTR_MANUFACTURER)+2),                       // bLength
568   USB_DESC_BYTE(USB_DESCRIPTOR_STRING),    // bDescriptorType
569   USBSTR_MANUFACTURER
570 };
571
572 /* Device Description string = product */
573 static const uint8_t usb_string_description[] = {
574   USB_DESC_BYTE(PP_NARG(USBSTR_PRODUCT)+2),           // bLength
575   USB_DESC_BYTE(USB_DESCRIPTOR_STRING),    // bDescriptorType
576   USBSTR_PRODUCT
577 };
578
579 /* Serial Number string (will be filled by the function init_usb_serial_string) */
580 static uint8_t usb_string_serial[] = {
581   USB_DESC_BYTE(22),                       // bLength
582   USB_DESC_BYTE(USB_DESCRIPTOR_STRING),    // bDescriptorType
583   '0', 0, 'x', 0, 'D', 0, 'E', 0, 'A', 0, 'D', 0, 'B', 0, 'E', 0, 'E', 0, 'F', 0
584 };
585
586 /* Strings wrappers array */
587 static const USBDescriptor usb_strings[] = {
588   { sizeof usb_string_langid, usb_string_langid }
589   ,
590   { sizeof usb_string_vendor, usb_string_vendor }
591   ,
592   { sizeof usb_string_description, usb_string_description }
593   ,
594   { sizeof usb_string_serial, usb_string_serial }
595 };
596
597 /*
598  * Handles the GET_DESCRIPTOR callback
599  *
600  * Returns the proper descriptor
601  */
602 static const USBDescriptor *usb_get_descriptor_cb(USBDriver *usbp, uint8_t dtype, uint8_t dindex, uint16_t lang) {
603   (void)usbp;
604   (void)lang;
605   switch(dtype) {
606   /* Generic descriptors */
607   case USB_DESCRIPTOR_DEVICE:   /* Device Descriptor */
608     return &usb_device_descriptor;
609
610   case USB_DESCRIPTOR_CONFIGURATION:    /* Configuration Descriptor */
611     return &hid_configuration_descriptor;
612
613   case USB_DESCRIPTOR_STRING:   /* Strings */
614     if(dindex < 4)
615       return &usb_strings[dindex];
616     break;
617
618   /* HID specific descriptors */
619   case USB_DESCRIPTOR_HID:      /* HID Descriptors */
620     switch(lang) {    /* yea, poor label, it's actually wIndex from the setup packet */
621     case KBD_INTERFACE:
622       return &keyboard_hid_descriptor;
623
624 #ifdef MOUSE_ENABLE
625     case MOUSE_INTERFACE:
626       return &mouse_hid_descriptor;
627 #endif /* MOUSE_ENABLE */
628 #ifdef CONSOLE_ENABLE
629     case CONSOLE_INTERFACE:
630       return &console_hid_descriptor;
631 #endif /* CONSOLE_ENABLE */
632 #ifdef EXTRAKEY_ENABLE
633     case EXTRA_INTERFACE:
634       return &extra_hid_descriptor;
635 #endif /* EXTRAKEY_ENABLE */
636 #ifdef NKRO_ENABLE
637     case NKRO_INTERFACE:
638       return &nkro_hid_descriptor;
639 #endif /* NKRO_ENABLE */
640     }
641
642   case USB_DESCRIPTOR_HID_REPORT:       /* HID Report Descriptor */
643     switch(lang) {
644     case KBD_INTERFACE:
645       return &keyboard_hid_report_descriptor;
646
647 #ifdef MOUSE_ENABLE
648     case MOUSE_INTERFACE:
649       return &mouse_hid_report_descriptor;
650 #endif /* MOUSE_ENABLE */
651 #ifdef CONSOLE_ENABLE
652     case CONSOLE_INTERFACE:
653       return &console_hid_report_descriptor;
654 #endif /* CONSOLE_ENABLE */
655 #ifdef EXTRAKEY_ENABLE
656     case EXTRA_INTERFACE:
657       return &extra_hid_report_descriptor;
658 #endif /* EXTRAKEY_ENABLE */
659 #ifdef NKRO_ENABLE
660     case NKRO_INTERFACE:
661       return &nkro_hid_report_descriptor;
662 #endif /* NKRO_ENABLE */
663     }
664   }
665   return NULL;
666 }
667
668 /* keyboard endpoint state structure */
669 static USBInEndpointState kbd_ep_state;
670 /* keyboard endpoint initialization structure (IN) */
671 static const USBEndpointConfig kbd_ep_config = {
672   USB_EP_MODE_TYPE_INTR,        /* Interrupt EP */
673   NULL,                         /* SETUP packet notification callback */
674   kbd_in_cb,                    /* IN notification callback */
675   NULL,                         /* OUT notification callback */
676   KBD_EPSIZE,                   /* IN maximum packet size */
677   0,                            /* OUT maximum packet size */
678   &kbd_ep_state,                /* IN Endpoint state */
679   NULL,                         /* OUT endpoint state */
680   2,                            /* IN multiplier */
681   NULL                          /* SETUP buffer (not a SETUP endpoint) */
682 };
683
684 #ifdef MOUSE_ENABLE
685 /* mouse endpoint state structure */
686 static USBInEndpointState mouse_ep_state;
687
688 /* mouse endpoint initialization structure (IN) */
689 static const USBEndpointConfig mouse_ep_config = {
690   USB_EP_MODE_TYPE_INTR,        /* Interrupt EP */
691   NULL,                         /* SETUP packet notification callback */
692   mouse_in_cb,                  /* IN notification callback */
693   NULL,                         /* OUT notification callback */
694   MOUSE_EPSIZE,                 /* IN maximum packet size */
695   0,                            /* OUT maximum packet size */
696   &mouse_ep_state,              /* IN Endpoint state */
697   NULL,                         /* OUT endpoint state */
698   2,                            /* IN multiplier */
699   NULL                          /* SETUP buffer (not a SETUP endpoint) */
700 };
701 #endif /* MOUSE_ENABLE */
702
703 #ifdef CONSOLE_ENABLE
704 /* console endpoint state structure */
705 static USBInEndpointState console_ep_state;
706
707 /* console endpoint initialization structure (IN) */
708 static const USBEndpointConfig console_ep_config = {
709   USB_EP_MODE_TYPE_INTR,        /* Interrupt EP */
710   NULL,                         /* SETUP packet notification callback */
711   console_in_cb,                /* IN notification callback */
712   NULL,                         /* OUT notification callback */
713   CONSOLE_EPSIZE,               /* IN maximum packet size */
714   0,                            /* OUT maximum packet size */
715   &console_ep_state,            /* IN Endpoint state */
716   NULL,                         /* OUT endpoint state */
717   2,                            /* IN multiplier */
718   NULL                          /* SETUP buffer (not a SETUP endpoint) */
719 };
720 #endif /* CONSOLE_ENABLE */
721
722 #ifdef EXTRAKEY_ENABLE
723 /* extrakey endpoint state structure */
724 static USBInEndpointState extra_ep_state;
725
726 /* extrakey endpoint initialization structure (IN) */
727 static const USBEndpointConfig extra_ep_config = {
728   USB_EP_MODE_TYPE_INTR,        /* Interrupt EP */
729   NULL,                         /* SETUP packet notification callback */
730   extra_in_cb,                  /* IN notification callback */
731   NULL,                         /* OUT notification callback */
732   EXTRA_EPSIZE,                 /* IN maximum packet size */
733   0,                            /* OUT maximum packet size */
734   &extra_ep_state,              /* IN Endpoint state */
735   NULL,                         /* OUT endpoint state */
736   2,                            /* IN multiplier */
737   NULL                          /* SETUP buffer (not a SETUP endpoint) */
738 };
739 #endif /* EXTRAKEY_ENABLE */
740
741 #ifdef NKRO_ENABLE
742 /* nkro endpoint state structure */
743 static USBInEndpointState nkro_ep_state;
744
745 /* nkro endpoint initialization structure (IN) */
746 static const USBEndpointConfig nkro_ep_config = {
747   USB_EP_MODE_TYPE_INTR,        /* Interrupt EP */
748   NULL,                         /* SETUP packet notification callback */
749   nkro_in_cb,                   /* IN notification callback */
750   NULL,                         /* OUT notification callback */
751   NKRO_EPSIZE,                  /* IN maximum packet size */
752   0,                            /* OUT maximum packet size */
753   &nkro_ep_state,               /* IN Endpoint state */
754   NULL,                         /* OUT endpoint state */
755   2,                            /* IN multiplier */
756   NULL                          /* SETUP buffer (not a SETUP endpoint) */
757 };
758 #endif /* NKRO_ENABLE */
759
760 /* ---------------------------------------------------------
761  *                  USB driver functions
762  * ---------------------------------------------------------
763  */
764
765 /* Handles the USB driver global events
766  * TODO: maybe disable some things when connection is lost? */
767 static void usb_event_cb(USBDriver *usbp, usbevent_t event) {
768   switch(event) {
769   case USB_EVENT_RESET:
770     //TODO: from ISR! print("[R]");
771     return;
772
773   case USB_EVENT_ADDRESS:
774     return;
775
776   case USB_EVENT_CONFIGURED:
777     osalSysLockFromISR();
778     /* Enable the endpoints specified into the configuration. */
779     usbInitEndpointI(usbp, KBD_ENDPOINT, &kbd_ep_config);
780 #ifdef MOUSE_ENABLE
781     usbInitEndpointI(usbp, MOUSE_ENDPOINT, &mouse_ep_config);
782 #endif /* MOUSE_ENABLE */
783 #ifdef CONSOLE_ENABLE
784     usbInitEndpointI(usbp, CONSOLE_ENDPOINT, &console_ep_config);
785     /* don't need to start the flush timer, it starts from console_in_cb automatically */
786 #endif /* CONSOLE_ENABLE */
787 #ifdef EXTRAKEY_ENABLE
788     usbInitEndpointI(usbp, EXTRA_ENDPOINT, &extra_ep_config);
789 #endif /* EXTRAKEY_ENABLE */
790 #ifdef NKRO_ENABLE
791     usbInitEndpointI(usbp, NKRO_ENDPOINT, &nkro_ep_config);
792 #endif /* NKRO_ENABLE */
793     osalSysUnlockFromISR();
794     return;
795
796   case USB_EVENT_SUSPEND:
797     //TODO: from ISR! print("[S]");
798 #ifdef SLEEP_LED_ENABLE
799     sleep_led_enable();
800 #endif /* SLEEP_LED_ENABLE */
801     return;
802
803   case USB_EVENT_WAKEUP:
804     //TODO: from ISR! print("[W]");
805     suspend_wakeup_init();
806 #ifdef SLEEP_LED_ENABLE
807     sleep_led_disable();
808     // NOTE: converters may not accept this
809     led_set(host_keyboard_leds());
810 #endif /* SLEEP_LED_ENABLE */
811     return;
812
813   case USB_EVENT_STALLED:
814     return;
815   }
816 }
817
818 /* Function used locally in os/hal/src/usb.c for getting descriptors
819  * need it here for HID descriptor */
820 static uint16_t get_hword(uint8_t *p) {
821   uint16_t hw;
822
823   hw = (uint16_t)*p++;
824   hw |= (uint16_t)*p << 8U;
825   return hw;
826 }
827
828 /*
829  * Appendix G: HID Request Support Requirements
830  *
831  * The following table enumerates the requests that need to be supported by various types of HID class devices.
832  * Device type     GetReport   SetReport   GetIdle     SetIdle     GetProtocol SetProtocol
833  * ------------------------------------------------------------------------------------------
834  * Boot Mouse      Required    Optional    Optional    Optional    Required    Required
835  * Non-Boot Mouse  Required    Optional    Optional    Optional    Optional    Optional
836  * Boot Keyboard   Required    Optional    Required    Required    Required    Required
837  * Non-Boot Keybrd Required    Optional    Required    Required    Optional    Optional
838  * Other Device    Required    Optional    Optional    Optional    Optional    Optional
839  */
840
841 /* Callback for SETUP request on the endpoint 0 (control) */
842 static bool usb_request_hook_cb(USBDriver *usbp) {
843   const USBDescriptor *dp;
844
845   /* usbp->setup fields:
846    *  0:   bmRequestType (bitmask)
847    *  1:   bRequest
848    *  2,3: (LSB,MSB) wValue
849    *  4,5: (LSB,MSB) wIndex
850    *  6,7: (LSB,MSB) wLength (number of bytes to transfer if there is a data phase) */
851
852   /* Handle HID class specific requests */
853   if(((usbp->setup[0] & USB_RTYPE_TYPE_MASK) == USB_RTYPE_TYPE_CLASS) &&
854      ((usbp->setup[0] & USB_RTYPE_RECIPIENT_MASK) == USB_RTYPE_RECIPIENT_INTERFACE)) {
855     switch(usbp->setup[0] & USB_RTYPE_DIR_MASK) {
856     case USB_RTYPE_DIR_DEV2HOST:
857       switch(usbp->setup[1]) {   /* bRequest */
858       case HID_GET_REPORT:
859         switch(usbp->setup[4]) {     /* LSB(wIndex) (check MSB==0?) */
860         case KBD_INTERFACE:
861 #ifdef NKRO_ENABLE
862         case NKRO_INTERFACE:
863 #endif /* NKRO_ENABLE */
864           usbSetupTransfer(usbp, (uint8_t *)&keyboard_report_sent, sizeof(keyboard_report_sent), NULL);
865           return TRUE;
866           break;
867
868 #ifdef MOUSE_ENABLE
869         case MOUSE_INTERFACE:
870           usbSetupTransfer(usbp, (uint8_t *)&mouse_report_blank, sizeof(mouse_report_blank), NULL);
871           return TRUE;
872           break;
873 #endif /* MOUSE_ENABLE */
874
875 #ifdef CONSOLE_ENABLE
876         case CONSOLE_INTERFACE:
877           usbSetupTransfer(usbp, console_queue_buffer, CONSOLE_EPSIZE, NULL);
878           return TRUE;
879           break;
880 #endif /* CONSOLE_ENABLE */
881
882 #ifdef EXTRAKEY_ENABLE
883         case EXTRA_INTERFACE:
884           if(usbp->setup[3] == 1) { /* MSB(wValue) [Report Type] == 1 [Input Report] */
885             switch(usbp->setup[2]) { /* LSB(wValue) [Report ID] */
886               case REPORT_ID_SYSTEM:
887                 extra_report_blank[0] = REPORT_ID_SYSTEM;
888                 usbSetupTransfer(usbp, (uint8_t *)extra_report_blank, sizeof(extra_report_blank), NULL);
889                 return TRUE;
890                 break;
891               case REPORT_ID_CONSUMER:
892                 extra_report_blank[0] = REPORT_ID_CONSUMER;
893                 usbSetupTransfer(usbp, (uint8_t *)extra_report_blank, sizeof(extra_report_blank), NULL);
894                 return TRUE;
895                 break;
896               default:
897                 return FALSE;
898             }
899           } else {
900             return FALSE;
901           }
902           break;
903 #endif /* EXTRAKEY_ENABLE */
904
905         default:
906           usbSetupTransfer(usbp, NULL, 0, NULL);
907           return TRUE;
908           break;
909         }
910         break;
911
912       case HID_GET_PROTOCOL:
913         if((usbp->setup[4] == KBD_INTERFACE) && (usbp->setup[5] == 0)) {   /* wIndex */
914           usbSetupTransfer(usbp, &keyboard_protocol, 1, NULL);
915           return TRUE;
916         }
917         break;
918
919       case HID_GET_IDLE:
920         usbSetupTransfer(usbp, &keyboard_idle, 1, NULL);
921         return TRUE;
922         break;
923       }
924       break;
925
926     case USB_RTYPE_DIR_HOST2DEV:
927       switch(usbp->setup[1]) {   /* bRequest */
928       case HID_SET_REPORT:
929         switch(usbp->setup[4]) {       /* LSB(wIndex) (check MSB==0 and wLength==1?) */
930         case KBD_INTERFACE:
931 #ifdef NKRO_ENABLE
932         case NKRO_INTERFACE:
933 #endif  /* NKRO_ENABLE */
934         /* keyboard_led_stats = <read byte from next OUT report>
935          * keyboard_led_stats needs be word (or dword), otherwise we get an exception on F0 */
936           usbSetupTransfer(usbp, (uint8_t *)&keyboard_led_stats, 1, NULL);
937           return TRUE;
938           break;
939         }
940         break;
941
942       case HID_SET_PROTOCOL:
943         if((usbp->setup[4] == KBD_INTERFACE) && (usbp->setup[5] == 0)) {   /* wIndex */
944           keyboard_protocol = ((usbp->setup[2]) != 0x00);   /* LSB(wValue) */
945 #ifdef NKRO_ENABLE
946           keyboard_nkro = !!keyboard_protocol;
947           if(!keyboard_nkro && keyboard_idle) {
948 #else /* NKRO_ENABLE */
949           if(keyboard_idle) {
950 #endif /* NKRO_ENABLE */
951           /* arm the idle timer if boot protocol & idle */
952             osalSysLockFromISR();
953             chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
954             osalSysUnlockFromISR();
955           }
956         }
957         usbSetupTransfer(usbp, NULL, 0, NULL);
958         return TRUE;
959         break;
960
961       case HID_SET_IDLE:
962         keyboard_idle = usbp->setup[3];     /* MSB(wValue) */
963         /* arm the timer */
964 #ifdef NKRO_ENABLE
965         if(!keyboard_nkro && keyboard_idle) {
966 #else /* NKRO_ENABLE */
967         if(keyboard_idle) {
968 #endif /* NKRO_ENABLE */
969           osalSysLockFromISR();
970           chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
971           osalSysUnlockFromISR();
972         }
973         usbSetupTransfer(usbp, NULL, 0, NULL);
974         return TRUE;
975         break;
976       }
977       break;
978     }
979   }
980
981   /* Handle the Get_Descriptor Request for HID class (not handled by the default hook) */
982   if((usbp->setup[0] == 0x81) && (usbp->setup[1] == USB_REQ_GET_DESCRIPTOR)) {
983     dp = usbp->config->get_descriptor_cb(usbp, usbp->setup[3], usbp->setup[2], get_hword(&usbp->setup[4]));
984     if(dp == NULL)
985       return FALSE;
986     usbSetupTransfer(usbp, (uint8_t *)dp->ud_string, dp->ud_size, NULL);
987     return TRUE;
988   }
989
990   return FALSE;
991 }
992
993 /* Start-of-frame callback */
994 static void usb_sof_cb(USBDriver *usbp) {
995   kbd_sof_cb(usbp);
996 }
997
998
999 /* USB driver configuration */
1000 static const USBConfig usbcfg = {
1001   usb_event_cb,                 /* USB events callback */
1002   usb_get_descriptor_cb,        /* Device GET_DESCRIPTOR request callback */
1003   usb_request_hook_cb,          /* Requests hook callback */
1004   usb_sof_cb                    /* Start Of Frame callback */
1005 };
1006
1007 /*
1008  * Initialize the USB driver
1009  */
1010 void init_usb_driver(USBDriver *usbp) {
1011   /*
1012    * Activates the USB driver and then the USB bus pull-up on D+.
1013    * Note, a delay is inserted in order to not have to disconnect the cable
1014    * after a reset.
1015    */
1016   usbDisconnectBus(usbp);
1017   chThdSleepMilliseconds(1500);
1018   usbStart(usbp, &usbcfg);
1019   usbConnectBus(usbp);
1020
1021   chVTObjectInit(&keyboard_idle_timer);
1022 #ifdef CONSOLE_ENABLE
1023   obqObjectInit(&console_buf_queue, console_queue_buffer, CONSOLE_EPSIZE, CONSOLE_QUEUE_CAPACITY, console_queue_onotify, (void*)usbp);
1024   chVTObjectInit(&console_flush_timer);
1025 #endif
1026 }
1027
1028 /*
1029  * Send remote wakeup packet
1030  * Note: should not be called from ISR
1031  */
1032 void send_remote_wakeup(USBDriver *usbp) {
1033   (void)usbp;
1034 #if defined(K20x) || defined(KL2x)
1035 #if KINETIS_USB_USE_USB0
1036   USB0->CTL |= USBx_CTL_RESUME;
1037   chThdSleepMilliseconds(15);
1038   USB0->CTL &= ~USBx_CTL_RESUME;
1039 #endif /* KINETIS_USB_USE_USB0 */
1040 #elif defined(STM32F0XX) || defined(STM32F1XX) /* K20x || KL2x */
1041   STM32_USB->CNTR |= CNTR_RESUME;
1042   chThdSleepMilliseconds(15);
1043   STM32_USB->CNTR &= ~CNTR_RESUME;
1044 #else /* STM32F0XX || STM32F1XX */
1045 #warning Sending remote wakeup packet not implemented for your platform.
1046 #endif /* K20x || KL2x */
1047 }
1048
1049 /* ---------------------------------------------------------
1050  *                  Keyboard functions
1051  * ---------------------------------------------------------
1052  */
1053
1054 /* keyboard IN callback hander (a kbd report has made it IN) */
1055 void kbd_in_cb(USBDriver *usbp, usbep_t ep) {
1056   /* STUB */
1057   (void)usbp;
1058   (void)ep;
1059 }
1060
1061 #ifdef NKRO_ENABLE
1062 /* nkro IN callback hander (a nkro report has made it IN) */
1063 void nkro_in_cb(USBDriver *usbp, usbep_t ep) {
1064   /* STUB */
1065   (void)usbp;
1066   (void)ep;
1067 }
1068 #endif /* NKRO_ENABLE */
1069
1070 /* start-of-frame handler
1071  * TODO: i guess it would be better to re-implement using timers,
1072  *  so that this is not going to have to be checked every 1ms */
1073 void kbd_sof_cb(USBDriver *usbp) {
1074   (void)usbp;
1075 }
1076
1077 /* Idle requests timer code
1078  * callback (called from ISR, unlocked state) */
1079 static void keyboard_idle_timer_cb(void *arg) {
1080   USBDriver *usbp = (USBDriver *)arg;
1081
1082   osalSysLockFromISR();
1083
1084   /* check that the states of things are as they're supposed to */
1085   if(usbGetDriverStateI(usbp) != USB_ACTIVE) {
1086     /* do not rearm the timer, should be enabled on IDLE request */
1087     osalSysUnlockFromISR();
1088     return;
1089   }
1090
1091 #ifdef NKRO_ENABLE
1092   if(!keyboard_nkro && keyboard_idle) {
1093 #else /* NKRO_ENABLE */
1094   if(keyboard_idle) {
1095 #endif /* NKRO_ENABLE */
1096     /* TODO: are we sure we want the KBD_ENDPOINT? */
1097     if(!usbGetTransmitStatusI(usbp, KBD_ENDPOINT)) {
1098       usbStartTransmitI(usbp, KBD_ENDPOINT, (uint8_t *)&keyboard_report_sent, KBD_EPSIZE);
1099     }
1100     /* rearm the timer */
1101     chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
1102   }
1103
1104   /* do not rearm the timer if the condition above fails
1105    * it should be enabled again on either IDLE or SET_PROTOCOL requests */
1106   osalSysUnlockFromISR();
1107 }
1108
1109 /* LED status */
1110 uint8_t keyboard_leds(void) {
1111   return (uint8_t)(keyboard_led_stats & 0xFF);
1112 }
1113
1114 /* prepare and start sending a report IN
1115  * not callable from ISR or locked state */
1116 void send_keyboard(report_keyboard_t *report) {
1117   osalSysLock();
1118   if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
1119     osalSysUnlock();
1120     return;
1121   }
1122   osalSysUnlock();
1123
1124 #ifdef NKRO_ENABLE
1125   if(keyboard_nkro) {  /* NKRO protocol */
1126     /* need to wait until the previous packet has made it through */
1127     /* can rewrite this using the synchronous API, then would wait
1128      * until *after* the packet has been transmitted. I think
1129      * this is more efficient */
1130     /* busy wait, should be short and not very common */
1131     osalSysLock();
1132     if(usbGetTransmitStatusI(&USB_DRIVER, NKRO_ENDPOINT)) {
1133       /* Need to either suspend, or loop and call unlock/lock during
1134        * every iteration - otherwise the system will remain locked,
1135        * no interrupts served, so USB not going through as well.
1136        * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
1137       osalThreadSuspendS(&(&USB_DRIVER)->epc[NKRO_ENDPOINT]->in_state->thread);
1138     }
1139     usbStartTransmitI(&USB_DRIVER, NKRO_ENDPOINT, (uint8_t *)report, sizeof(report_keyboard_t));
1140     osalSysUnlock();
1141   } else
1142 #endif /* NKRO_ENABLE */
1143   { /* boot protocol */
1144     /* need to wait until the previous packet has made it through */
1145     /* busy wait, should be short and not very common */
1146     osalSysLock();
1147     if(usbGetTransmitStatusI(&USB_DRIVER, KBD_ENDPOINT)) {
1148       /* Need to either suspend, or loop and call unlock/lock during
1149        * every iteration - otherwise the system will remain locked,
1150        * no interrupts served, so USB not going through as well.
1151        * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
1152       osalThreadSuspendS(&(&USB_DRIVER)->epc[KBD_ENDPOINT]->in_state->thread);
1153     }
1154     usbStartTransmitI(&USB_DRIVER, KBD_ENDPOINT, (uint8_t *)report, KBD_EPSIZE);
1155     osalSysUnlock();
1156   }
1157   keyboard_report_sent = *report;
1158 }
1159
1160 /* ---------------------------------------------------------
1161  *                     Mouse functions
1162  * ---------------------------------------------------------
1163  */
1164
1165 #ifdef MOUSE_ENABLE
1166
1167 /* mouse IN callback hander (a mouse report has made it IN) */
1168 void mouse_in_cb(USBDriver *usbp, usbep_t ep) {
1169   (void)usbp;
1170   (void)ep;
1171 }
1172
1173 void send_mouse(report_mouse_t *report) {
1174   osalSysLock();
1175   if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
1176     osalSysUnlock();
1177     return;
1178   }
1179   osalSysUnlock();
1180
1181   /* TODO: LUFA manually waits for the endpoint to become ready
1182    * for about 10ms for mouse, kbd, system; 1ms for nkro
1183    * is this really needed?
1184    */
1185
1186   osalSysLock();
1187   usbStartTransmitI(&USB_DRIVER, MOUSE_ENDPOINT, (uint8_t *)report, sizeof(report_mouse_t));
1188   osalSysUnlock();
1189 }
1190
1191 #else /* MOUSE_ENABLE */
1192 void send_mouse(report_mouse_t *report) {
1193   (void)report;
1194 }
1195 #endif /* MOUSE_ENABLE */
1196
1197 /* ---------------------------------------------------------
1198  *                   Extrakey functions
1199  * ---------------------------------------------------------
1200  */
1201
1202 #ifdef EXTRAKEY_ENABLE
1203
1204 /* extrakey IN callback hander */
1205 void extra_in_cb(USBDriver *usbp, usbep_t ep) {
1206   /* STUB */
1207   (void)usbp;
1208   (void)ep;
1209 }
1210
1211 static void send_extra_report(uint8_t report_id, uint16_t data) {
1212   osalSysLock();
1213   if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
1214     osalSysUnlock();
1215     return;
1216   }
1217
1218   report_extra_t report = {
1219     .report_id = report_id,
1220     .usage = data
1221   };
1222
1223   usbStartTransmitI(&USB_DRIVER, EXTRA_ENDPOINT, (uint8_t *)&report, sizeof(report_extra_t));
1224   osalSysUnlock();
1225 }
1226
1227 void send_system(uint16_t data) {
1228   send_extra_report(REPORT_ID_SYSTEM, data);
1229 }
1230
1231 void send_consumer(uint16_t data) {
1232   send_extra_report(REPORT_ID_CONSUMER, data);
1233 }
1234
1235 #else /* EXTRAKEY_ENABLE */
1236 void send_system(uint16_t data) {
1237   (void)data;
1238 }
1239 void send_consumer(uint16_t data) {
1240   (void)data;
1241 }
1242 #endif /* EXTRAKEY_ENABLE */
1243
1244 /* ---------------------------------------------------------
1245  *                   Console functions
1246  * ---------------------------------------------------------
1247  */
1248
1249 #ifdef CONSOLE_ENABLE
1250
1251 /* console IN callback hander */
1252 void console_in_cb(USBDriver *usbp, usbep_t ep) {
1253   (void)ep; /* should have ep == CONSOLE_ENDPOINT, so use that to save time/space */
1254   uint8_t *buf;
1255   size_t n;
1256
1257   osalSysLockFromISR();
1258
1259   /* rearm the timer */
1260   chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
1261
1262   /* Freeing the buffer just transmitted, if it was not a zero size packet.*/
1263   if (usbp->epc[CONSOLE_ENDPOINT]->in_state->txsize > 0U) {
1264     obqReleaseEmptyBufferI(&console_buf_queue);
1265   }
1266
1267   /* Checking if there is a buffer ready for transmission.*/
1268   buf = obqGetFullBufferI(&console_buf_queue, &n);
1269
1270   if (buf != NULL) {
1271     /* The endpoint cannot be busy, we are in the context of the callback,
1272        so it is safe to transmit without a check.*/
1273     /* Should have n == CONSOLE_EPSIZE; check it? */
1274     usbStartTransmitI(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_EPSIZE);
1275   } else {
1276     /* Nothing to transmit.*/
1277   }
1278
1279   osalSysUnlockFromISR();
1280 }
1281
1282 /* Callback when data is inserted into the output queue
1283  * Called from a locked state */
1284 void console_queue_onotify(io_buffers_queue_t *bqp) {
1285   size_t n;
1286   USBDriver *usbp = bqGetLinkX(bqp);
1287
1288   if(usbGetDriverStateI(usbp) != USB_ACTIVE)
1289     return;
1290
1291   /* Checking if there is already a transaction ongoing on the endpoint.*/
1292   if (!usbGetTransmitStatusI(usbp, CONSOLE_ENDPOINT)) {
1293     /* Trying to get a full buffer.*/
1294     uint8_t *buf = obqGetFullBufferI(&console_buf_queue, &n);
1295     if (buf != NULL) {
1296       /* Buffer found, starting a new transaction.*/
1297       /* Should have n == CONSOLE_EPSIZE; check this? */
1298       usbStartTransmitI(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_EPSIZE);
1299     }
1300   }
1301 }
1302
1303 /* Flush timer code
1304  * callback (called from ISR, unlocked state) */
1305 static void console_flush_cb(void *arg) {
1306   USBDriver *usbp = (USBDriver *)arg;
1307   osalSysLockFromISR();
1308
1309   /* check that the states of things are as they're supposed to */
1310   if(usbGetDriverStateI(usbp) != USB_ACTIVE) {
1311     /* rearm the timer */
1312     chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
1313     osalSysUnlockFromISR();
1314     return;
1315   }
1316
1317   /* If there is already a transaction ongoing then another one cannot be
1318      started.*/
1319   if (usbGetTransmitStatusI(usbp, CONSOLE_ENDPOINT)) {
1320     /* rearm the timer */
1321     chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
1322     osalSysUnlockFromISR();
1323     return;
1324   }
1325
1326   /* Checking if there only a buffer partially filled, if so then it is
1327      enforced in the queue and transmitted.*/
1328   if(obqTryFlushI(&console_buf_queue)) {
1329     size_t n,i;
1330     uint8_t *buf = obqGetFullBufferI(&console_buf_queue, &n);
1331
1332     osalDbgAssert(buf != NULL, "queue is empty");
1333
1334     /* zero the rest of the buffer (buf should point to allocated space) */
1335     for(i=n; i<CONSOLE_EPSIZE; i++)
1336       buf[i]=0;
1337     usbStartTransmitI(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_EPSIZE);
1338   }
1339
1340   /* rearm the timer */
1341   chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
1342   osalSysUnlockFromISR();
1343 }
1344
1345
1346 int8_t sendchar(uint8_t c) {
1347   osalSysLock();
1348   if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
1349     osalSysUnlock();
1350     return 0;
1351   }
1352   osalSysUnlock();
1353   /* Timeout after 100us if the queue is full.
1354    * Increase this timeout if too much stuff is getting
1355    * dropped (i.e. the buffer is getting full too fast
1356    * for USB/HIDRAW to dequeue). Another possibility
1357    * for fixing this kind of thing is to increase
1358    * CONSOLE_QUEUE_CAPACITY. */
1359   return(obqPutTimeout(&console_buf_queue, c, US2ST(100)));
1360 }
1361
1362 #else /* CONSOLE_ENABLE */
1363 int8_t sendchar(uint8_t c) {
1364   (void)c;
1365   return 0;
1366 }
1367 #endif /* CONSOLE_ENABLE */
1368
1369 void sendchar_pf(void *p, char c) {
1370   (void)p;
1371   sendchar((uint8_t)c);
1372 }