]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/lufa/lufa.c
rgblight.[ch] more configurable (#3582)
[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     ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
413                                      KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
414
415 #ifdef MOUSE_ENABLE
416     /* Setup Mouse HID Report Endpoint */
417     ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
418                                      MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
419 #endif
420
421 #ifdef EXTRAKEY_ENABLE
422     /* Setup Extra HID Report Endpoint */
423     ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
424                                      EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
425 #endif
426
427 #ifdef RAW_ENABLE
428     /* Setup Raw HID Report Endpoints */
429     ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
430                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
431     ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
432                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
433 #endif
434
435 #ifdef CONSOLE_ENABLE
436     /* Setup Console HID Report Endpoints */
437     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
438                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
439 #if 0
440     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
441                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
442 #endif
443 #endif
444
445 #ifdef NKRO_ENABLE
446     /* Setup NKRO HID Report Endpoints */
447     ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
448                                      NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
449 #endif
450
451 #ifdef MIDI_ENABLE
452     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_IN_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
453     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_OUT_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
454 #endif
455
456 #ifdef VIRTSER_ENABLE
457     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, ENDPOINT_BANK_SINGLE);
458     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_OUT_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
459     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_IN_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
460 #endif
461 }
462
463 /* FIXME: Expose this table in the docs somehow
464 Appendix G: HID Request Support Requirements
465
466 The following table enumerates the requests that need to be supported by various types of HID class devices.
467
468 Device type     GetReport   SetReport   GetIdle     SetIdle     GetProtocol SetProtocol
469 ------------------------------------------------------------------------------------------
470 Boot Mouse      Required    Optional    Optional    Optional    Required    Required
471 Non-Boot Mouse  Required    Optional    Optional    Optional    Optional    Optional
472 Boot Keyboard   Required    Optional    Required    Required    Required    Required
473 Non-Boot Keybrd Required    Optional    Required    Required    Optional    Optional
474 Other Device    Required    Optional    Optional    Optional    Optional    Optional
475 */
476 /** \brief Event handler for the USB_ControlRequest event.
477  *
478  *  This is fired before passing along unhandled control requests to the library for processing internally.
479  */
480 void EVENT_USB_Device_ControlRequest(void)
481 {
482     uint8_t* ReportData = NULL;
483     uint8_t  ReportSize = 0;
484
485     /* Handle HID Class specific requests */
486     switch (USB_ControlRequest.bRequest)
487     {
488         case HID_REQ_GetReport:
489             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
490             {
491                 Endpoint_ClearSETUP();
492
493                 // Interface
494                 switch (USB_ControlRequest.wIndex) {
495                 case KEYBOARD_INTERFACE:
496                     // TODO: test/check
497                     ReportData = (uint8_t*)&keyboard_report_sent;
498                     ReportSize = sizeof(keyboard_report_sent);
499                     break;
500                 }
501
502                 /* Write the report data to the control endpoint */
503                 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
504                 Endpoint_ClearOUT();
505             }
506
507             break;
508         case HID_REQ_SetReport:
509             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
510             {
511
512                 // Interface
513                 switch (USB_ControlRequest.wIndex) {
514                 case KEYBOARD_INTERFACE:
515 #ifdef NKRO_ENABLE
516                 case NKRO_INTERFACE:
517 #endif
518                     Endpoint_ClearSETUP();
519
520                     while (!(Endpoint_IsOUTReceived())) {
521                         if (USB_DeviceState == DEVICE_STATE_Unattached)
522                           return;
523                     }
524                     keyboard_led_stats = Endpoint_Read_8();
525
526                     Endpoint_ClearOUT();
527                     Endpoint_ClearStatusStage();
528                     break;
529                 }
530
531             }
532
533             break;
534
535         case HID_REQ_GetProtocol:
536             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
537             {
538                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
539                     Endpoint_ClearSETUP();
540                     while (!(Endpoint_IsINReady()));
541                     Endpoint_Write_8(keyboard_protocol);
542                     Endpoint_ClearIN();
543                     Endpoint_ClearStatusStage();
544                 }
545             }
546
547             break;
548         case HID_REQ_SetProtocol:
549             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
550             {
551                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
552                     Endpoint_ClearSETUP();
553                     Endpoint_ClearStatusStage();
554
555                     keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
556                     clear_keyboard();
557                 }
558             }
559
560             break;
561         case HID_REQ_SetIdle:
562             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
563             {
564                 Endpoint_ClearSETUP();
565                 Endpoint_ClearStatusStage();
566
567                 keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
568             }
569
570             break;
571         case HID_REQ_GetIdle:
572             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
573             {
574                 Endpoint_ClearSETUP();
575                 while (!(Endpoint_IsINReady()));
576                 Endpoint_Write_8(keyboard_idle);
577                 Endpoint_ClearIN();
578                 Endpoint_ClearStatusStage();
579             }
580
581             break;
582     }
583
584 #ifdef VIRTSER_ENABLE
585     CDC_Device_ProcessControlRequest(&cdc_device);
586 #endif
587 }
588
589 /*******************************************************************************
590  * Host driver
591  ******************************************************************************/
592 /** \brief Keyboard LEDs
593  *
594  * FIXME: Needs doc
595  */
596 static uint8_t keyboard_leds(void)
597 {
598     return keyboard_led_stats;
599 }
600
601 /** \brief Send Keyboard
602  *
603  * FIXME: Needs doc
604  */
605 static void send_keyboard(report_keyboard_t *report)
606 {
607     uint8_t timeout = 255;
608     uint8_t where = where_to_send();
609
610 #ifdef BLUETOOTH_ENABLE
611   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
612     #ifdef MODULE_ADAFRUIT_BLE
613       adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
614     #elif MODULE_RN42
615        bluefruit_serial_send(0xFD);
616        bluefruit_serial_send(0x09);
617        bluefruit_serial_send(0x01);
618        for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
619          bluefruit_serial_send(report->raw[i]);
620        }
621     #else
622       bluefruit_serial_send(0xFD);
623       for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
624         bluefruit_serial_send(report->raw[i]);
625       }
626     #endif
627   }
628 #endif
629
630     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
631       return;
632     }
633
634     /* Select the Keyboard Report Endpoint */
635 #ifdef NKRO_ENABLE
636     if (keyboard_protocol && keymap_config.nkro) {
637         /* Report protocol - NKRO */
638         Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
639
640         /* Check if write ready for a polling interval around 1ms */
641         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
642         if (!Endpoint_IsReadWriteAllowed()) return;
643
644         /* Write Keyboard Report Data */
645         Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
646     }
647     else
648 #endif
649     {
650         /* Boot protocol */
651         Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
652
653         /* Check if write ready for a polling interval around 10ms */
654         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
655         if (!Endpoint_IsReadWriteAllowed()) return;
656
657         /* Write Keyboard Report Data */
658         Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
659     }
660
661     /* Finalize the stream transfer to send the last packet */
662     Endpoint_ClearIN();
663
664     keyboard_report_sent = *report;
665 }
666  
667 /** \brief Send Mouse
668  *
669  * FIXME: Needs doc
670  */
671 static void send_mouse(report_mouse_t *report)
672 {
673 #ifdef MOUSE_ENABLE
674     uint8_t timeout = 255;
675     uint8_t where = where_to_send();
676
677 #ifdef BLUETOOTH_ENABLE
678   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
679     #ifdef MODULE_ADAFRUIT_BLE
680       // FIXME: mouse buttons
681       adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
682     #else
683       bluefruit_serial_send(0xFD);
684       bluefruit_serial_send(0x00);
685       bluefruit_serial_send(0x03);
686       bluefruit_serial_send(report->buttons);
687       bluefruit_serial_send(report->x);
688       bluefruit_serial_send(report->y);
689       bluefruit_serial_send(report->v); // should try sending the wheel v here
690       bluefruit_serial_send(report->h); // should try sending the wheel h here
691       bluefruit_serial_send(0x00);
692     #endif
693   }
694 #endif
695
696     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
697       return;
698     }
699
700     /* Select the Mouse Report Endpoint */
701     Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
702
703     /* Check if write ready for a polling interval around 10ms */
704     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
705     if (!Endpoint_IsReadWriteAllowed()) return;
706
707     /* Write Mouse Report Data */
708     Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
709
710     /* Finalize the stream transfer to send the last packet */
711     Endpoint_ClearIN();
712 #endif
713 }
714
715 /** \brief Send System
716  *
717  * FIXME: Needs doc
718  */
719 static void send_system(uint16_t data)
720 {
721     uint8_t timeout = 255;
722
723     if (USB_DeviceState != DEVICE_STATE_Configured)
724         return;
725
726     report_extra_t r = {
727         .report_id = REPORT_ID_SYSTEM,
728         .usage = data - SYSTEM_POWER_DOWN + 1
729     };
730     Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
731
732     /* Check if write ready for a polling interval around 10ms */
733     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
734     if (!Endpoint_IsReadWriteAllowed()) return;
735
736     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
737     Endpoint_ClearIN();
738 }
739
740 /** \brief Send Consumer
741  *
742  * FIXME: Needs doc
743  */
744 static void send_consumer(uint16_t data)
745 {
746     uint8_t timeout = 255;
747     uint8_t where = where_to_send();
748
749 #ifdef BLUETOOTH_ENABLE
750     if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
751       #ifdef MODULE_ADAFRUIT_BLE
752         adafruit_ble_send_consumer_key(data, 0);
753       #elif MODULE_RN42
754         static uint16_t last_data = 0;
755         if (data == last_data) return;
756         last_data = data;
757         uint16_t bitmap = CONSUMER2RN42(data);
758         bluefruit_serial_send(0xFD);
759         bluefruit_serial_send(0x03);
760         bluefruit_serial_send(0x03);
761         bluefruit_serial_send(bitmap&0xFF);
762         bluefruit_serial_send((bitmap>>8)&0xFF);
763       #else
764         static uint16_t last_data = 0;
765         if (data == last_data) return;
766         last_data = data;
767         uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
768         bluefruit_serial_send(0xFD);
769         bluefruit_serial_send(0x00);
770         bluefruit_serial_send(0x02);
771         bluefruit_serial_send((bitmap>>8)&0xFF);
772         bluefruit_serial_send(bitmap&0xFF);
773         bluefruit_serial_send(0x00);
774         bluefruit_serial_send(0x00);
775         bluefruit_serial_send(0x00);
776         bluefruit_serial_send(0x00);
777       #endif
778     }
779 #endif
780
781     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
782       return;
783     }
784
785     report_extra_t r = {
786         .report_id = REPORT_ID_CONSUMER,
787         .usage = data
788     };
789     Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
790
791     /* Check if write ready for a polling interval around 10ms */
792     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
793     if (!Endpoint_IsReadWriteAllowed()) return;
794
795     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
796     Endpoint_ClearIN();
797 }
798
799
800 /*******************************************************************************
801  * sendchar
802  ******************************************************************************/
803 #ifdef CONSOLE_ENABLE
804 #define SEND_TIMEOUT 5
805 /** \brief Send Char
806  *
807  * FIXME: Needs doc
808  */
809 int8_t sendchar(uint8_t c)
810 {
811     // Not wait once timeouted.
812     // Because sendchar() is called so many times, waiting each call causes big lag.
813     static bool timeouted = false;
814
815     // prevents Console_Task() from running during sendchar() runs.
816     // or char will be lost. These two function is mutually exclusive.
817     CONSOLE_FLUSH_SET(false);
818
819     if (USB_DeviceState != DEVICE_STATE_Configured)
820         return -1;
821
822     uint8_t ep = Endpoint_GetCurrentEndpoint();
823     Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
824     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
825         goto ERROR_EXIT;
826     }
827
828     if (timeouted && !Endpoint_IsReadWriteAllowed()) {
829         goto ERROR_EXIT;
830     }
831
832     timeouted = false;
833
834     uint8_t timeout = SEND_TIMEOUT;
835     while (!Endpoint_IsReadWriteAllowed()) {
836         if (USB_DeviceState != DEVICE_STATE_Configured) {
837             goto ERROR_EXIT;
838         }
839         if (Endpoint_IsStalled()) {
840             goto ERROR_EXIT;
841         }
842         if (!(timeout--)) {
843             timeouted = true;
844             goto ERROR_EXIT;
845         }
846         _delay_ms(1);
847     }
848
849     Endpoint_Write_8(c);
850
851     // send when bank is full
852     if (!Endpoint_IsReadWriteAllowed()) {
853         while (!(Endpoint_IsINReady()));
854         Endpoint_ClearIN();
855     } else {
856         CONSOLE_FLUSH_SET(true);
857     }
858
859     Endpoint_SelectEndpoint(ep);
860     return 0;
861 ERROR_EXIT:
862     Endpoint_SelectEndpoint(ep);
863     return -1;
864 }
865 #else
866 int8_t sendchar(uint8_t c)
867 {
868     return 0;
869 }
870 #endif
871
872 /*******************************************************************************
873  * MIDI
874  ******************************************************************************/
875
876 #ifdef MIDI_ENABLE
877 USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
878 {
879   .Config =
880   {
881     .StreamingInterfaceNumber = AS_INTERFACE,
882     .DataINEndpoint           =
883     {
884       .Address          = MIDI_STREAM_IN_EPADDR,
885       .Size             = MIDI_STREAM_EPSIZE,
886       .Banks            = 1,
887     },
888     .DataOUTEndpoint          =
889     {
890       .Address          = MIDI_STREAM_OUT_EPADDR,
891       .Size             = MIDI_STREAM_EPSIZE,
892       .Banks            = 1,
893     },
894   },
895 };
896
897 void send_midi_packet(MIDI_EventPacket_t* event) {
898   MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
899 }
900
901 bool recv_midi_packet(MIDI_EventPacket_t* const event) {
902   return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
903 }
904
905 #endif
906
907 /*******************************************************************************
908  * VIRTUAL SERIAL
909  ******************************************************************************/
910
911 #ifdef VIRTSER_ENABLE
912 /** \brief Virtual Serial Init
913  *
914  * FIXME: Needs doc
915  */
916 void virtser_init(void)
917 {
918   cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
919   CDC_Device_SendControlLineStateChange(&cdc_device);
920 }
921
922 /** \brief Virtual Serial Receive
923  *
924  * FIXME: Needs doc
925  */
926 void virtser_recv(uint8_t c) __attribute__ ((weak));
927 void virtser_recv(uint8_t c)
928 {
929   // Ignore by default
930 }
931
932 /** \brief Virtual Serial Task
933  *
934  * FIXME: Needs doc
935  */
936 void virtser_task(void)
937 {
938   uint16_t count = CDC_Device_BytesReceived(&cdc_device);
939   uint8_t ch;
940   if (count)
941   {
942     ch = CDC_Device_ReceiveByte(&cdc_device);
943     virtser_recv(ch);
944   }
945 }
946 /** \brief Virtual Serial Send
947  *
948  * FIXME: Needs doc
949  */
950 void virtser_send(const uint8_t byte)
951 {
952   uint8_t timeout = 255;
953   uint8_t ep = Endpoint_GetCurrentEndpoint();
954
955   if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
956   {
957     /* IN packet */
958     Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
959
960     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
961         Endpoint_SelectEndpoint(ep);
962         return;
963     }
964
965     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
966
967     Endpoint_Write_8(byte);
968     CDC_Device_Flush(&cdc_device);
969
970     if (Endpoint_IsINReady()) {
971       Endpoint_ClearIN();
972     }
973
974     Endpoint_SelectEndpoint(ep);
975   }
976 }
977 #endif
978
979 /*******************************************************************************
980  * main
981  ******************************************************************************/
982 /** \brief Setup MCU
983  *
984  * FIXME: Needs doc
985  */
986 static void setup_mcu(void)
987 {
988     /* Disable watchdog if enabled by bootloader/fuses */
989     MCUSR &= ~(1 << WDRF);
990     wdt_disable();
991
992     /* Disable clock division */
993     // clock_prescale_set(clock_div_1);
994
995     CLKPR = (1 << CLKPCE);
996     CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
997 }
998
999 /** \brief Setup USB
1000  *
1001  * FIXME: Needs doc
1002  */
1003 static void setup_usb(void)
1004 {
1005     // Leonardo needs. Without this USB device is not recognized.
1006     USB_Disable();
1007
1008     USB_Init();
1009
1010     // for Console_Task
1011     USB_Device_EnableSOFEvents();
1012     print_set_sendchar(sendchar);
1013 }
1014
1015 /** \brief Main
1016  *
1017  * FIXME: Needs doc
1018  */
1019 int main(void)  __attribute__ ((weak));
1020 int main(void)
1021 {
1022 #ifdef MIDI_ENABLE
1023     setup_midi();
1024 #endif
1025
1026     setup_mcu();
1027     keyboard_setup();
1028     setup_usb();
1029     sei();
1030
1031 #if defined(MODULE_ADAFRUIT_EZKEY) || defined(MODULE_RN42)
1032     serial_init();
1033 #endif
1034
1035     /* wait for USB startup & debug output */
1036
1037 #ifdef WAIT_FOR_USB
1038     while (USB_DeviceState != DEVICE_STATE_Configured) {
1039     #if defined(INTERRUPT_CONTROL_ENDPOINT)
1040             ;
1041     #else
1042             USB_USBTask();
1043     #endif
1044     }
1045     print("USB configured.\n");
1046 #else
1047     USB_USBTask();
1048 #endif
1049     /* init modules */
1050     keyboard_init();
1051     host_set_driver(&lufa_driver);
1052 #ifdef SLEEP_LED_ENABLE
1053     sleep_led_init();
1054 #endif
1055
1056 #ifdef VIRTSER_ENABLE
1057     virtser_init();
1058 #endif
1059
1060     print("Keyboard start.\n");
1061     while (1) {
1062         #if !defined(NO_USB_STARTUP_CHECK)
1063         while (USB_DeviceState == DEVICE_STATE_Suspended) {
1064             print("[s]");
1065             suspend_power_down();
1066             if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
1067                     USB_Device_SendRemoteWakeup();
1068             }
1069         }
1070         #endif
1071
1072         keyboard_task();
1073
1074 #ifdef MIDI_ENABLE
1075         MIDI_Device_USBTask(&USB_MIDI_Interface);
1076 #endif
1077
1078 #if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
1079         rgblight_task();
1080 #endif
1081
1082 #ifdef MODULE_ADAFRUIT_BLE
1083         adafruit_ble_task();
1084 #endif
1085
1086 #ifdef VIRTSER_ENABLE
1087         virtser_task();
1088         CDC_Device_USBTask(&cdc_device);
1089 #endif
1090
1091 #ifdef RAW_ENABLE
1092         raw_hid_task();
1093 #endif
1094
1095 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
1096         USB_USBTask();
1097 #endif
1098
1099     }
1100 }
1101
1102 uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
1103                                     const uint16_t wIndex,
1104                                     const void** const DescriptorAddress)
1105 {
1106   return get_usb_descriptor(wValue, wIndex, DescriptorAddress);
1107 }
1108