lufa.c 32 KB

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