]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/lufa/lufa.c
Use a single endpoint for HID reports (#3951)
[qmk_firmware.git] / tmk_core / protocol / lufa / lufa.c
1 /*
2  * Copyright 2012 Jun Wako <wakojun@gmail.com>
3  * This file is based on:
4  *     LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
5  *     LUFA-120219/Demos/Device/Lowlevel/GenericHID
6  */
7
8 /*
9              LUFA Library
10      Copyright (C) Dean Camera, 2012.
11
12   dean [at] fourwalledcubicle [dot] com
13            www.lufa-lib.org
14 */
15
16 /*
17   Copyright 2012  Dean Camera (dean [at] fourwalledcubicle [dot] com)
18   Copyright 2010  Denver Gingerich (denver [at] ossguy [dot] com)
19
20   Permission to use, copy, modify, distribute, and sell this
21   software and its documentation for any purpose is hereby granted
22   without fee, provided that the above copyright notice appear in
23   all copies and that both that the copyright notice and this
24   permission notice and warranty disclaimer appear in supporting
25   documentation, and that the name of the author not be used in
26   advertising or publicity pertaining to distribution of the
27   software without specific, written prior permission.
28
29   The author disclaim all warranties with regard to this
30   software, including all implied warranties of merchantability
31   and fitness.  In no event shall the author be liable for any
32   special, indirect or consequential damages or any damages
33   whatsoever resulting from loss of use, data or profits, whether
34   in an action of contract, negligence or other tortious action,
35   arising out of or in connection with the use or performance of
36   this software.
37 */
38
39 #include "report.h"
40 #include "host.h"
41 #include "host_driver.h"
42 #include "keyboard.h"
43 #include "action.h"
44 #include "led.h"
45 #include "sendchar.h"
46 #include "debug.h"
47 #ifdef SLEEP_LED_ENABLE
48 #include "sleep_led.h"
49 #endif
50 #include "suspend.h"
51
52 #include "usb_descriptor.h"
53 #include "lufa.h"
54 #include "quantum.h"
55 #include <util/atomic.h>
56 #include "outputselect.h"
57 #include "rgblight_reconfig.h"
58
59 #ifdef NKRO_ENABLE
60   #include "keycode_config.h"
61
62   extern keymap_config_t keymap_config;
63 #endif
64
65
66 #ifdef AUDIO_ENABLE
67     #include <audio.h>
68 #endif
69
70 #ifdef BLUETOOTH_ENABLE
71   #ifdef MODULE_ADAFRUIT_BLE
72     #include "adafruit_ble.h"
73   #else
74     #include "bluetooth.h"
75   #endif
76 #endif
77
78 #ifdef VIRTSER_ENABLE
79     #include "virtser.h"
80 #endif
81
82 #if (defined(RGB_MIDI) | defined(RGBLIGHT_ANIMATIONS)) & defined(RGBLIGHT_ENABLE)
83     #include "rgblight.h"
84 #endif
85
86 #ifdef MIDI_ENABLE
87   #include "qmk_midi.h"
88 #endif
89
90 #ifdef RAW_ENABLE
91         #include "raw_hid.h"
92 #endif
93
94 uint8_t keyboard_idle = 0;
95 /* 0: Boot Protocol, 1: Report Protocol(default) */
96 uint8_t keyboard_protocol = 1;
97 static uint8_t keyboard_led_stats = 0;
98
99 static report_keyboard_t keyboard_report_sent;
100
101 /* Host driver */
102 static uint8_t keyboard_leds(void);
103 static void send_keyboard(report_keyboard_t *report);
104 static void send_mouse(report_mouse_t *report);
105 static void send_system(uint16_t data);
106 static void send_consumer(uint16_t data);
107 host_driver_t lufa_driver = {
108     keyboard_leds,
109     send_keyboard,
110     send_mouse,
111     send_system,
112     send_consumer,
113 };
114
115 #ifdef VIRTSER_ENABLE
116 USB_ClassInfo_CDC_Device_t cdc_device =
117 {
118   .Config =
119   {
120     .ControlInterfaceNumber = CCI_INTERFACE,
121     .DataINEndpoint         =
122     {
123       .Address          = CDC_IN_EPADDR,
124       .Size             = CDC_EPSIZE,
125       .Banks            = 1,
126     },
127     .DataOUTEndpoint        =
128     {
129       .Address          = CDC_OUT_EPADDR,
130       .Size             = CDC_EPSIZE,
131       .Banks            = 1,
132     },
133     .NotificationEndpoint   =
134     {
135       .Address          = CDC_NOTIFICATION_EPADDR,
136       .Size             = CDC_NOTIFICATION_EPSIZE,
137       .Banks            = 1,
138     },
139   },
140 };
141 #endif
142
143 #ifdef RAW_ENABLE
144
145 /** \brief Raw HID Send
146  *
147  * FIXME: Needs doc
148  */
149 void raw_hid_send( uint8_t *data, uint8_t length )
150 {
151         // TODO: implement variable size packet
152         if ( length != RAW_EPSIZE )
153         {
154                 return;
155         }
156
157         if (USB_DeviceState != DEVICE_STATE_Configured)
158         {
159                 return;
160         }
161
162         // TODO: decide if we allow calls to raw_hid_send() in the middle
163         // of other endpoint usage.
164         uint8_t ep = Endpoint_GetCurrentEndpoint();
165
166         Endpoint_SelectEndpoint(RAW_IN_EPNUM);
167
168         // Check to see if the host is ready to accept another packet
169         if (Endpoint_IsINReady())
170         {
171                 // Write data
172                 Endpoint_Write_Stream_LE(data, RAW_EPSIZE, NULL);
173                 // Finalize the stream transfer to send the last packet
174                 Endpoint_ClearIN();
175         }
176
177         Endpoint_SelectEndpoint(ep);
178 }
179
180 /** \brief Raw HID Receive
181  *
182  * FIXME: Needs doc
183  */
184 __attribute__ ((weak))
185 void raw_hid_receive( uint8_t *data, uint8_t length )
186 {
187         // Users should #include "raw_hid.h" in their own code
188         // and implement this function there. Leave this as weak linkage
189         // so users can opt to not handle data coming in.
190 }
191
192 /** \brief Raw HID Task
193  *
194  * FIXME: Needs doc
195  */
196 static void raw_hid_task(void)
197 {
198         // Create a temporary buffer to hold the read in data from the host
199         uint8_t data[RAW_EPSIZE];
200         bool data_read = false;
201
202         // Device must be connected and configured for the task to run
203         if (USB_DeviceState != DEVICE_STATE_Configured)
204         return;
205
206         Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
207
208         // Check to see if a packet has been sent from the host
209         if (Endpoint_IsOUTReceived())
210         {
211                 // Check to see if the packet contains data
212                 if (Endpoint_IsReadWriteAllowed())
213                 {
214                         /* Read data */
215                         Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
216                         data_read = true;
217                 }
218
219                 // Finalize the stream transfer to receive the last packet
220                 Endpoint_ClearOUT();
221
222                 if ( data_read )
223                 {
224                         raw_hid_receive( data, sizeof(data) );
225                 }
226         }
227 }
228 #endif
229
230 /*******************************************************************************
231  * Console
232  ******************************************************************************/
233 #ifdef CONSOLE_ENABLE
234 /** \brief Console Task
235  *
236  * FIXME: Needs doc
237  */
238 static void Console_Task(void)
239 {
240     /* Device must be connected and configured for the task to run */
241     if (USB_DeviceState != DEVICE_STATE_Configured)
242         return;
243
244     uint8_t ep = Endpoint_GetCurrentEndpoint();
245
246 #if 0
247     // TODO: impl receivechar()/recvchar()
248     Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
249
250     /* Check to see if a packet has been sent from the host */
251     if (Endpoint_IsOUTReceived())
252     {
253         /* Check to see if the packet contains data */
254         if (Endpoint_IsReadWriteAllowed())
255         {
256             /* Create a temporary buffer to hold the read in report from the host */
257             uint8_t ConsoleData[CONSOLE_EPSIZE];
258
259             /* Read Console Report Data */
260             Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
261
262             /* Process Console Report Data */
263             //ProcessConsoleHIDReport(ConsoleData);
264         }
265
266         /* Finalize the stream transfer to send the last packet */
267         Endpoint_ClearOUT();
268     }
269 #endif
270
271     /* IN packet */
272     Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
273     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
274         Endpoint_SelectEndpoint(ep);
275         return;
276     }
277
278     // fill empty bank
279     while (Endpoint_IsReadWriteAllowed())
280         Endpoint_Write_8(0);
281
282     // flash senchar packet
283     if (Endpoint_IsINReady()) {
284         Endpoint_ClearIN();
285     }
286
287     Endpoint_SelectEndpoint(ep);
288 }
289 #endif
290
291
292 /*******************************************************************************
293  * USB Events
294  ******************************************************************************/
295 /*
296  * Event Order of Plug in:
297  * 0) EVENT_USB_Device_Connect
298  * 1) EVENT_USB_Device_Suspend
299  * 2) EVENT_USB_Device_Reset
300  * 3) EVENT_USB_Device_Wake
301 */
302 /** \brief Event USB Device Connect
303  *
304  * FIXME: Needs doc
305  */
306 void EVENT_USB_Device_Connect(void)
307 {
308     print("[C]");
309     /* For battery powered device */
310     if (!USB_IsInitialized) {
311         USB_Disable();
312         USB_Init();
313         USB_Device_EnableSOFEvents();
314     }
315 }
316
317 /** \brief Event USB Device Connect
318  *
319  * FIXME: Needs doc
320  */
321 void EVENT_USB_Device_Disconnect(void)
322 {
323     print("[D]");
324     /* For battery powered device */
325     USB_IsInitialized = false;
326 /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
327     if (USB_IsInitialized) {
328         USB_Disable();  // Disable all interrupts
329         USB_Controller_Enable();
330         USB_INT_Enable(USB_INT_VBUSTI);
331     }
332 */
333 }
334
335 /** \brief Event USB Device Connect
336  *
337  * FIXME: Needs doc
338  */
339 void EVENT_USB_Device_Reset(void)
340 {
341     print("[R]");
342 }
343
344 /** \brief Event USB Device Connect
345  *
346  * FIXME: Needs doc
347  */
348 void EVENT_USB_Device_Suspend()
349 {
350     print("[S]");
351 #ifdef SLEEP_LED_ENABLE
352     sleep_led_enable();
353 #endif
354 }
355
356 /** \brief Event USB Device Connect
357  *
358  * FIXME: Needs doc
359  */
360 void EVENT_USB_Device_WakeUp()
361 {
362     print("[W]");
363     suspend_wakeup_init();
364
365 #ifdef SLEEP_LED_ENABLE
366     sleep_led_disable();
367     // NOTE: converters may not accept this
368     led_set(host_keyboard_leds());
369 #endif
370 }
371
372
373
374 #ifdef CONSOLE_ENABLE
375 static bool console_flush = false;
376 #define CONSOLE_FLUSH_SET(b)   do { \
377   ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {\
378     console_flush = b; \
379   } \
380 } while (0)
381
382 /** \brief Event USB Device Start Of Frame
383  *
384  * FIXME: Needs doc
385  * called every 1ms
386  */
387 void EVENT_USB_Device_StartOfFrame(void)
388 {
389     static uint8_t count;
390     if (++count % 50) return;
391     count = 0;
392
393     if (!console_flush) return;
394     Console_Task();
395     console_flush = false;
396 }
397
398 #endif
399
400 /** \brief Event handler for the USB_ConfigurationChanged event.
401  *
402  * This is fired when the host sets the current configuration of the USB device after enumeration.
403  *
404  * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
405  * it is safe to use single bank for all endpoints.
406  */
407 void EVENT_USB_Device_ConfigurationChanged(void)
408 {
409     bool ConfigSuccess = true;
410
411     /* Setup Keyboard HID Report Endpoints */
412 #ifndef KEYBOARD_SHARED_EP
413     ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
414                                      KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
415 #endif
416
417 #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
418     /* Setup Mouse HID Report Endpoint */
419     ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
420                                      MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
421 #endif
422
423 #ifdef SHARED_EP_ENABLE
424     /* Setup Shared HID Report Endpoint */
425     ConfigSuccess &= ENDPOINT_CONFIG(SHARED_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
426                                      SHARED_EPSIZE, ENDPOINT_BANK_SINGLE);
427 #endif
428
429 #ifdef RAW_ENABLE
430     /* Setup Raw HID Report Endpoints */
431     ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
432                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
433     ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
434                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
435 #endif
436
437 #ifdef CONSOLE_ENABLE
438     /* Setup Console HID Report Endpoints */
439     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
440                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
441 #if 0
442     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
443                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
444 #endif
445 #endif
446
447 #ifdef MIDI_ENABLE
448     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_IN_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
449     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_OUT_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
450 #endif
451
452 #ifdef VIRTSER_ENABLE
453     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, ENDPOINT_BANK_SINGLE);
454     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_OUT_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
455     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_IN_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
456 #endif
457 }
458
459 /* FIXME: Expose this table in the docs somehow
460 Appendix G: HID Request Support Requirements
461
462 The following table enumerates the requests that need to be supported by various types of HID class devices.
463
464 Device type     GetReport   SetReport   GetIdle     SetIdle     GetProtocol SetProtocol
465 ------------------------------------------------------------------------------------------
466 Boot Mouse      Required    Optional    Optional    Optional    Required    Required
467 Non-Boot Mouse  Required    Optional    Optional    Optional    Optional    Optional
468 Boot Keyboard   Required    Optional    Required    Required    Required    Required
469 Non-Boot Keybrd Required    Optional    Required    Required    Optional    Optional
470 Other Device    Required    Optional    Optional    Optional    Optional    Optional
471 */
472 /** \brief Event handler for the USB_ControlRequest event.
473  *
474  *  This is fired before passing along unhandled control requests to the library for processing internally.
475  */
476 void EVENT_USB_Device_ControlRequest(void)
477 {
478     uint8_t* ReportData = NULL;
479     uint8_t  ReportSize = 0;
480
481     /* Handle HID Class specific requests */
482     switch (USB_ControlRequest.bRequest)
483     {
484         case HID_REQ_GetReport:
485             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
486             {
487                 Endpoint_ClearSETUP();
488
489                 // Interface
490                 switch (USB_ControlRequest.wIndex) {
491                 case KEYBOARD_INTERFACE:
492                     // TODO: test/check
493                     ReportData = (uint8_t*)&keyboard_report_sent;
494                     ReportSize = sizeof(keyboard_report_sent);
495                     break;
496                 }
497
498                 /* Write the report data to the control endpoint */
499                 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
500                 Endpoint_ClearOUT();
501             }
502
503             break;
504         case HID_REQ_SetReport:
505             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
506             {
507
508                 // Interface
509                 switch (USB_ControlRequest.wIndex) {
510                 case KEYBOARD_INTERFACE:
511 #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
512                 case SHARED_INTERFACE:
513 #endif
514                     Endpoint_ClearSETUP();
515
516                     while (!(Endpoint_IsOUTReceived())) {
517                         if (USB_DeviceState == DEVICE_STATE_Unattached)
518                           return;
519                     }
520 #if defined(SHARED_EP_ENABLE)
521                     uint8_t report_id = REPORT_ID_KEYBOARD;
522                     if (keyboard_protocol) {
523                        report_id = Endpoint_Read_8();
524                     }
525                     if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
526                         keyboard_led_stats = Endpoint_Read_8();
527                     }
528 #else
529                     keyboard_led_stats = Endpoint_Read_8();
530 #endif
531
532                     Endpoint_ClearOUT();
533                     Endpoint_ClearStatusStage();
534                     break;
535                 }
536
537             }
538
539             break;
540
541         case HID_REQ_GetProtocol:
542             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
543             {
544                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
545                     Endpoint_ClearSETUP();
546                     while (!(Endpoint_IsINReady()));
547                     Endpoint_Write_8(keyboard_protocol);
548                     Endpoint_ClearIN();
549                     Endpoint_ClearStatusStage();
550                 }
551             }
552
553             break;
554         case HID_REQ_SetProtocol:
555             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
556             {
557                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
558                     Endpoint_ClearSETUP();
559                     Endpoint_ClearStatusStage();
560
561                     keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
562                     clear_keyboard();
563                 }
564             }
565
566             break;
567         case HID_REQ_SetIdle:
568             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
569             {
570                 Endpoint_ClearSETUP();
571                 Endpoint_ClearStatusStage();
572
573                 keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
574             }
575
576             break;
577         case HID_REQ_GetIdle:
578             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
579             {
580                 Endpoint_ClearSETUP();
581                 while (!(Endpoint_IsINReady()));
582                 Endpoint_Write_8(keyboard_idle);
583                 Endpoint_ClearIN();
584                 Endpoint_ClearStatusStage();
585             }
586
587             break;
588     }
589
590 #ifdef VIRTSER_ENABLE
591     CDC_Device_ProcessControlRequest(&cdc_device);
592 #endif
593 }
594
595 /*******************************************************************************
596  * Host driver
597  ******************************************************************************/
598 /** \brief Keyboard LEDs
599  *
600  * FIXME: Needs doc
601  */
602 static uint8_t keyboard_leds(void)
603 {
604     return keyboard_led_stats;
605 }
606
607 /** \brief Send Keyboard
608  *
609  * FIXME: Needs doc
610  */
611 static void send_keyboard(report_keyboard_t *report)
612 {
613     uint8_t timeout = 255;
614     uint8_t where = where_to_send();
615
616 #ifdef BLUETOOTH_ENABLE
617   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
618     #ifdef MODULE_ADAFRUIT_BLE
619       adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
620     #elif MODULE_RN42
621       bluefruit_serial_send(0xFD);
622       bluefruit_serial_send(0x09);
623       bluefruit_serial_send(0x01);
624       bluefruit_serial_send(report->mods);
625       bluefruit_serial_send(report->reserved);
626       for (uint8_t i = 0; i < KEYBOARD_REPORT_KEYS; i++) {
627         bluefruit_serial_send(report->keys[i]);
628       }
629     #else
630       bluefruit_serial_send(0xFD);
631       bluefruit_serial_send(report->mods);
632       bluefruit_serial_send(report->reserved);
633       for (uint8_t i = 0; i < KEYBOARD_REPORT_KEYS; i++) {
634         bluefruit_serial_send(report->keys[i]);
635       }
636     #endif
637   }
638 #endif
639
640     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
641       return;
642     }
643
644     /* Select the Keyboard Report Endpoint */
645     uint8_t ep = KEYBOARD_IN_EPNUM;
646     uint8_t size = KEYBOARD_REPORT_SIZE;
647 #ifdef NKRO_ENABLE
648     if (keyboard_protocol && keymap_config.nkro) {
649         ep = SHARED_IN_EPNUM;
650         size = sizeof(struct nkro_report);
651     }
652 #endif
653     Endpoint_SelectEndpoint(ep);
654     /* Check if write ready for a polling interval around 10ms */
655     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
656     if (!Endpoint_IsReadWriteAllowed()) return;
657
658     /* If we're in Boot Protocol, don't send any report ID or other funky fields */
659     if (!keyboard_protocol) {
660         Endpoint_Write_Stream_LE(&report->mods, 8, NULL);
661     } else {
662         Endpoint_Write_Stream_LE(report, size, NULL);
663     }
664
665     /* Finalize the stream transfer to send the last packet */
666     Endpoint_ClearIN();
667
668     keyboard_report_sent = *report;
669 }
670  
671 /** \brief Send Mouse
672  *
673  * FIXME: Needs doc
674  */
675 static void send_mouse(report_mouse_t *report)
676 {
677 #ifdef MOUSE_ENABLE
678     uint8_t timeout = 255;
679     uint8_t where = where_to_send();
680
681 #ifdef BLUETOOTH_ENABLE
682   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
683     #ifdef MODULE_ADAFRUIT_BLE
684       // FIXME: mouse buttons
685       adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
686     #else
687       bluefruit_serial_send(0xFD);
688       bluefruit_serial_send(0x00);
689       bluefruit_serial_send(0x03);
690       bluefruit_serial_send(report->buttons);
691       bluefruit_serial_send(report->x);
692       bluefruit_serial_send(report->y);
693       bluefruit_serial_send(report->v); // should try sending the wheel v here
694       bluefruit_serial_send(report->h); // should try sending the wheel h here
695       bluefruit_serial_send(0x00);
696     #endif
697   }
698 #endif
699
700     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
701       return;
702     }
703
704     /* Select the Mouse Report Endpoint */
705     Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
706
707     /* Check if write ready for a polling interval around 10ms */
708     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
709     if (!Endpoint_IsReadWriteAllowed()) return;
710
711     /* Write Mouse Report Data */
712     Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
713
714     /* Finalize the stream transfer to send the last packet */
715     Endpoint_ClearIN();
716 #endif
717 }
718
719 /** \brief Send System
720  *
721  * FIXME: Needs doc
722  */
723 static void send_system(uint16_t data)
724 {
725 #ifdef EXTRAKEY_ENABLE
726     uint8_t timeout = 255;
727
728     if (USB_DeviceState != DEVICE_STATE_Configured)
729         return;
730
731     report_extra_t r = {
732         .report_id = REPORT_ID_SYSTEM,
733         .usage = data - SYSTEM_POWER_DOWN + 1
734     };
735     Endpoint_SelectEndpoint(SHARED_IN_EPNUM);
736
737     /* Check if write ready for a polling interval around 10ms */
738     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
739     if (!Endpoint_IsReadWriteAllowed()) return;
740
741     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
742     Endpoint_ClearIN();
743 #endif
744 }
745
746 /** \brief Send Consumer
747  *
748  * FIXME: Needs doc
749  */
750 static void send_consumer(uint16_t data)
751 {
752 #ifdef EXTRAKEY_ENABLE
753     uint8_t timeout = 255;
754     uint8_t where = where_to_send();
755
756 #ifdef BLUETOOTH_ENABLE
757     if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
758       #ifdef MODULE_ADAFRUIT_BLE
759         adafruit_ble_send_consumer_key(data, 0);
760       #elif MODULE_RN42
761         static uint16_t last_data = 0;
762         if (data == last_data) return;
763         last_data = data;
764         uint16_t bitmap = CONSUMER2RN42(data);
765         bluefruit_serial_send(0xFD);
766         bluefruit_serial_send(0x03);
767         bluefruit_serial_send(0x03);
768         bluefruit_serial_send(bitmap&0xFF);
769         bluefruit_serial_send((bitmap>>8)&0xFF);
770       #else
771         static uint16_t last_data = 0;
772         if (data == last_data) return;
773         last_data = data;
774         uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
775         bluefruit_serial_send(0xFD);
776         bluefruit_serial_send(0x00);
777         bluefruit_serial_send(0x02);
778         bluefruit_serial_send((bitmap>>8)&0xFF);
779         bluefruit_serial_send(bitmap&0xFF);
780         bluefruit_serial_send(0x00);
781         bluefruit_serial_send(0x00);
782         bluefruit_serial_send(0x00);
783         bluefruit_serial_send(0x00);
784       #endif
785     }
786 #endif
787
788     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
789       return;
790     }
791
792     report_extra_t r = {
793         .report_id = REPORT_ID_CONSUMER,
794         .usage = data
795     };
796     Endpoint_SelectEndpoint(SHARED_IN_EPNUM);
797
798     /* Check if write ready for a polling interval around 10ms */
799     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
800     if (!Endpoint_IsReadWriteAllowed()) return;
801
802     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
803     Endpoint_ClearIN();
804 #endif
805 }
806
807
808 /*******************************************************************************
809  * sendchar
810  ******************************************************************************/
811 #ifdef CONSOLE_ENABLE
812 #define SEND_TIMEOUT 5
813 /** \brief Send Char
814  *
815  * FIXME: Needs doc
816  */
817 int8_t sendchar(uint8_t c)
818 {
819     // Not wait once timeouted.
820     // Because sendchar() is called so many times, waiting each call causes big lag.
821     static bool timeouted = false;
822
823     // prevents Console_Task() from running during sendchar() runs.
824     // or char will be lost. These two function is mutually exclusive.
825     CONSOLE_FLUSH_SET(false);
826
827     if (USB_DeviceState != DEVICE_STATE_Configured)
828         return -1;
829
830     uint8_t ep = Endpoint_GetCurrentEndpoint();
831     Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
832     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
833         goto ERROR_EXIT;
834     }
835
836     if (timeouted && !Endpoint_IsReadWriteAllowed()) {
837         goto ERROR_EXIT;
838     }
839
840     timeouted = false;
841
842     uint8_t timeout = SEND_TIMEOUT;
843     while (!Endpoint_IsReadWriteAllowed()) {
844         if (USB_DeviceState != DEVICE_STATE_Configured) {
845             goto ERROR_EXIT;
846         }
847         if (Endpoint_IsStalled()) {
848             goto ERROR_EXIT;
849         }
850         if (!(timeout--)) {
851             timeouted = true;
852             goto ERROR_EXIT;
853         }
854         _delay_ms(1);
855     }
856
857     Endpoint_Write_8(c);
858
859     // send when bank is full
860     if (!Endpoint_IsReadWriteAllowed()) {
861         while (!(Endpoint_IsINReady()));
862         Endpoint_ClearIN();
863     } else {
864         CONSOLE_FLUSH_SET(true);
865     }
866
867     Endpoint_SelectEndpoint(ep);
868     return 0;
869 ERROR_EXIT:
870     Endpoint_SelectEndpoint(ep);
871     return -1;
872 }
873 #else
874 int8_t sendchar(uint8_t c)
875 {
876     return 0;
877 }
878 #endif
879
880 /*******************************************************************************
881  * MIDI
882  ******************************************************************************/
883
884 #ifdef MIDI_ENABLE
885 USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
886 {
887   .Config =
888   {
889     .StreamingInterfaceNumber = AS_INTERFACE,
890     .DataINEndpoint           =
891     {
892       .Address          = MIDI_STREAM_IN_EPADDR,
893       .Size             = MIDI_STREAM_EPSIZE,
894       .Banks            = 1,
895     },
896     .DataOUTEndpoint          =
897     {
898       .Address          = MIDI_STREAM_OUT_EPADDR,
899       .Size             = MIDI_STREAM_EPSIZE,
900       .Banks            = 1,
901     },
902   },
903 };
904
905 void send_midi_packet(MIDI_EventPacket_t* event) {
906   MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
907 }
908
909 bool recv_midi_packet(MIDI_EventPacket_t* const event) {
910   return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
911 }
912
913 #endif
914
915 /*******************************************************************************
916  * VIRTUAL SERIAL
917  ******************************************************************************/
918
919 #ifdef VIRTSER_ENABLE
920 /** \brief Virtual Serial Init
921  *
922  * FIXME: Needs doc
923  */
924 void virtser_init(void)
925 {
926   cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
927   CDC_Device_SendControlLineStateChange(&cdc_device);
928 }
929
930 /** \brief Virtual Serial Receive
931  *
932  * FIXME: Needs doc
933  */
934 void virtser_recv(uint8_t c) __attribute__ ((weak));
935 void virtser_recv(uint8_t c)
936 {
937   // Ignore by default
938 }
939
940 /** \brief Virtual Serial Task
941  *
942  * FIXME: Needs doc
943  */
944 void virtser_task(void)
945 {
946   uint16_t count = CDC_Device_BytesReceived(&cdc_device);
947   uint8_t ch;
948   if (count)
949   {
950     ch = CDC_Device_ReceiveByte(&cdc_device);
951     virtser_recv(ch);
952   }
953 }
954 /** \brief Virtual Serial Send
955  *
956  * FIXME: Needs doc
957  */
958 void virtser_send(const uint8_t byte)
959 {
960   uint8_t timeout = 255;
961   uint8_t ep = Endpoint_GetCurrentEndpoint();
962
963   if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
964   {
965     /* IN packet */
966     Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
967
968     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
969         Endpoint_SelectEndpoint(ep);
970         return;
971     }
972
973     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
974
975     Endpoint_Write_8(byte);
976     CDC_Device_Flush(&cdc_device);
977
978     if (Endpoint_IsINReady()) {
979       Endpoint_ClearIN();
980     }
981
982     Endpoint_SelectEndpoint(ep);
983   }
984 }
985 #endif
986
987 /*******************************************************************************
988  * main
989  ******************************************************************************/
990 /** \brief Setup MCU
991  *
992  * FIXME: Needs doc
993  */
994 static void setup_mcu(void)
995 {
996     /* Disable watchdog if enabled by bootloader/fuses */
997     MCUSR &= ~(1 << WDRF);
998     wdt_disable();
999
1000     /* Disable clock division */
1001     // clock_prescale_set(clock_div_1);
1002
1003     CLKPR = (1 << CLKPCE);
1004     CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
1005 }
1006
1007 /** \brief Setup USB
1008  *
1009  * FIXME: Needs doc
1010  */
1011 static void setup_usb(void)
1012 {
1013     // Leonardo needs. Without this USB device is not recognized.
1014     USB_Disable();
1015
1016     USB_Init();
1017
1018     // for Console_Task
1019     USB_Device_EnableSOFEvents();
1020     print_set_sendchar(sendchar);
1021 }
1022
1023 /** \brief Main
1024  *
1025  * FIXME: Needs doc
1026  */
1027 int main(void)  __attribute__ ((weak));
1028 int main(void)
1029 {
1030 #ifdef MIDI_ENABLE
1031     setup_midi();
1032 #endif
1033
1034     setup_mcu();
1035     keyboard_setup();
1036     setup_usb();
1037     sei();
1038
1039 #if defined(MODULE_ADAFRUIT_EZKEY) || defined(MODULE_RN42)
1040     serial_init();
1041 #endif
1042
1043     /* wait for USB startup & debug output */
1044
1045 #ifdef WAIT_FOR_USB
1046     while (USB_DeviceState != DEVICE_STATE_Configured) {
1047     #if defined(INTERRUPT_CONTROL_ENDPOINT)
1048             ;
1049     #else
1050             USB_USBTask();
1051     #endif
1052     }
1053     print("USB configured.\n");
1054 #else
1055     USB_USBTask();
1056 #endif
1057     /* init modules */
1058     keyboard_init();
1059     host_set_driver(&lufa_driver);
1060 #ifdef SLEEP_LED_ENABLE
1061     sleep_led_init();
1062 #endif
1063
1064 #ifdef VIRTSER_ENABLE
1065     virtser_init();
1066 #endif
1067
1068     print("Keyboard start.\n");
1069     while (1) {
1070         #if !defined(NO_USB_STARTUP_CHECK)
1071         while (USB_DeviceState == DEVICE_STATE_Suspended) {
1072             print("[s]");
1073             suspend_power_down();
1074             if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
1075                     USB_Device_SendRemoteWakeup();
1076             }
1077         }
1078         #endif
1079
1080         keyboard_task();
1081
1082 #ifdef MIDI_ENABLE
1083         MIDI_Device_USBTask(&USB_MIDI_Interface);
1084 #endif
1085
1086 #if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
1087         rgblight_task();
1088 #endif
1089
1090 #ifdef MODULE_ADAFRUIT_BLE
1091         adafruit_ble_task();
1092 #endif
1093
1094 #ifdef VIRTSER_ENABLE
1095         virtser_task();
1096         CDC_Device_USBTask(&cdc_device);
1097 #endif
1098
1099 #ifdef RAW_ENABLE
1100         raw_hid_task();
1101 #endif
1102
1103 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
1104         USB_USBTask();
1105 #endif
1106
1107     }
1108 }
1109
1110 uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
1111                                     const uint16_t wIndex,
1112                                     const void** const DescriptorAddress)
1113 {
1114   return get_usb_descriptor(wValue, wIndex, DescriptorAddress);
1115 }
1116