]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/lufa/lufa.c
ae6129d1a28dfe185129cbef44abdb4d2424f35d
[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     #elif MODULE_RN42
610        bluefruit_serial_send(0xFD);
611        bluefruit_serial_send(0x09);
612        bluefruit_serial_send(0x01);
613        for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
614          bluefruit_serial_send(report->raw[i]);
615        }
616     #else
617       bluefruit_serial_send(0xFD);
618       for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
619         bluefruit_serial_send(report->raw[i]);
620       }
621     #endif
622   }
623 #endif
624
625     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
626       return;
627     }
628
629     /* Select the Keyboard Report Endpoint */
630 #ifdef NKRO_ENABLE
631     if (keyboard_protocol && keymap_config.nkro) {
632         /* Report protocol - NKRO */
633         Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
634
635         /* Check if write ready for a polling interval around 1ms */
636         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
637         if (!Endpoint_IsReadWriteAllowed()) return;
638
639         /* Write Keyboard Report Data */
640         Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
641     }
642     else
643 #endif
644     {
645         /* Boot protocol */
646         Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
647
648         /* Check if write ready for a polling interval around 10ms */
649         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
650         if (!Endpoint_IsReadWriteAllowed()) return;
651
652         /* Write Keyboard Report Data */
653         Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
654     }
655
656     /* Finalize the stream transfer to send the last packet */
657     Endpoint_ClearIN();
658
659     keyboard_report_sent = *report;
660 }
661
662 static void send_mouse(report_mouse_t *report)
663 {
664 #ifdef MOUSE_ENABLE
665     uint8_t timeout = 255;
666     uint8_t where = where_to_send();
667
668 #ifdef BLUETOOTH_ENABLE
669   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
670     #ifdef MODULE_ADAFRUIT_BLE
671       // FIXME: mouse buttons
672       adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h);
673     #else
674       bluefruit_serial_send(0xFD);
675       bluefruit_serial_send(0x00);
676       bluefruit_serial_send(0x03);
677       bluefruit_serial_send(report->buttons);
678       bluefruit_serial_send(report->x);
679       bluefruit_serial_send(report->y);
680       bluefruit_serial_send(report->v); // should try sending the wheel v here
681       bluefruit_serial_send(report->h); // should try sending the wheel h here
682       bluefruit_serial_send(0x00);
683     #endif
684   }
685 #endif
686
687     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
688       return;
689     }
690
691     /* Select the Mouse Report Endpoint */
692     Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
693
694     /* Check if write ready for a polling interval around 10ms */
695     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
696     if (!Endpoint_IsReadWriteAllowed()) return;
697
698     /* Write Mouse Report Data */
699     Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
700
701     /* Finalize the stream transfer to send the last packet */
702     Endpoint_ClearIN();
703 #endif
704 }
705
706 static void send_system(uint16_t data)
707 {
708     uint8_t timeout = 255;
709
710     if (USB_DeviceState != DEVICE_STATE_Configured)
711         return;
712
713     report_extra_t r = {
714         .report_id = REPORT_ID_SYSTEM,
715         .usage = data - SYSTEM_POWER_DOWN + 1
716     };
717     Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
718
719     /* Check if write ready for a polling interval around 10ms */
720     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
721     if (!Endpoint_IsReadWriteAllowed()) return;
722
723     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
724     Endpoint_ClearIN();
725 }
726
727 static void send_consumer(uint16_t data)
728 {
729     uint8_t timeout = 255;
730     uint8_t where = where_to_send();
731
732 #ifdef BLUETOOTH_ENABLE
733     if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
734       #ifdef MODULE_ADAFRUIT_BLE
735         adafruit_ble_send_consumer_key(data, 0);
736       #elif MODULE_RN42
737         static uint16_t last_data = 0;
738         if (data == last_data) return;
739         last_data = data;
740         uint16_t bitmap = CONSUMER2RN42(data);
741         bluefruit_serial_send(0xFD);
742         bluefruit_serial_send(0x03);
743         bluefruit_serial_send(0x03);
744         bluefruit_serial_send(bitmap&0xFF);
745         bluefruit_serial_send((bitmap>>8)&0xFF);
746       #else
747         static uint16_t last_data = 0;
748         if (data == last_data) return;
749         last_data = data;
750         uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
751         bluefruit_serial_send(0xFD);
752         bluefruit_serial_send(0x00);
753         bluefruit_serial_send(0x02);
754         bluefruit_serial_send((bitmap>>8)&0xFF);
755         bluefruit_serial_send(bitmap&0xFF);
756         bluefruit_serial_send(0x00);
757         bluefruit_serial_send(0x00);
758         bluefruit_serial_send(0x00);
759         bluefruit_serial_send(0x00);
760       #endif
761     }
762 #endif
763
764     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
765       return;
766     }
767
768     report_extra_t r = {
769         .report_id = REPORT_ID_CONSUMER,
770         .usage = data
771     };
772     Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
773
774     /* Check if write ready for a polling interval around 10ms */
775     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
776     if (!Endpoint_IsReadWriteAllowed()) return;
777
778     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
779     Endpoint_ClearIN();
780 }
781
782
783 /*******************************************************************************
784  * sendchar
785  ******************************************************************************/
786 #ifdef CONSOLE_ENABLE
787 #define SEND_TIMEOUT 5
788 int8_t sendchar(uint8_t c)
789 {
790     // Not wait once timeouted.
791     // Because sendchar() is called so many times, waiting each call causes big lag.
792     static bool timeouted = false;
793
794     // prevents Console_Task() from running during sendchar() runs.
795     // or char will be lost. These two function is mutually exclusive.
796     CONSOLE_FLUSH_SET(false);
797
798     if (USB_DeviceState != DEVICE_STATE_Configured)
799         return -1;
800
801     uint8_t ep = Endpoint_GetCurrentEndpoint();
802     Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
803     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
804         goto ERROR_EXIT;
805     }
806
807     if (timeouted && !Endpoint_IsReadWriteAllowed()) {
808         goto ERROR_EXIT;
809     }
810
811     timeouted = false;
812
813     uint8_t timeout = SEND_TIMEOUT;
814     while (!Endpoint_IsReadWriteAllowed()) {
815         if (USB_DeviceState != DEVICE_STATE_Configured) {
816             goto ERROR_EXIT;
817         }
818         if (Endpoint_IsStalled()) {
819             goto ERROR_EXIT;
820         }
821         if (!(timeout--)) {
822             timeouted = true;
823             goto ERROR_EXIT;
824         }
825         _delay_ms(1);
826     }
827
828     Endpoint_Write_8(c);
829
830     // send when bank is full
831     if (!Endpoint_IsReadWriteAllowed()) {
832         while (!(Endpoint_IsINReady()));
833         Endpoint_ClearIN();
834     } else {
835         CONSOLE_FLUSH_SET(true);
836     }
837
838     Endpoint_SelectEndpoint(ep);
839     return 0;
840 ERROR_EXIT:
841     Endpoint_SelectEndpoint(ep);
842     return -1;
843 }
844 #else
845 int8_t sendchar(uint8_t c)
846 {
847     return 0;
848 }
849 #endif
850
851 /*******************************************************************************
852  * MIDI
853  ******************************************************************************/
854
855 #ifdef MIDI_ENABLE
856 static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) {
857   MIDI_EventPacket_t event;
858   event.Data1 = byte0;
859   event.Data2 = byte1;
860   event.Data3 = byte2;
861
862   uint8_t cable = 0;
863
864 // Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPNUM);
865
866   //if the length is undefined we assume it is a SYSEX message
867   if (midi_packet_length(byte0) == UNDEFINED) {
868     switch(cnt) {
869       case 3:
870         if (byte2 == SYSEX_END)
871           event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_3);
872         else
873           event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
874         break;
875       case 2:
876         if (byte1 == SYSEX_END)
877           event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_2);
878         else
879           event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
880         break;
881       case 1:
882         if (byte0 == SYSEX_END)
883           event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_1);
884         else
885           event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
886         break;
887       default:
888         return; //invalid cnt
889     }
890   } else {
891     //deal with 'system common' messages
892     //TODO are there any more?
893     switch(byte0 & 0xF0){
894       case MIDI_SONGPOSITION:
895         event.Event = MIDI_EVENT(cable, SYS_COMMON_3);
896         break;
897       case MIDI_SONGSELECT:
898       case MIDI_TC_QUARTERFRAME:
899         event.Event = MIDI_EVENT(cable, SYS_COMMON_2);
900         break;
901       default:
902         event.Event = MIDI_EVENT(cable, byte0);
903         break;
904     }
905   }
906
907 // Endpoint_Write_Stream_LE(&event, sizeof(event), NULL);
908 // Endpoint_ClearIN();
909
910   MIDI_Device_SendEventPacket(&USB_MIDI_Interface, &event);
911   MIDI_Device_Flush(&USB_MIDI_Interface);
912   MIDI_Device_USBTask(&USB_MIDI_Interface);
913   USB_USBTask();
914 }
915
916 static void usb_get_midi(MidiDevice * device) {
917   MIDI_EventPacket_t event;
918   while (MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, &event)) {
919
920     midi_packet_length_t length = midi_packet_length(event.Data1);
921     uint8_t input[3];
922     input[0] = event.Data1;
923     input[1] = event.Data2;
924     input[2] = event.Data3;
925     if (length == UNDEFINED) {
926       //sysex
927       if (event.Event == MIDI_EVENT(0, SYSEX_START_OR_CONT) || event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_3)) {
928         length = 3;
929       } else if (event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_2)) {
930         length = 2;
931       } else if(event.Event ==  MIDI_EVENT(0, SYSEX_ENDS_IN_1)) {
932         length = 1;
933       } else {
934         //XXX what to do?
935       }
936     }
937
938     //pass the data to the device input function
939     if (length != UNDEFINED)
940       midi_device_input(device, length, input);
941   }
942   MIDI_Device_USBTask(&USB_MIDI_Interface);
943   USB_USBTask();
944 }
945
946 static void midi_usb_init(MidiDevice * device){
947   midi_device_init(device);
948   midi_device_set_send_func(device, usb_send_func);
949   midi_device_set_pre_input_process_func(device, usb_get_midi);
950
951   // SetupHardware();
952   sei();
953 }
954
955 void MIDI_Task(void)
956 {
957
958     /* Device must be connected and configured for the task to run */
959     dprint("in MIDI_TASK\n");
960     if (USB_DeviceState != DEVICE_STATE_Configured)
961       return;
962     dprint("continuing in MIDI_TASK\n");
963
964     Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPADDR);
965
966     if (Endpoint_IsINReady())
967     {
968
969         dprint("Endpoint is ready\n");
970
971         uint8_t MIDICommand = 0;
972         uint8_t MIDIPitch;
973
974         /* Get board button status - if pressed use channel 10 (percussion), otherwise use channel 1 */
975         uint8_t Channel = MIDI_CHANNEL(1);
976
977         MIDICommand = MIDI_COMMAND_NOTE_ON;
978         MIDIPitch   = 0x3E;
979
980         /* Check if a MIDI command is to be sent */
981         if (MIDICommand)
982         {
983             dprint("Command exists\n");
984             MIDI_EventPacket_t MIDIEvent = (MIDI_EventPacket_t)
985                 {
986                     .Event       = MIDI_EVENT(0, MIDICommand),
987
988                     .Data1       = MIDICommand | Channel,
989                     .Data2       = MIDIPitch,
990                     .Data3       = MIDI_STANDARD_VELOCITY,
991                 };
992
993             /* Write the MIDI event packet to the endpoint */
994             Endpoint_Write_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
995
996             /* Send the data in the endpoint to the host */
997             Endpoint_ClearIN();
998         }
999     }
1000
1001
1002     /* Select the MIDI OUT stream */
1003     Endpoint_SelectEndpoint(MIDI_STREAM_OUT_EPADDR);
1004
1005     /* Check if a MIDI command has been received */
1006     if (Endpoint_IsOUTReceived())
1007     {
1008         MIDI_EventPacket_t MIDIEvent;
1009
1010         /* Read the MIDI event packet from the endpoint */
1011         Endpoint_Read_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
1012
1013         /* If the endpoint is now empty, clear the bank */
1014         if (!(Endpoint_BytesInEndpoint()))
1015         {
1016             /* Clear the endpoint ready for new packet */
1017             Endpoint_ClearOUT();
1018         }
1019     }
1020 }
1021
1022 #endif
1023
1024 /*******************************************************************************
1025  * VIRTUAL SERIAL
1026  ******************************************************************************/
1027
1028 #ifdef VIRTSER_ENABLE
1029 void virtser_init(void)
1030 {
1031   cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
1032   CDC_Device_SendControlLineStateChange(&cdc_device);
1033 }
1034
1035 void virtser_recv(uint8_t c) __attribute__ ((weak));
1036 void virtser_recv(uint8_t c)
1037 {
1038   // Ignore by default
1039 }
1040
1041 void virtser_task(void)
1042 {
1043   uint16_t count = CDC_Device_BytesReceived(&cdc_device);
1044   uint8_t ch;
1045   if (count)
1046   {
1047     ch = CDC_Device_ReceiveByte(&cdc_device);
1048     virtser_recv(ch);
1049   }
1050 }
1051 void virtser_send(const uint8_t byte)
1052 {
1053   uint8_t timeout = 255;
1054   uint8_t ep = Endpoint_GetCurrentEndpoint();
1055
1056   if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
1057   {
1058     /* IN packet */
1059     Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
1060
1061     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
1062         Endpoint_SelectEndpoint(ep);
1063         return;
1064     }
1065
1066     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
1067
1068     Endpoint_Write_8(byte);
1069     CDC_Device_Flush(&cdc_device);
1070
1071     if (Endpoint_IsINReady()) {
1072       Endpoint_ClearIN();
1073     }
1074
1075     Endpoint_SelectEndpoint(ep);
1076   }
1077 }
1078 #endif
1079
1080 /*******************************************************************************
1081  * main
1082  ******************************************************************************/
1083 static void setup_mcu(void)
1084 {
1085     /* Disable watchdog if enabled by bootloader/fuses */
1086     MCUSR &= ~(1 << WDRF);
1087     wdt_disable();
1088
1089     /* Disable clock division */
1090     // clock_prescale_set(clock_div_1);
1091
1092     CLKPR = (1 << CLKPCE);
1093     CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
1094 }
1095
1096 static void setup_usb(void)
1097 {
1098     // Leonardo needs. Without this USB device is not recognized.
1099     USB_Disable();
1100
1101     USB_Init();
1102
1103     // for Console_Task
1104     USB_Device_EnableSOFEvents();
1105     print_set_sendchar(sendchar);
1106 }
1107
1108
1109 #ifdef MIDI_ENABLE
1110 void fallthrough_callback(MidiDevice * device,
1111     uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
1112 void cc_callback(MidiDevice * device,
1113     uint8_t chan, uint8_t num, uint8_t val);
1114 void sysex_callback(MidiDevice * device,
1115     uint16_t start, uint8_t length, uint8_t * data);
1116
1117 void setup_midi(void)
1118 {
1119 #ifdef MIDI_ADVANCED
1120         midi_init();
1121 #endif
1122         midi_device_init(&midi_device);
1123     midi_device_set_send_func(&midi_device, usb_send_func);
1124     midi_device_set_pre_input_process_func(&midi_device, usb_get_midi);
1125 }
1126 #endif
1127
1128 int main(void)  __attribute__ ((weak));
1129 int main(void)
1130 {
1131 #ifdef MIDI_ENABLE
1132     setup_midi();
1133 #endif
1134
1135     setup_mcu();
1136     keyboard_setup();
1137     setup_usb();
1138     sei();
1139
1140 #ifdef MIDI_ENABLE
1141     midi_register_fallthrough_callback(&midi_device, fallthrough_callback);
1142     midi_register_cc_callback(&midi_device, cc_callback);
1143     midi_register_sysex_callback(&midi_device, sysex_callback);
1144
1145     // init_notes();
1146     // midi_send_cc(&midi_device, 0, 1, 2);
1147     // midi_send_cc(&midi_device, 15, 1, 0);
1148     // midi_send_noteon(&midi_device, 0, 64, 127);
1149     // midi_send_noteoff(&midi_device, 0, 64, 127);
1150 #endif
1151
1152 #if defined(MODULE_ADAFRUIT_EZKEY) || defined(MODULE_RN42)
1153     serial_init();
1154 #endif
1155
1156     /* wait for USB startup & debug output */
1157
1158 #ifdef WAIT_FOR_USB
1159     while (USB_DeviceState != DEVICE_STATE_Configured) {
1160     #if defined(INTERRUPT_CONTROL_ENDPOINT)
1161             ;
1162     #else
1163             USB_USBTask();
1164     #endif
1165     }
1166     print("USB configured.\n");
1167 #else
1168     USB_USBTask();
1169 #endif
1170     /* init modules */
1171     keyboard_init();
1172     host_set_driver(&lufa_driver);
1173 #ifdef SLEEP_LED_ENABLE
1174     sleep_led_init();
1175 #endif
1176
1177 #ifdef VIRTSER_ENABLE
1178     virtser_init();
1179 #endif
1180
1181     print("Keyboard start.\n");
1182     while (1) {
1183         #if !defined(BLUETOOTH_ENABLE)
1184         while (USB_DeviceState == DEVICE_STATE_Suspended) {
1185             print("[s]");
1186             suspend_power_down();
1187             if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
1188                     USB_Device_SendRemoteWakeup();
1189             }
1190         }
1191         #endif
1192
1193         keyboard_task();
1194
1195 #ifdef MIDI_ENABLE
1196         midi_device_process(&midi_device);
1197 #ifdef MIDI_ADVANCED
1198         midi_task();
1199 #endif
1200 #endif
1201
1202 #if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
1203         rgblight_task();
1204 #endif
1205
1206 #ifdef MODULE_ADAFRUIT_BLE
1207         adafruit_ble_task();
1208 #endif
1209
1210 #ifdef VIRTSER_ENABLE
1211         virtser_task();
1212         CDC_Device_USBTask(&cdc_device);
1213 #endif
1214
1215 #ifdef RAW_ENABLE
1216         raw_hid_task();
1217 #endif
1218
1219 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
1220         USB_USBTask();
1221 #endif
1222
1223     }
1224 }
1225
1226 #ifdef MIDI_ENABLE
1227 void fallthrough_callback(MidiDevice * device,
1228     uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2){
1229
1230 #ifdef AUDIO_ENABLE
1231   if (cnt == 3) {
1232     switch (byte0 & 0xF0) {
1233         case MIDI_NOTEON:
1234             play_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0), (byte2 & 0x7F) / 8);
1235             break;
1236         case MIDI_NOTEOFF:
1237             stop_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0));
1238             break;
1239     }
1240   }
1241   if (byte0 == MIDI_STOP) {
1242     stop_all_notes();
1243   }
1244 #endif
1245 }
1246
1247
1248 void cc_callback(MidiDevice * device,
1249     uint8_t chan, uint8_t num, uint8_t val) {
1250   //sending it back on the next channel
1251   // midi_send_cc(device, (chan + 1) % 16, num, val);
1252 }
1253
1254 #ifdef API_SYSEX_ENABLE
1255 uint8_t midi_buffer[MIDI_SYSEX_BUFFER] = {0};
1256 #endif
1257
1258 void sysex_callback(MidiDevice * device, uint16_t start, uint8_t length, uint8_t * data) {
1259     #ifdef API_SYSEX_ENABLE
1260         // SEND_STRING("\n");
1261         // send_word(start);
1262         // SEND_STRING(": ");
1263         // Don't store the header
1264         int16_t pos = start - 4;
1265         for (uint8_t place = 0; place < length; place++) {
1266             // send_byte(*data);
1267             if (pos >= 0) {
1268                 if (*data == 0xF7) {
1269                     // SEND_STRING("\nRD: ");
1270                     // for (uint8_t i = 0; i < start + place + 1; i++){
1271                     //     send_byte(midi_buffer[i]);
1272                     // SEND_STRING(" ");
1273                     // }
1274                     const unsigned decoded_length = sysex_decoded_length(pos);
1275                     uint8_t decoded[API_SYSEX_MAX_SIZE];
1276                     sysex_decode(decoded, midi_buffer, pos);
1277                     process_api(decoded_length, decoded);
1278                     return;
1279                 }
1280                 else if (pos >= MIDI_SYSEX_BUFFER) {
1281                     return;
1282                 }
1283                 midi_buffer[pos] = *data;
1284             }
1285             // SEND_STRING(" ");
1286             data++;
1287             pos++;
1288         }
1289     #endif
1290 }
1291
1292
1293 #endif