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