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