]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/lufa/lufa.c
Merge branch 'master' into default_atreus_layout
[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 "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 "sysex_tools.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 #ifdef MIDI_ENABLE
101 static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
102 static void usb_get_midi(MidiDevice * device);
103 static void midi_usb_init(MidiDevice * device);
104 #endif
105
106 /* Host driver */
107 static uint8_t keyboard_leds(void);
108 static void send_keyboard(report_keyboard_t *report);
109 static void send_mouse(report_mouse_t *report);
110 static void send_system(uint16_t data);
111 static void send_consumer(uint16_t data);
112 host_driver_t lufa_driver = {
113     keyboard_leds,
114     send_keyboard,
115     send_mouse,
116     send_system,
117     send_consumer,
118 #ifdef MIDI_ENABLE
119     usb_send_func,
120     usb_get_midi,
121     midi_usb_init
122 #endif
123 };
124
125 /*******************************************************************************
126  * MIDI
127  ******************************************************************************/
128
129 #ifdef MIDI_ENABLE
130 USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
131 {
132   .Config =
133   {
134     .StreamingInterfaceNumber = AS_INTERFACE,
135     .DataINEndpoint           =
136     {
137       .Address          = MIDI_STREAM_IN_EPADDR,
138       .Size             = MIDI_STREAM_EPSIZE,
139       .Banks            = 1,
140     },
141     .DataOUTEndpoint          =
142     {
143       .Address          = MIDI_STREAM_OUT_EPADDR,
144       .Size             = MIDI_STREAM_EPSIZE,
145       .Banks            = 1,
146     },
147   },
148 };
149
150 #define SYSEX_START_OR_CONT 0x40
151 #define SYSEX_ENDS_IN_1 0x50
152 #define SYSEX_ENDS_IN_2 0x60
153 #define SYSEX_ENDS_IN_3 0x70
154
155 #define SYS_COMMON_1 0x50
156 #define SYS_COMMON_2 0x20
157 #define SYS_COMMON_3 0x30
158 #endif
159
160 #ifdef VIRTSER_ENABLE
161 USB_ClassInfo_CDC_Device_t cdc_device =
162 {
163   .Config =
164   {
165     .ControlInterfaceNumber = CCI_INTERFACE,
166     .DataINEndpoint         =
167     {
168       .Address          = CDC_IN_EPADDR,
169       .Size             = CDC_EPSIZE,
170       .Banks            = 1,
171     },
172     .DataOUTEndpoint        =
173     {
174       .Address          = CDC_OUT_EPADDR,
175       .Size             = CDC_EPSIZE,
176       .Banks            = 1,
177     },
178     .NotificationEndpoint   =
179     {
180       .Address          = CDC_NOTIFICATION_EPADDR,
181       .Size             = CDC_NOTIFICATION_EPSIZE,
182       .Banks            = 1,
183     },
184   },
185 };
186 #endif
187
188 #ifdef RAW_ENABLE
189
190 void raw_hid_send( uint8_t *data, uint8_t length )
191 {
192         // TODO: implement variable size packet
193         if ( length != RAW_EPSIZE )
194         {
195                 return;
196         }
197
198         if (USB_DeviceState != DEVICE_STATE_Configured)
199         {
200                 return;
201         }
202
203         // TODO: decide if we allow calls to raw_hid_send() in the middle
204         // of other endpoint usage.
205         uint8_t ep = Endpoint_GetCurrentEndpoint();
206
207         Endpoint_SelectEndpoint(RAW_IN_EPNUM);
208
209         // Check to see if the host is ready to accept another packet
210         if (Endpoint_IsINReady())
211         {
212                 // Write data
213                 Endpoint_Write_Stream_LE(data, RAW_EPSIZE, NULL);
214                 // Finalize the stream transfer to send the last packet
215                 Endpoint_ClearIN();
216         }
217
218         Endpoint_SelectEndpoint(ep);
219 }
220
221 __attribute__ ((weak))
222 void raw_hid_receive( uint8_t *data, uint8_t length )
223 {
224         // Users should #include "raw_hid.h" in their own code
225         // and implement this function there. Leave this as weak linkage
226         // so users can opt to not handle data coming in.
227 }
228
229 static void raw_hid_task(void)
230 {
231         // Create a temporary buffer to hold the read in data from the host
232         uint8_t data[RAW_EPSIZE];
233         bool data_read = false;
234
235         // Device must be connected and configured for the task to run
236         if (USB_DeviceState != DEVICE_STATE_Configured)
237         return;
238
239         Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
240
241         // Check to see if a packet has been sent from the host
242         if (Endpoint_IsOUTReceived())
243         {
244                 // Check to see if the packet contains data
245                 if (Endpoint_IsReadWriteAllowed())
246                 {
247                         /* Read data */
248                         Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
249                         data_read = true;
250                 }
251
252                 // Finalize the stream transfer to receive the last packet
253                 Endpoint_ClearOUT();
254
255                 if ( data_read )
256                 {
257                         raw_hid_receive( data, sizeof(data) );
258                 }
259         }
260 }
261 #endif
262
263 /*******************************************************************************
264  * Console
265  ******************************************************************************/
266 #ifdef CONSOLE_ENABLE
267 static void Console_Task(void)
268 {
269     /* Device must be connected and configured for the task to run */
270     if (USB_DeviceState != DEVICE_STATE_Configured)
271         return;
272
273     uint8_t ep = Endpoint_GetCurrentEndpoint();
274
275 #if 0
276     // TODO: impl receivechar()/recvchar()
277     Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
278
279     /* Check to see if a packet has been sent from the host */
280     if (Endpoint_IsOUTReceived())
281     {
282         /* Check to see if the packet contains data */
283         if (Endpoint_IsReadWriteAllowed())
284         {
285             /* Create a temporary buffer to hold the read in report from the host */
286             uint8_t ConsoleData[CONSOLE_EPSIZE];
287
288             /* Read Console Report Data */
289             Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
290
291             /* Process Console Report Data */
292             //ProcessConsoleHIDReport(ConsoleData);
293         }
294
295         /* Finalize the stream transfer to send the last packet */
296         Endpoint_ClearOUT();
297     }
298 #endif
299
300     /* IN packet */
301     Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
302     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
303         Endpoint_SelectEndpoint(ep);
304         return;
305     }
306
307     // fill empty bank
308     while (Endpoint_IsReadWriteAllowed())
309         Endpoint_Write_8(0);
310
311     // flash senchar packet
312     if (Endpoint_IsINReady()) {
313         Endpoint_ClearIN();
314     }
315
316     Endpoint_SelectEndpoint(ep);
317 }
318 #endif
319
320
321 /*******************************************************************************
322  * USB Events
323  ******************************************************************************/
324 /*
325  * Event Order of Plug in:
326  * 0) EVENT_USB_Device_Connect
327  * 1) EVENT_USB_Device_Suspend
328  * 2) EVENT_USB_Device_Reset
329  * 3) EVENT_USB_Device_Wake
330 */
331 void EVENT_USB_Device_Connect(void)
332 {
333     print("[C]");
334     /* For battery powered device */
335     if (!USB_IsInitialized) {
336         USB_Disable();
337         USB_Init();
338         USB_Device_EnableSOFEvents();
339     }
340 }
341
342 void EVENT_USB_Device_Disconnect(void)
343 {
344     print("[D]");
345     /* For battery powered device */
346     USB_IsInitialized = false;
347 /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
348     if (USB_IsInitialized) {
349         USB_Disable();  // Disable all interrupts
350         USB_Controller_Enable();
351         USB_INT_Enable(USB_INT_VBUSTI);
352     }
353 */
354 }
355
356 void EVENT_USB_Device_Reset(void)
357 {
358     print("[R]");
359 }
360
361 void EVENT_USB_Device_Suspend()
362 {
363     print("[S]");
364 #ifdef SLEEP_LED_ENABLE
365     sleep_led_enable();
366 #endif
367 }
368
369 void EVENT_USB_Device_WakeUp()
370 {
371     print("[W]");
372     suspend_wakeup_init();
373
374 #ifdef SLEEP_LED_ENABLE
375     sleep_led_disable();
376     // NOTE: converters may not accept this
377     led_set(host_keyboard_leds());
378 #endif
379 }
380
381
382
383 #ifdef CONSOLE_ENABLE
384 static bool console_flush = false;
385 #define CONSOLE_FLUSH_SET(b)   do { \
386   ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {\
387     console_flush = b; \
388   } \
389 } while (0)
390
391 // called every 1ms
392 void EVENT_USB_Device_StartOfFrame(void)
393 {
394     static uint8_t count;
395     if (++count % 50) return;
396     count = 0;
397
398     if (!console_flush) return;
399     Console_Task();
400     console_flush = false;
401 }
402
403 #endif
404
405 /** Event handler for the USB_ConfigurationChanged event.
406  * This is fired when the host sets the current configuration of the USB device after enumeration.
407  *
408  * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
409  * it is safe to use singl bank for all endpoints.
410  */
411 void EVENT_USB_Device_ConfigurationChanged(void)
412 {
413     bool ConfigSuccess = true;
414
415     /* Setup Keyboard HID Report Endpoints */
416     ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
417                                      KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
418
419 #ifdef MOUSE_ENABLE
420     /* Setup Mouse HID Report Endpoint */
421     ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
422                                      MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
423 #endif
424
425 #ifdef EXTRAKEY_ENABLE
426     /* Setup Extra HID Report Endpoint */
427     ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
428                                      EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
429 #endif
430
431 #ifdef RAW_ENABLE
432     /* Setup Raw HID Report Endpoints */
433     ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
434                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
435     ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
436                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
437 #endif
438
439 #ifdef CONSOLE_ENABLE
440     /* Setup Console HID Report Endpoints */
441     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
442                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
443 #if 0
444     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
445                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
446 #endif
447 #endif
448
449 #ifdef NKRO_ENABLE
450     /* Setup NKRO HID Report Endpoints */
451     ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
452                                      NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
453 #endif
454
455 #ifdef MIDI_ENABLE
456     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_IN_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
457     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_OUT_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
458 #endif
459
460 #ifdef VIRTSER_ENABLE
461     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, ENDPOINT_BANK_SINGLE);
462     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_OUT_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
463     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_IN_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
464 #endif
465 }
466
467 /*
468 Appendix G: HID Request Support Requirements
469
470 The following table enumerates the requests that need to be supported by various types of HID class devices.
471
472 Device type     GetReport   SetReport   GetIdle     SetIdle     GetProtocol SetProtocol
473 ------------------------------------------------------------------------------------------
474 Boot Mouse      Required    Optional    Optional    Optional    Required    Required
475 Non-Boot Mouse  Required    Optional    Optional    Optional    Optional    Optional
476 Boot Keyboard   Required    Optional    Required    Required    Required    Required
477 Non-Boot Keybrd Required    Optional    Required    Required    Optional    Optional
478 Other Device    Required    Optional    Optional    Optional    Optional    Optional
479 */
480 /** Event handler for the USB_ControlRequest event.
481  *  This is fired before passing along unhandled control requests to the library for processing internally.
482  */
483 void EVENT_USB_Device_ControlRequest(void)
484 {
485     uint8_t* ReportData = NULL;
486     uint8_t  ReportSize = 0;
487
488     /* Handle HID Class specific requests */
489     switch (USB_ControlRequest.bRequest)
490     {
491         case HID_REQ_GetReport:
492             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
493             {
494                 Endpoint_ClearSETUP();
495
496                 // Interface
497                 switch (USB_ControlRequest.wIndex) {
498                 case KEYBOARD_INTERFACE:
499                     // TODO: test/check
500                     ReportData = (uint8_t*)&keyboard_report_sent;
501                     ReportSize = sizeof(keyboard_report_sent);
502                     break;
503                 }
504
505                 /* Write the report data to the control endpoint */
506                 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
507                 Endpoint_ClearOUT();
508             }
509
510             break;
511         case HID_REQ_SetReport:
512             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
513             {
514
515                 // Interface
516                 switch (USB_ControlRequest.wIndex) {
517                 case KEYBOARD_INTERFACE:
518 #ifdef NKRO_ENABLE
519                 case NKRO_INTERFACE:
520 #endif
521                     Endpoint_ClearSETUP();
522
523                     while (!(Endpoint_IsOUTReceived())) {
524                         if (USB_DeviceState == DEVICE_STATE_Unattached)
525                           return;
526                     }
527                     keyboard_led_stats = Endpoint_Read_8();
528
529                     Endpoint_ClearOUT();
530                     Endpoint_ClearStatusStage();
531                     break;
532                 }
533
534             }
535
536             break;
537
538         case HID_REQ_GetProtocol:
539             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
540             {
541                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
542                     Endpoint_ClearSETUP();
543                     while (!(Endpoint_IsINReady()));
544                     Endpoint_Write_8(keyboard_protocol);
545                     Endpoint_ClearIN();
546                     Endpoint_ClearStatusStage();
547                 }
548             }
549
550             break;
551         case HID_REQ_SetProtocol:
552             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
553             {
554                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
555                     Endpoint_ClearSETUP();
556                     Endpoint_ClearStatusStage();
557
558                     keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
559                     clear_keyboard();
560                 }
561             }
562
563             break;
564         case HID_REQ_SetIdle:
565             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
566             {
567                 Endpoint_ClearSETUP();
568                 Endpoint_ClearStatusStage();
569
570                 keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
571             }
572
573             break;
574         case HID_REQ_GetIdle:
575             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
576             {
577                 Endpoint_ClearSETUP();
578                 while (!(Endpoint_IsINReady()));
579                 Endpoint_Write_8(keyboard_idle);
580                 Endpoint_ClearIN();
581                 Endpoint_ClearStatusStage();
582             }
583
584             break;
585     }
586
587 #ifdef VIRTSER_ENABLE
588     CDC_Device_ProcessControlRequest(&cdc_device);
589 #endif
590 }
591
592 /*******************************************************************************
593  * Host driver
594  ******************************************************************************/
595 static uint8_t keyboard_leds(void)
596 {
597     return keyboard_led_stats;
598 }
599
600 static void send_keyboard(report_keyboard_t *report)
601 {
602     uint8_t timeout = 255;
603     uint8_t where = where_to_send();
604
605 #ifdef BLUETOOTH_ENABLE
606   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
607     #ifdef MODULE_ADAFRUIT_BLE
608       adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
609     #else
610       bluefruit_serial_send(0xFD);
611       for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
612         bluefruit_serial_send(report->raw[i]);
613       }
614     #endif
615   }
616 #endif
617
618     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
619       return;
620     }
621
622     /* Select the Keyboard Report Endpoint */
623 #ifdef NKRO_ENABLE
624     if (keyboard_protocol && keymap_config.nkro) {
625         /* Report protocol - NKRO */
626         Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
627
628         /* Check if write ready for a polling interval around 1ms */
629         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
630         if (!Endpoint_IsReadWriteAllowed()) return;
631
632         /* Write Keyboard Report Data */
633         Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
634     }
635     else
636 #endif
637     {
638         /* Boot protocol */
639         Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
640
641         /* Check if write ready for a polling interval around 10ms */
642         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
643         if (!Endpoint_IsReadWriteAllowed()) return;
644
645         /* Write Keyboard Report Data */
646         Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
647     }
648
649     /* Finalize the stream transfer to send the last packet */
650     Endpoint_ClearIN();
651
652     keyboard_report_sent = *report;
653 }
654
655 static void send_mouse(report_mouse_t *report)
656 {
657 #ifdef MOUSE_ENABLE
658     uint8_t timeout = 255;
659     uint8_t where = where_to_send();
660
661 #ifdef BLUETOOTH_ENABLE
662   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
663     #ifdef MODULE_ADAFRUIT_BLE
664       // FIXME: mouse buttons
665       adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h);
666     #else
667       bluefruit_serial_send(0xFD);
668       bluefruit_serial_send(0x00);
669       bluefruit_serial_send(0x03);
670       bluefruit_serial_send(report->buttons);
671       bluefruit_serial_send(report->x);
672       bluefruit_serial_send(report->y);
673       bluefruit_serial_send(report->v); // should try sending the wheel v here
674       bluefruit_serial_send(report->h); // should try sending the wheel h here
675       bluefruit_serial_send(0x00);
676     #endif
677   }
678 #endif
679
680     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
681       return;
682     }
683
684     /* Select the Mouse Report Endpoint */
685     Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
686
687     /* Check if write ready for a polling interval around 10ms */
688     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
689     if (!Endpoint_IsReadWriteAllowed()) return;
690
691     /* Write Mouse Report Data */
692     Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
693
694     /* Finalize the stream transfer to send the last packet */
695     Endpoint_ClearIN();
696 #endif
697 }
698
699 static void send_system(uint16_t data)
700 {
701     uint8_t timeout = 255;
702
703     if (USB_DeviceState != DEVICE_STATE_Configured)
704         return;
705
706     report_extra_t r = {
707         .report_id = REPORT_ID_SYSTEM,
708         .usage = data - SYSTEM_POWER_DOWN + 1
709     };
710     Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
711
712     /* Check if write ready for a polling interval around 10ms */
713     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
714     if (!Endpoint_IsReadWriteAllowed()) return;
715
716     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
717     Endpoint_ClearIN();
718 }
719
720 static void send_consumer(uint16_t data)
721 {
722     uint8_t timeout = 255;
723     uint8_t where = where_to_send();
724
725 #ifdef BLUETOOTH_ENABLE
726     if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
727       #ifdef MODULE_ADAFRUIT_BLE
728         adafruit_ble_send_consumer_key(data, 0);
729       #else
730         static uint16_t last_data = 0;
731         if (data == last_data) return;
732         last_data = data;
733         uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
734         bluefruit_serial_send(0xFD);
735         bluefruit_serial_send(0x00);
736         bluefruit_serial_send(0x02);
737         bluefruit_serial_send((bitmap>>8)&0xFF);
738         bluefruit_serial_send(bitmap&0xFF);
739         bluefruit_serial_send(0x00);
740         bluefruit_serial_send(0x00);
741         bluefruit_serial_send(0x00);
742         bluefruit_serial_send(0x00);
743       #endif
744     }
745 #endif
746
747     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
748       return;
749     }
750
751     report_extra_t r = {
752         .report_id = REPORT_ID_CONSUMER,
753         .usage = data
754     };
755     Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
756
757     /* Check if write ready for a polling interval around 10ms */
758     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
759     if (!Endpoint_IsReadWriteAllowed()) return;
760
761     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
762     Endpoint_ClearIN();
763 }
764
765
766 /*******************************************************************************
767  * sendchar
768  ******************************************************************************/
769 #ifdef CONSOLE_ENABLE
770 #define SEND_TIMEOUT 5
771 int8_t sendchar(uint8_t c)
772 {
773     // Not wait once timeouted.
774     // Because sendchar() is called so many times, waiting each call causes big lag.
775     static bool timeouted = false;
776
777     // prevents Console_Task() from running during sendchar() runs.
778     // or char will be lost. These two function is mutually exclusive.
779     CONSOLE_FLUSH_SET(false);
780
781     if (USB_DeviceState != DEVICE_STATE_Configured)
782         return -1;
783
784     uint8_t ep = Endpoint_GetCurrentEndpoint();
785     Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
786     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
787         goto ERROR_EXIT;
788     }
789
790     if (timeouted && !Endpoint_IsReadWriteAllowed()) {
791         goto ERROR_EXIT;
792     }
793
794     timeouted = false;
795
796     uint8_t timeout = SEND_TIMEOUT;
797     while (!Endpoint_IsReadWriteAllowed()) {
798         if (USB_DeviceState != DEVICE_STATE_Configured) {
799             goto ERROR_EXIT;
800         }
801         if (Endpoint_IsStalled()) {
802             goto ERROR_EXIT;
803         }
804         if (!(timeout--)) {
805             timeouted = true;
806             goto ERROR_EXIT;
807         }
808         _delay_ms(1);
809     }
810
811     Endpoint_Write_8(c);
812
813     // send when bank is full
814     if (!Endpoint_IsReadWriteAllowed()) {
815         while (!(Endpoint_IsINReady()));
816         Endpoint_ClearIN();
817     } else {
818         CONSOLE_FLUSH_SET(true);
819     }
820
821     Endpoint_SelectEndpoint(ep);
822     return 0;
823 ERROR_EXIT:
824     Endpoint_SelectEndpoint(ep);
825     return -1;
826 }
827 #else
828 int8_t sendchar(uint8_t c)
829 {
830     return 0;
831 }
832 #endif
833
834 /*******************************************************************************
835  * MIDI
836  ******************************************************************************/
837
838 #ifdef MIDI_ENABLE
839 static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) {
840   MIDI_EventPacket_t event;
841   event.Data1 = byte0;
842   event.Data2 = byte1;
843   event.Data3 = byte2;
844
845   uint8_t cable = 0;
846
847 // Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPNUM);
848
849   //if the length is undefined we assume it is a SYSEX message
850   if (midi_packet_length(byte0) == UNDEFINED) {
851     switch(cnt) {
852       case 3:
853         if (byte2 == SYSEX_END)
854           event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_3);
855         else
856           event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
857         break;
858       case 2:
859         if (byte1 == SYSEX_END)
860           event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_2);
861         else
862           event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
863         break;
864       case 1:
865         if (byte0 == SYSEX_END)
866           event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_1);
867         else
868           event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
869         break;
870       default:
871         return; //invalid cnt
872     }
873   } else {
874     //deal with 'system common' messages
875     //TODO are there any more?
876     switch(byte0 & 0xF0){
877       case MIDI_SONGPOSITION:
878         event.Event = MIDI_EVENT(cable, SYS_COMMON_3);
879         break;
880       case MIDI_SONGSELECT:
881       case MIDI_TC_QUARTERFRAME:
882         event.Event = MIDI_EVENT(cable, SYS_COMMON_2);
883         break;
884       default:
885         event.Event = MIDI_EVENT(cable, byte0);
886         break;
887     }
888   }
889
890 // Endpoint_Write_Stream_LE(&event, sizeof(event), NULL);
891 // Endpoint_ClearIN();
892
893   MIDI_Device_SendEventPacket(&USB_MIDI_Interface, &event);
894   MIDI_Device_Flush(&USB_MIDI_Interface);
895   MIDI_Device_USBTask(&USB_MIDI_Interface);
896   USB_USBTask();
897 }
898
899 static void usb_get_midi(MidiDevice * device) {
900   MIDI_EventPacket_t event;
901   while (MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, &event)) {
902
903     midi_packet_length_t length = midi_packet_length(event.Data1);
904     uint8_t input[3];
905     input[0] = event.Data1;
906     input[1] = event.Data2;
907     input[2] = event.Data3;
908     if (length == UNDEFINED) {
909       //sysex
910       if (event.Event == MIDI_EVENT(0, SYSEX_START_OR_CONT) || event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_3)) {
911         length = 3;
912       } else if (event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_2)) {
913         length = 2;
914       } else if(event.Event ==  MIDI_EVENT(0, SYSEX_ENDS_IN_1)) {
915         length = 1;
916       } else {
917         //XXX what to do?
918       }
919     }
920
921     //pass the data to the device input function
922     if (length != UNDEFINED)
923       midi_device_input(device, length, input);
924   }
925   MIDI_Device_USBTask(&USB_MIDI_Interface);
926   USB_USBTask();
927 }
928
929 static void midi_usb_init(MidiDevice * device){
930   midi_device_init(device);
931   midi_device_set_send_func(device, usb_send_func);
932   midi_device_set_pre_input_process_func(device, usb_get_midi);
933
934   // SetupHardware();
935   sei();
936 }
937
938 void MIDI_Task(void)
939 {
940
941     /* Device must be connected and configured for the task to run */
942     dprint("in MIDI_TASK\n");
943     if (USB_DeviceState != DEVICE_STATE_Configured)
944       return;
945     dprint("continuing in MIDI_TASK\n");
946
947     Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPADDR);
948
949     if (Endpoint_IsINReady())
950     {
951
952         dprint("Endpoint is ready\n");
953
954         uint8_t MIDICommand = 0;
955         uint8_t MIDIPitch;
956
957         /* Get board button status - if pressed use channel 10 (percussion), otherwise use channel 1 */
958         uint8_t Channel = MIDI_CHANNEL(1);
959
960         MIDICommand = MIDI_COMMAND_NOTE_ON;
961         MIDIPitch   = 0x3E;
962
963         /* Check if a MIDI command is to be sent */
964         if (MIDICommand)
965         {
966             dprint("Command exists\n");
967             MIDI_EventPacket_t MIDIEvent = (MIDI_EventPacket_t)
968                 {
969                     .Event       = MIDI_EVENT(0, MIDICommand),
970
971                     .Data1       = MIDICommand | Channel,
972                     .Data2       = MIDIPitch,
973                     .Data3       = MIDI_STANDARD_VELOCITY,
974                 };
975
976             /* Write the MIDI event packet to the endpoint */
977             Endpoint_Write_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
978
979             /* Send the data in the endpoint to the host */
980             Endpoint_ClearIN();
981         }
982     }
983
984
985     /* Select the MIDI OUT stream */
986     Endpoint_SelectEndpoint(MIDI_STREAM_OUT_EPADDR);
987
988     /* Check if a MIDI command has been received */
989     if (Endpoint_IsOUTReceived())
990     {
991         MIDI_EventPacket_t MIDIEvent;
992
993         /* Read the MIDI event packet from the endpoint */
994         Endpoint_Read_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
995
996         /* If the endpoint is now empty, clear the bank */
997         if (!(Endpoint_BytesInEndpoint()))
998         {
999             /* Clear the endpoint ready for new packet */
1000             Endpoint_ClearOUT();
1001         }
1002     }
1003 }
1004
1005 #endif
1006
1007 /*******************************************************************************
1008  * VIRTUAL SERIAL
1009  ******************************************************************************/
1010
1011 #ifdef VIRTSER_ENABLE
1012 void virtser_init(void)
1013 {
1014   cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
1015   CDC_Device_SendControlLineStateChange(&cdc_device);
1016 }
1017
1018 void virtser_recv(uint8_t c) __attribute__ ((weak));
1019 void virtser_recv(uint8_t c)
1020 {
1021   // Ignore by default
1022 }
1023
1024 void virtser_task(void)
1025 {
1026   uint16_t count = CDC_Device_BytesReceived(&cdc_device);
1027   uint8_t ch;
1028   if (count)
1029   {
1030     ch = CDC_Device_ReceiveByte(&cdc_device);
1031     virtser_recv(ch);
1032   }
1033 }
1034 void virtser_send(const uint8_t byte)
1035 {
1036   uint8_t timeout = 255;
1037   uint8_t ep = Endpoint_GetCurrentEndpoint();
1038
1039   if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
1040   {
1041     /* IN packet */
1042     Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
1043
1044     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
1045         Endpoint_SelectEndpoint(ep);
1046         return;
1047     }
1048
1049     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
1050
1051     Endpoint_Write_8(byte);
1052     CDC_Device_Flush(&cdc_device);
1053
1054     if (Endpoint_IsINReady()) {
1055       Endpoint_ClearIN();
1056     }
1057
1058     Endpoint_SelectEndpoint(ep);
1059   }
1060 }
1061 #endif
1062
1063 /*******************************************************************************
1064  * main
1065  ******************************************************************************/
1066 static void setup_mcu(void)
1067 {
1068     /* Disable watchdog if enabled by bootloader/fuses */
1069     MCUSR &= ~(1 << WDRF);
1070     wdt_disable();
1071
1072     /* Disable clock division */
1073     // clock_prescale_set(clock_div_1);
1074
1075     CLKPR = (1 << CLKPCE);
1076     CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
1077 }
1078
1079 static void setup_usb(void)
1080 {
1081     // Leonardo needs. Without this USB device is not recognized.
1082     USB_Disable();
1083
1084     USB_Init();
1085
1086     // for Console_Task
1087     USB_Device_EnableSOFEvents();
1088     print_set_sendchar(sendchar);
1089 }
1090
1091
1092 #ifdef MIDI_ENABLE
1093 void fallthrough_callback(MidiDevice * device,
1094     uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
1095 void cc_callback(MidiDevice * device,
1096     uint8_t chan, uint8_t num, uint8_t val);
1097 void sysex_callback(MidiDevice * device,
1098     uint16_t start, uint8_t length, uint8_t * data);
1099
1100 void setup_midi(void)
1101 {
1102 #ifdef MIDI_ADVANCED
1103         midi_init();
1104 #endif
1105         midi_device_init(&midi_device);
1106     midi_device_set_send_func(&midi_device, usb_send_func);
1107     midi_device_set_pre_input_process_func(&midi_device, usb_get_midi);
1108 }
1109 #endif
1110
1111 int main(void)  __attribute__ ((weak));
1112 int main(void)
1113 {
1114 #ifdef MIDI_ENABLE
1115     setup_midi();
1116 #endif
1117
1118     setup_mcu();
1119     keyboard_setup();
1120     setup_usb();
1121     sei();
1122
1123 #ifdef MIDI_ENABLE
1124     midi_register_fallthrough_callback(&midi_device, fallthrough_callback);
1125     midi_register_cc_callback(&midi_device, cc_callback);
1126     midi_register_sysex_callback(&midi_device, sysex_callback);
1127
1128     // init_notes();
1129     // midi_send_cc(&midi_device, 0, 1, 2);
1130     // midi_send_cc(&midi_device, 15, 1, 0);
1131     // midi_send_noteon(&midi_device, 0, 64, 127);
1132     // midi_send_noteoff(&midi_device, 0, 64, 127);
1133 #endif
1134
1135 #ifdef MODULE_ADAFRUIT_EZKEY
1136     serial_init();
1137 #endif
1138
1139     /* wait for USB startup & debug output */
1140
1141 #ifdef WAIT_FOR_USB
1142     while (USB_DeviceState != DEVICE_STATE_Configured) {
1143     #if defined(INTERRUPT_CONTROL_ENDPOINT)
1144             ;
1145     #else
1146             USB_USBTask();
1147     #endif
1148     }
1149     print("USB configured.\n");
1150 #else
1151     USB_USBTask();
1152 #endif
1153     /* init modules */
1154     keyboard_init();
1155     host_set_driver(&lufa_driver);
1156 #ifdef SLEEP_LED_ENABLE
1157     sleep_led_init();
1158 #endif
1159
1160 #ifdef VIRTSER_ENABLE
1161     virtser_init();
1162 #endif
1163
1164     print("Keyboard start.\n");
1165     while (1) {
1166         #if !defined(BLUETOOTH_ENABLE)
1167         while (USB_DeviceState == DEVICE_STATE_Suspended) {
1168             print("[s]");
1169             suspend_power_down();
1170             if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
1171                     USB_Device_SendRemoteWakeup();
1172             }
1173         }
1174         #endif
1175
1176         keyboard_task();
1177
1178 #ifdef MIDI_ENABLE
1179         midi_device_process(&midi_device);
1180 #ifdef MIDI_ADVANCED
1181         midi_task();
1182 #endif
1183 #endif
1184
1185 #if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
1186         rgblight_task();
1187 #endif
1188
1189 #ifdef MODULE_ADAFRUIT_BLE
1190         adafruit_ble_task();
1191 #endif
1192
1193 #ifdef VIRTSER_ENABLE
1194         virtser_task();
1195         CDC_Device_USBTask(&cdc_device);
1196 #endif
1197
1198 #ifdef RAW_ENABLE
1199         raw_hid_task();
1200 #endif
1201
1202 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
1203         USB_USBTask();
1204 #endif
1205
1206     }
1207 }
1208
1209 #ifdef MIDI_ENABLE
1210 void fallthrough_callback(MidiDevice * device,
1211     uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2){
1212
1213 #ifdef AUDIO_ENABLE
1214   if (cnt == 3) {
1215     switch (byte0 & 0xF0) {
1216         case MIDI_NOTEON:
1217             play_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0), (byte2 & 0x7F) / 8);
1218             break;
1219         case MIDI_NOTEOFF:
1220             stop_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0));
1221             break;
1222     }
1223   }
1224   if (byte0 == MIDI_STOP) {
1225     stop_all_notes();
1226   }
1227 #endif
1228 }
1229
1230
1231 void cc_callback(MidiDevice * device,
1232     uint8_t chan, uint8_t num, uint8_t val) {
1233   //sending it back on the next channel
1234   // midi_send_cc(device, (chan + 1) % 16, num, val);
1235 }
1236
1237 #ifdef API_SYSEX_ENABLE
1238 uint8_t midi_buffer[MIDI_SYSEX_BUFFER] = {0};
1239 #endif
1240
1241 void sysex_callback(MidiDevice * device, uint16_t start, uint8_t length, uint8_t * data) {
1242     #ifdef API_SYSEX_ENABLE
1243         // SEND_STRING("\n");
1244         // send_word(start);
1245         // SEND_STRING(": ");
1246         // Don't store the header
1247         int16_t pos = start - 4;
1248         for (uint8_t place = 0; place < length; place++) {
1249             // send_byte(*data);
1250             if (pos >= 0) {
1251                 if (*data == 0xF7) {
1252                     // SEND_STRING("\nRD: ");
1253                     // for (uint8_t i = 0; i < start + place + 1; i++){
1254                     //     send_byte(midi_buffer[i]);
1255                     // SEND_STRING(" ");
1256                     // }
1257                     const unsigned decoded_length = sysex_decoded_length(pos);
1258                     uint8_t decoded[API_SYSEX_MAX_SIZE];
1259                     sysex_decode(decoded, midi_buffer, pos);
1260                     process_api(decoded_length, decoded);
1261                     return;
1262                 }
1263                 else if (pos >= MIDI_SYSEX_BUFFER) {
1264                     return;
1265                 }
1266                 midi_buffer[pos] = *data;
1267             }
1268             // SEND_STRING(" ");
1269             data++;
1270             pos++;
1271         }
1272     #endif
1273 }
1274
1275
1276 #endif