]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/lufa/lufa.c
a1cab98a66abd18c9a580c3859427a0d45d9562a
[qmk_firmware.git] / tmk_core / protocol / lufa / lufa.c
1 /*
2  * Copyright 2012 Jun Wako <wakojun@gmail.com>
3  * This file is based on:
4  *     LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
5  *     LUFA-120219/Demos/Device/Lowlevel/GenericHID
6  */
7
8 /*
9              LUFA Library
10      Copyright (C) Dean Camera, 2012.
11
12   dean [at] fourwalledcubicle [dot] com
13            www.lufa-lib.org
14 */
15
16 /*
17   Copyright 2012  Dean Camera (dean [at] fourwalledcubicle [dot] com)
18   Copyright 2010  Denver Gingerich (denver [at] ossguy [dot] com)
19
20   Permission to use, copy, modify, distribute, and sell this
21   software and its documentation for any purpose is hereby granted
22   without fee, provided that the above copyright notice appear in
23   all copies and that both that the copyright notice and this
24   permission notice and warranty disclaimer appear in supporting
25   documentation, and that the name of the author not be used in
26   advertising or publicity pertaining to distribution of the
27   software without specific, written prior permission.
28
29   The author disclaim all warranties with regard to this
30   software, including all implied warranties of merchantability
31   and fitness.  In no event shall the author be liable for any
32   special, indirect or consequential damages or any damages
33   whatsoever resulting from loss of use, data or profits, whether
34   in an action of contract, negligence or other tortious action,
35   arising out of or in connection with the use or performance of
36   this software.
37 */
38
39 #include "report.h"
40 #include "host.h"
41 #include "host_driver.h"
42 #include "keyboard.h"
43 #include "action.h"
44 #include "led.h"
45 #include "sendchar.h"
46 #include "debug.h"
47 #ifdef SLEEP_LED_ENABLE
48 #include "sleep_led.h"
49 #endif
50 #include "suspend.h"
51
52 #include "usb_descriptor.h"
53 #include "lufa.h"
54 #include "quantum.h"
55 #include <util/atomic.h>
56 #include "outputselect.h"
57
58 #ifdef NKRO_ENABLE
59   #include "keycode_config.h"
60
61   extern keymap_config_t keymap_config;
62 #endif
63
64
65 #ifdef AUDIO_ENABLE
66     #include <audio.h>
67 #endif
68
69 #ifdef BLUETOOTH_ENABLE
70   #ifdef MODULE_ADAFRUIT_BLE
71     #include "adafruit_ble.h"
72   #else
73     #include "bluetooth.h"
74   #endif
75 #endif
76
77 #ifdef VIRTSER_ENABLE
78     #include "virtser.h"
79 #endif
80
81 #if (defined(RGB_MIDI) | defined(RGBLIGHT_ANIMATIONS)) & defined(RGBLIGHT_ENABLE)
82     #include "rgblight.h"
83 #endif
84
85 #ifdef MIDI_ENABLE
86   #include "qmk_midi.h"
87 #endif
88
89 #ifdef RAW_ENABLE
90         #include "raw_hid.h"
91 #endif
92
93 uint8_t keyboard_idle = 0;
94 /* 0: Boot Protocol, 1: Report Protocol(default) */
95 uint8_t keyboard_protocol = 1;
96 static uint8_t keyboard_led_stats = 0;
97
98 static report_keyboard_t keyboard_report_sent;
99
100 /* Host driver */
101 static uint8_t keyboard_leds(void);
102 static void send_keyboard(report_keyboard_t *report);
103 static void send_mouse(report_mouse_t *report);
104 static void send_system(uint16_t data);
105 static void send_consumer(uint16_t data);
106 host_driver_t lufa_driver = {
107     keyboard_leds,
108     send_keyboard,
109     send_mouse,
110     send_system,
111     send_consumer,
112 };
113
114 #ifdef VIRTSER_ENABLE
115 USB_ClassInfo_CDC_Device_t cdc_device =
116 {
117   .Config =
118   {
119     .ControlInterfaceNumber = CCI_INTERFACE,
120     .DataINEndpoint         =
121     {
122       .Address          = CDC_IN_EPADDR,
123       .Size             = CDC_EPSIZE,
124       .Banks            = 1,
125     },
126     .DataOUTEndpoint        =
127     {
128       .Address          = CDC_OUT_EPADDR,
129       .Size             = CDC_EPSIZE,
130       .Banks            = 1,
131     },
132     .NotificationEndpoint   =
133     {
134       .Address          = CDC_NOTIFICATION_EPADDR,
135       .Size             = CDC_NOTIFICATION_EPSIZE,
136       .Banks            = 1,
137     },
138   },
139 };
140 #endif
141
142 #ifdef RAW_ENABLE
143
144 void raw_hid_send( uint8_t *data, uint8_t length )
145 {
146         // TODO: implement variable size packet
147         if ( length != RAW_EPSIZE )
148         {
149                 return;
150         }
151
152         if (USB_DeviceState != DEVICE_STATE_Configured)
153         {
154                 return;
155         }
156
157         // TODO: decide if we allow calls to raw_hid_send() in the middle
158         // of other endpoint usage.
159         uint8_t ep = Endpoint_GetCurrentEndpoint();
160
161         Endpoint_SelectEndpoint(RAW_IN_EPNUM);
162
163         // Check to see if the host is ready to accept another packet
164         if (Endpoint_IsINReady())
165         {
166                 // Write data
167                 Endpoint_Write_Stream_LE(data, RAW_EPSIZE, NULL);
168                 // Finalize the stream transfer to send the last packet
169                 Endpoint_ClearIN();
170         }
171
172         Endpoint_SelectEndpoint(ep);
173 }
174
175 __attribute__ ((weak))
176 void raw_hid_receive( uint8_t *data, uint8_t length )
177 {
178         // Users should #include "raw_hid.h" in their own code
179         // and implement this function there. Leave this as weak linkage
180         // so users can opt to not handle data coming in.
181 }
182
183 static void raw_hid_task(void)
184 {
185         // Create a temporary buffer to hold the read in data from the host
186         uint8_t data[RAW_EPSIZE];
187         bool data_read = false;
188
189         // Device must be connected and configured for the task to run
190         if (USB_DeviceState != DEVICE_STATE_Configured)
191         return;
192
193         Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
194
195         // Check to see if a packet has been sent from the host
196         if (Endpoint_IsOUTReceived())
197         {
198                 // Check to see if the packet contains data
199                 if (Endpoint_IsReadWriteAllowed())
200                 {
201                         /* Read data */
202                         Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
203                         data_read = true;
204                 }
205
206                 // Finalize the stream transfer to receive the last packet
207                 Endpoint_ClearOUT();
208
209                 if ( data_read )
210                 {
211                         raw_hid_receive( data, sizeof(data) );
212                 }
213         }
214 }
215 #endif
216
217 /*******************************************************************************
218  * Console
219  ******************************************************************************/
220 #ifdef CONSOLE_ENABLE
221 static void Console_Task(void)
222 {
223     /* Device must be connected and configured for the task to run */
224     if (USB_DeviceState != DEVICE_STATE_Configured)
225         return;
226
227     uint8_t ep = Endpoint_GetCurrentEndpoint();
228
229 #if 0
230     // TODO: impl receivechar()/recvchar()
231     Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
232
233     /* Check to see if a packet has been sent from the host */
234     if (Endpoint_IsOUTReceived())
235     {
236         /* Check to see if the packet contains data */
237         if (Endpoint_IsReadWriteAllowed())
238         {
239             /* Create a temporary buffer to hold the read in report from the host */
240             uint8_t ConsoleData[CONSOLE_EPSIZE];
241
242             /* Read Console Report Data */
243             Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
244
245             /* Process Console Report Data */
246             //ProcessConsoleHIDReport(ConsoleData);
247         }
248
249         /* Finalize the stream transfer to send the last packet */
250         Endpoint_ClearOUT();
251     }
252 #endif
253
254     /* IN packet */
255     Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
256     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
257         Endpoint_SelectEndpoint(ep);
258         return;
259     }
260
261     // fill empty bank
262     while (Endpoint_IsReadWriteAllowed())
263         Endpoint_Write_8(0);
264
265     // flash senchar packet
266     if (Endpoint_IsINReady()) {
267         Endpoint_ClearIN();
268     }
269
270     Endpoint_SelectEndpoint(ep);
271 }
272 #endif
273
274
275 /*******************************************************************************
276  * USB Events
277  ******************************************************************************/
278 /*
279  * Event Order of Plug in:
280  * 0) EVENT_USB_Device_Connect
281  * 1) EVENT_USB_Device_Suspend
282  * 2) EVENT_USB_Device_Reset
283  * 3) EVENT_USB_Device_Wake
284 */
285 void EVENT_USB_Device_Connect(void)
286 {
287     print("[C]");
288     /* For battery powered device */
289     if (!USB_IsInitialized) {
290         USB_Disable();
291         USB_Init();
292         USB_Device_EnableSOFEvents();
293     }
294 }
295
296 void EVENT_USB_Device_Disconnect(void)
297 {
298     print("[D]");
299     /* For battery powered device */
300     USB_IsInitialized = false;
301 /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
302     if (USB_IsInitialized) {
303         USB_Disable();  // Disable all interrupts
304         USB_Controller_Enable();
305         USB_INT_Enable(USB_INT_VBUSTI);
306     }
307 */
308 }
309
310 void EVENT_USB_Device_Reset(void)
311 {
312     print("[R]");
313 }
314
315 void EVENT_USB_Device_Suspend()
316 {
317     print("[S]");
318 #ifdef SLEEP_LED_ENABLE
319     sleep_led_enable();
320 #endif
321 }
322
323 void EVENT_USB_Device_WakeUp()
324 {
325     print("[W]");
326     suspend_wakeup_init();
327
328 #ifdef SLEEP_LED_ENABLE
329     sleep_led_disable();
330     // NOTE: converters may not accept this
331     led_set(host_keyboard_leds());
332 #endif
333 }
334
335
336
337 #ifdef CONSOLE_ENABLE
338 static bool console_flush = false;
339 #define CONSOLE_FLUSH_SET(b)   do { \
340   ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {\
341     console_flush = b; \
342   } \
343 } while (0)
344
345 // called every 1ms
346 void EVENT_USB_Device_StartOfFrame(void)
347 {
348     static uint8_t count;
349     if (++count % 50) return;
350     count = 0;
351
352     if (!console_flush) return;
353     Console_Task();
354     console_flush = false;
355 }
356
357 #endif
358
359 /** Event handler for the USB_ConfigurationChanged event.
360  * This is fired when the host sets the current configuration of the USB device after enumeration.
361  *
362  * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
363  * it is safe to use singl bank for all endpoints.
364  */
365 void EVENT_USB_Device_ConfigurationChanged(void)
366 {
367     bool ConfigSuccess = true;
368
369     /* Setup Keyboard HID Report Endpoints */
370     ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
371                                      KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
372
373 #ifdef MOUSE_ENABLE
374     /* Setup Mouse HID Report Endpoint */
375     ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
376                                      MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
377 #endif
378
379 #ifdef EXTRAKEY_ENABLE
380     /* Setup Extra HID Report Endpoint */
381     ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
382                                      EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
383 #endif
384
385 #ifdef RAW_ENABLE
386     /* Setup Raw HID Report Endpoints */
387     ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
388                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
389     ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
390                                                                          RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
391 #endif
392
393 #ifdef CONSOLE_ENABLE
394     /* Setup Console HID Report Endpoints */
395     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
396                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
397 #if 0
398     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
399                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
400 #endif
401 #endif
402
403 #ifdef NKRO_ENABLE
404     /* Setup NKRO HID Report Endpoints */
405     ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
406                                      NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
407 #endif
408
409 #ifdef MIDI_ENABLE
410     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_IN_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
411     ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_OUT_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
412 #endif
413
414 #ifdef VIRTSER_ENABLE
415     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, ENDPOINT_BANK_SINGLE);
416     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_OUT_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
417     ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_IN_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
418 #endif
419 }
420
421 /*
422 Appendix G: HID Request Support Requirements
423
424 The following table enumerates the requests that need to be supported by various types of HID class devices.
425
426 Device type     GetReport   SetReport   GetIdle     SetIdle     GetProtocol SetProtocol
427 ------------------------------------------------------------------------------------------
428 Boot Mouse      Required    Optional    Optional    Optional    Required    Required
429 Non-Boot Mouse  Required    Optional    Optional    Optional    Optional    Optional
430 Boot Keyboard   Required    Optional    Required    Required    Required    Required
431 Non-Boot Keybrd Required    Optional    Required    Required    Optional    Optional
432 Other Device    Required    Optional    Optional    Optional    Optional    Optional
433 */
434 /** Event handler for the USB_ControlRequest event.
435  *  This is fired before passing along unhandled control requests to the library for processing internally.
436  */
437 void EVENT_USB_Device_ControlRequest(void)
438 {
439     uint8_t* ReportData = NULL;
440     uint8_t  ReportSize = 0;
441
442     /* Handle HID Class specific requests */
443     switch (USB_ControlRequest.bRequest)
444     {
445         case HID_REQ_GetReport:
446             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
447             {
448                 Endpoint_ClearSETUP();
449
450                 // Interface
451                 switch (USB_ControlRequest.wIndex) {
452                 case KEYBOARD_INTERFACE:
453                     // TODO: test/check
454                     ReportData = (uint8_t*)&keyboard_report_sent;
455                     ReportSize = sizeof(keyboard_report_sent);
456                     break;
457                 }
458
459                 /* Write the report data to the control endpoint */
460                 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
461                 Endpoint_ClearOUT();
462             }
463
464             break;
465         case HID_REQ_SetReport:
466             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
467             {
468
469                 // Interface
470                 switch (USB_ControlRequest.wIndex) {
471                 case KEYBOARD_INTERFACE:
472 #ifdef NKRO_ENABLE
473                 case NKRO_INTERFACE:
474 #endif
475                     Endpoint_ClearSETUP();
476
477                     while (!(Endpoint_IsOUTReceived())) {
478                         if (USB_DeviceState == DEVICE_STATE_Unattached)
479                           return;
480                     }
481                     keyboard_led_stats = Endpoint_Read_8();
482
483                     Endpoint_ClearOUT();
484                     Endpoint_ClearStatusStage();
485                     break;
486                 }
487
488             }
489
490             break;
491
492         case HID_REQ_GetProtocol:
493             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
494             {
495                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
496                     Endpoint_ClearSETUP();
497                     while (!(Endpoint_IsINReady()));
498                     Endpoint_Write_8(keyboard_protocol);
499                     Endpoint_ClearIN();
500                     Endpoint_ClearStatusStage();
501                 }
502             }
503
504             break;
505         case HID_REQ_SetProtocol:
506             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
507             {
508                 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
509                     Endpoint_ClearSETUP();
510                     Endpoint_ClearStatusStage();
511
512                     keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
513                     clear_keyboard();
514                 }
515             }
516
517             break;
518         case HID_REQ_SetIdle:
519             if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
520             {
521                 Endpoint_ClearSETUP();
522                 Endpoint_ClearStatusStage();
523
524                 keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
525             }
526
527             break;
528         case HID_REQ_GetIdle:
529             if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
530             {
531                 Endpoint_ClearSETUP();
532                 while (!(Endpoint_IsINReady()));
533                 Endpoint_Write_8(keyboard_idle);
534                 Endpoint_ClearIN();
535                 Endpoint_ClearStatusStage();
536             }
537
538             break;
539     }
540
541 #ifdef VIRTSER_ENABLE
542     CDC_Device_ProcessControlRequest(&cdc_device);
543 #endif
544 }
545
546 /*******************************************************************************
547  * Host driver
548  ******************************************************************************/
549 static uint8_t keyboard_leds(void)
550 {
551     return keyboard_led_stats;
552 }
553
554 static void send_keyboard(report_keyboard_t *report)
555 {
556     uint8_t timeout = 255;
557     uint8_t where = where_to_send();
558
559 #ifdef BLUETOOTH_ENABLE
560   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
561     #ifdef MODULE_ADAFRUIT_BLE
562       adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
563     #elif MODULE_RN42
564        bluefruit_serial_send(0xFD);
565        bluefruit_serial_send(0x09);
566        bluefruit_serial_send(0x01);
567        for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
568          bluefruit_serial_send(report->raw[i]);
569        }
570     #else
571       bluefruit_serial_send(0xFD);
572       for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
573         bluefruit_serial_send(report->raw[i]);
574       }
575     #endif
576   }
577 #endif
578
579     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
580       return;
581     }
582
583     /* Select the Keyboard Report Endpoint */
584 #ifdef NKRO_ENABLE
585     if (keyboard_protocol && keymap_config.nkro) {
586         /* Report protocol - NKRO */
587         Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
588
589         /* Check if write ready for a polling interval around 1ms */
590         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
591         if (!Endpoint_IsReadWriteAllowed()) return;
592
593         /* Write Keyboard Report Data */
594         Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
595     }
596     else
597 #endif
598     {
599         /* Boot protocol */
600         Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
601
602         /* Check if write ready for a polling interval around 10ms */
603         while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
604         if (!Endpoint_IsReadWriteAllowed()) return;
605
606         /* Write Keyboard Report Data */
607         Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
608     }
609
610     /* Finalize the stream transfer to send the last packet */
611     Endpoint_ClearIN();
612
613     keyboard_report_sent = *report;
614 }
615
616 static void send_mouse(report_mouse_t *report)
617 {
618 #ifdef MOUSE_ENABLE
619     uint8_t timeout = 255;
620     uint8_t where = where_to_send();
621
622 #ifdef BLUETOOTH_ENABLE
623   if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
624     #ifdef MODULE_ADAFRUIT_BLE
625       // FIXME: mouse buttons
626       adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
627     #else
628       bluefruit_serial_send(0xFD);
629       bluefruit_serial_send(0x00);
630       bluefruit_serial_send(0x03);
631       bluefruit_serial_send(report->buttons);
632       bluefruit_serial_send(report->x);
633       bluefruit_serial_send(report->y);
634       bluefruit_serial_send(report->v); // should try sending the wheel v here
635       bluefruit_serial_send(report->h); // should try sending the wheel h here
636       bluefruit_serial_send(0x00);
637     #endif
638   }
639 #endif
640
641     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
642       return;
643     }
644
645     /* Select the Mouse Report Endpoint */
646     Endpoint_SelectEndpoint(MOUSE_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 Mouse Report Data */
653     Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
654
655     /* Finalize the stream transfer to send the last packet */
656     Endpoint_ClearIN();
657 #endif
658 }
659
660 static void send_system(uint16_t data)
661 {
662     uint8_t timeout = 255;
663
664     if (USB_DeviceState != DEVICE_STATE_Configured)
665         return;
666
667     report_extra_t r = {
668         .report_id = REPORT_ID_SYSTEM,
669         .usage = data - SYSTEM_POWER_DOWN + 1
670     };
671     Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
672
673     /* Check if write ready for a polling interval around 10ms */
674     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
675     if (!Endpoint_IsReadWriteAllowed()) return;
676
677     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
678     Endpoint_ClearIN();
679 }
680
681 static void send_consumer(uint16_t data)
682 {
683     uint8_t timeout = 255;
684     uint8_t where = where_to_send();
685
686 #ifdef BLUETOOTH_ENABLE
687     if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
688       #ifdef MODULE_ADAFRUIT_BLE
689         adafruit_ble_send_consumer_key(data, 0);
690       #elif MODULE_RN42
691         static uint16_t last_data = 0;
692         if (data == last_data) return;
693         last_data = data;
694         uint16_t bitmap = CONSUMER2RN42(data);
695         bluefruit_serial_send(0xFD);
696         bluefruit_serial_send(0x03);
697         bluefruit_serial_send(0x03);
698         bluefruit_serial_send(bitmap&0xFF);
699         bluefruit_serial_send((bitmap>>8)&0xFF);
700       #else
701         static uint16_t last_data = 0;
702         if (data == last_data) return;
703         last_data = data;
704         uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
705         bluefruit_serial_send(0xFD);
706         bluefruit_serial_send(0x00);
707         bluefruit_serial_send(0x02);
708         bluefruit_serial_send((bitmap>>8)&0xFF);
709         bluefruit_serial_send(bitmap&0xFF);
710         bluefruit_serial_send(0x00);
711         bluefruit_serial_send(0x00);
712         bluefruit_serial_send(0x00);
713         bluefruit_serial_send(0x00);
714       #endif
715     }
716 #endif
717
718     if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
719       return;
720     }
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 USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
811 {
812   .Config =
813   {
814     .StreamingInterfaceNumber = AS_INTERFACE,
815     .DataINEndpoint           =
816     {
817       .Address          = MIDI_STREAM_IN_EPADDR,
818       .Size             = MIDI_STREAM_EPSIZE,
819       .Banks            = 1,
820     },
821     .DataOUTEndpoint          =
822     {
823       .Address          = MIDI_STREAM_OUT_EPADDR,
824       .Size             = MIDI_STREAM_EPSIZE,
825       .Banks            = 1,
826     },
827   },
828 };
829
830 void send_midi_packet(MIDI_EventPacket_t* event) {
831   MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
832 }
833
834 bool recv_midi_packet(MIDI_EventPacket_t* const event) {
835   return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
836 }
837
838 #endif
839
840 /*******************************************************************************
841  * VIRTUAL SERIAL
842  ******************************************************************************/
843
844 #ifdef VIRTSER_ENABLE
845 void virtser_init(void)
846 {
847   cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
848   CDC_Device_SendControlLineStateChange(&cdc_device);
849 }
850
851 void virtser_recv(uint8_t c) __attribute__ ((weak));
852 void virtser_recv(uint8_t c)
853 {
854   // Ignore by default
855 }
856
857 void virtser_task(void)
858 {
859   uint16_t count = CDC_Device_BytesReceived(&cdc_device);
860   uint8_t ch;
861   if (count)
862   {
863     ch = CDC_Device_ReceiveByte(&cdc_device);
864     virtser_recv(ch);
865   }
866 }
867 void virtser_send(const uint8_t byte)
868 {
869   uint8_t timeout = 255;
870   uint8_t ep = Endpoint_GetCurrentEndpoint();
871
872   if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
873   {
874     /* IN packet */
875     Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
876
877     if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
878         Endpoint_SelectEndpoint(ep);
879         return;
880     }
881
882     while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
883
884     Endpoint_Write_8(byte);
885     CDC_Device_Flush(&cdc_device);
886
887     if (Endpoint_IsINReady()) {
888       Endpoint_ClearIN();
889     }
890
891     Endpoint_SelectEndpoint(ep);
892   }
893 }
894 #endif
895
896 /*******************************************************************************
897  * main
898  ******************************************************************************/
899 static void setup_mcu(void)
900 {
901     /* Disable watchdog if enabled by bootloader/fuses */
902     MCUSR &= ~(1 << WDRF);
903     wdt_disable();
904
905     /* Disable clock division */
906     // clock_prescale_set(clock_div_1);
907
908     CLKPR = (1 << CLKPCE);
909     CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
910 }
911
912 static void setup_usb(void)
913 {
914     // Leonardo needs. Without this USB device is not recognized.
915     USB_Disable();
916
917     USB_Init();
918
919     // for Console_Task
920     USB_Device_EnableSOFEvents();
921     print_set_sendchar(sendchar);
922 }
923
924 int main(void)  __attribute__ ((weak));
925 int main(void)
926 {
927 #ifdef MIDI_ENABLE
928     setup_midi();
929 #endif
930
931     setup_mcu();
932     keyboard_setup();
933     setup_usb();
934     sei();
935
936 #if defined(MODULE_ADAFRUIT_EZKEY) || defined(MODULE_RN42)
937     serial_init();
938 #endif
939
940     /* wait for USB startup & debug output */
941
942 #ifdef WAIT_FOR_USB
943     while (USB_DeviceState != DEVICE_STATE_Configured) {
944     #if defined(INTERRUPT_CONTROL_ENDPOINT)
945             ;
946     #else
947             USB_USBTask();
948     #endif
949     }
950     print("USB configured.\n");
951 #else
952     USB_USBTask();
953 #endif
954     /* init modules */
955     keyboard_init();
956     host_set_driver(&lufa_driver);
957 #ifdef SLEEP_LED_ENABLE
958     sleep_led_init();
959 #endif
960
961 #ifdef VIRTSER_ENABLE
962     virtser_init();
963 #endif
964
965     print("Keyboard start.\n");
966     while (1) {
967         #if !defined(NO_USB_STARTUP_CHECK)
968         while (USB_DeviceState == DEVICE_STATE_Suspended) {
969             print("[s]");
970             suspend_power_down();
971             if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
972                     USB_Device_SendRemoteWakeup();
973             }
974         }
975         #endif
976
977         keyboard_task();
978
979 #ifdef MIDI_ENABLE
980         MIDI_Device_USBTask(&USB_MIDI_Interface);
981 #endif
982
983 #if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
984         rgblight_task();
985 #endif
986
987 #ifdef MODULE_ADAFRUIT_BLE
988         adafruit_ble_task();
989 #endif
990
991 #ifdef VIRTSER_ENABLE
992         virtser_task();
993         CDC_Device_USBTask(&cdc_device);
994 #endif
995
996 #ifdef RAW_ENABLE
997         raw_hid_task();
998 #endif
999
1000 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
1001         USB_USBTask();
1002 #endif
1003
1004     }
1005 }
1006
1007 uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
1008                                     const uint16_t wIndex,
1009                                     const void** const DescriptorAddress)
1010 {
1011   return get_usb_descriptor(wValue, wIndex, DescriptorAddress);
1012 }
1013