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