lufa.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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 "usb_descriptor.h"
  46. #include "lufa.h"
  47. #include "quantum.h"
  48. #include <util/atomic.h>
  49. #include "outputselect.h"
  50. #include "rgblight_reconfig.h"
  51. #ifdef NKRO_ENABLE
  52. #include "keycode_config.h"
  53. extern keymap_config_t keymap_config;
  54. #endif
  55. #ifdef AUDIO_ENABLE
  56. #include <audio.h>
  57. #endif
  58. #ifdef BLUETOOTH_ENABLE
  59. #ifdef MODULE_ADAFRUIT_BLE
  60. #include "adafruit_ble.h"
  61. #else
  62. #include "bluetooth.h"
  63. #endif
  64. #endif
  65. #ifdef VIRTSER_ENABLE
  66. #include "virtser.h"
  67. #endif
  68. #if (defined(RGB_MIDI) | defined(RGBLIGHT_ANIMATIONS)) & defined(RGBLIGHT_ENABLE)
  69. #include "rgblight.h"
  70. #endif
  71. #ifdef MIDI_ENABLE
  72. #include "qmk_midi.h"
  73. #endif
  74. #ifdef RAW_ENABLE
  75. #include "raw_hid.h"
  76. #endif
  77. uint8_t keyboard_idle = 0;
  78. /* 0: Boot Protocol, 1: Report Protocol(default) */
  79. uint8_t keyboard_protocol = 1;
  80. static uint8_t keyboard_led_stats = 0;
  81. static report_keyboard_t keyboard_report_sent;
  82. /* Host driver */
  83. static uint8_t keyboard_leds(void);
  84. static void send_keyboard(report_keyboard_t *report);
  85. static void send_mouse(report_mouse_t *report);
  86. static void send_system(uint16_t data);
  87. static void send_consumer(uint16_t data);
  88. host_driver_t lufa_driver = {
  89. keyboard_leds,
  90. send_keyboard,
  91. send_mouse,
  92. send_system,
  93. send_consumer,
  94. };
  95. #ifdef VIRTSER_ENABLE
  96. USB_ClassInfo_CDC_Device_t cdc_device =
  97. {
  98. .Config =
  99. {
  100. .ControlInterfaceNumber = CCI_INTERFACE,
  101. .DataINEndpoint =
  102. {
  103. .Address = CDC_IN_EPADDR,
  104. .Size = CDC_EPSIZE,
  105. .Banks = 1,
  106. },
  107. .DataOUTEndpoint =
  108. {
  109. .Address = CDC_OUT_EPADDR,
  110. .Size = CDC_EPSIZE,
  111. .Banks = 1,
  112. },
  113. .NotificationEndpoint =
  114. {
  115. .Address = CDC_NOTIFICATION_EPADDR,
  116. .Size = CDC_NOTIFICATION_EPSIZE,
  117. .Banks = 1,
  118. },
  119. },
  120. };
  121. #endif
  122. #ifdef RAW_ENABLE
  123. /** \brief Raw HID Send
  124. *
  125. * FIXME: Needs doc
  126. */
  127. void raw_hid_send( uint8_t *data, uint8_t length )
  128. {
  129. // TODO: implement variable size packet
  130. if ( length != RAW_EPSIZE )
  131. {
  132. return;
  133. }
  134. if (USB_DeviceState != DEVICE_STATE_Configured)
  135. {
  136. return;
  137. }
  138. // TODO: decide if we allow calls to raw_hid_send() in the middle
  139. // of other endpoint usage.
  140. uint8_t ep = Endpoint_GetCurrentEndpoint();
  141. Endpoint_SelectEndpoint(RAW_IN_EPNUM);
  142. // Check to see if the host is ready to accept another packet
  143. if (Endpoint_IsINReady())
  144. {
  145. // Write data
  146. Endpoint_Write_Stream_LE(data, RAW_EPSIZE, NULL);
  147. // Finalize the stream transfer to send the last packet
  148. Endpoint_ClearIN();
  149. }
  150. Endpoint_SelectEndpoint(ep);
  151. }
  152. /** \brief Raw HID Receive
  153. *
  154. * FIXME: Needs doc
  155. */
  156. __attribute__ ((weak))
  157. void raw_hid_receive( uint8_t *data, uint8_t length )
  158. {
  159. // Users should #include "raw_hid.h" in their own code
  160. // and implement this function there. Leave this as weak linkage
  161. // so users can opt to not handle data coming in.
  162. }
  163. /** \brief Raw HID Task
  164. *
  165. * FIXME: Needs doc
  166. */
  167. static void raw_hid_task(void)
  168. {
  169. // Create a temporary buffer to hold the read in data from the host
  170. uint8_t data[RAW_EPSIZE];
  171. bool data_read = false;
  172. // Device must be connected and configured for the task to run
  173. if (USB_DeviceState != DEVICE_STATE_Configured)
  174. return;
  175. Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
  176. // Check to see if a packet has been sent from the host
  177. if (Endpoint_IsOUTReceived())
  178. {
  179. // Check to see if the packet contains data
  180. if (Endpoint_IsReadWriteAllowed())
  181. {
  182. /* Read data */
  183. Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
  184. data_read = true;
  185. }
  186. // Finalize the stream transfer to receive the last packet
  187. Endpoint_ClearOUT();
  188. if ( data_read )
  189. {
  190. raw_hid_receive( data, sizeof(data) );
  191. }
  192. }
  193. }
  194. #endif
  195. /*******************************************************************************
  196. * Console
  197. ******************************************************************************/
  198. #ifdef CONSOLE_ENABLE
  199. /** \brief Console Task
  200. *
  201. * FIXME: Needs doc
  202. */
  203. static void Console_Task(void)
  204. {
  205. /* Device must be connected and configured for the task to run */
  206. if (USB_DeviceState != DEVICE_STATE_Configured)
  207. return;
  208. uint8_t ep = Endpoint_GetCurrentEndpoint();
  209. #if 0
  210. // TODO: impl receivechar()/recvchar()
  211. Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
  212. /* Check to see if a packet has been sent from the host */
  213. if (Endpoint_IsOUTReceived())
  214. {
  215. /* Check to see if the packet contains data */
  216. if (Endpoint_IsReadWriteAllowed())
  217. {
  218. /* Create a temporary buffer to hold the read in report from the host */
  219. uint8_t ConsoleData[CONSOLE_EPSIZE];
  220. /* Read Console Report Data */
  221. Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
  222. /* Process Console Report Data */
  223. //ProcessConsoleHIDReport(ConsoleData);
  224. }
  225. /* Finalize the stream transfer to send the last packet */
  226. Endpoint_ClearOUT();
  227. }
  228. #endif
  229. /* IN packet */
  230. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  231. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  232. Endpoint_SelectEndpoint(ep);
  233. return;
  234. }
  235. // fill empty bank
  236. while (Endpoint_IsReadWriteAllowed())
  237. Endpoint_Write_8(0);
  238. // flash senchar packet
  239. if (Endpoint_IsINReady()) {
  240. Endpoint_ClearIN();
  241. }
  242. Endpoint_SelectEndpoint(ep);
  243. }
  244. #endif
  245. /*******************************************************************************
  246. * USB Events
  247. ******************************************************************************/
  248. /*
  249. * Event Order of Plug in:
  250. * 0) EVENT_USB_Device_Connect
  251. * 1) EVENT_USB_Device_Suspend
  252. * 2) EVENT_USB_Device_Reset
  253. * 3) EVENT_USB_Device_Wake
  254. */
  255. /** \brief Event USB Device Connect
  256. *
  257. * FIXME: Needs doc
  258. */
  259. void EVENT_USB_Device_Connect(void)
  260. {
  261. print("[C]");
  262. /* For battery powered device */
  263. if (!USB_IsInitialized) {
  264. USB_Disable();
  265. USB_Init();
  266. USB_Device_EnableSOFEvents();
  267. }
  268. }
  269. /** \brief Event USB Device Connect
  270. *
  271. * FIXME: Needs doc
  272. */
  273. void EVENT_USB_Device_Disconnect(void)
  274. {
  275. print("[D]");
  276. /* For battery powered device */
  277. USB_IsInitialized = false;
  278. /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
  279. if (USB_IsInitialized) {
  280. USB_Disable(); // Disable all interrupts
  281. USB_Controller_Enable();
  282. USB_INT_Enable(USB_INT_VBUSTI);
  283. }
  284. */
  285. }
  286. /** \brief Event USB Device Connect
  287. *
  288. * FIXME: Needs doc
  289. */
  290. void EVENT_USB_Device_Reset(void)
  291. {
  292. print("[R]");
  293. }
  294. /** \brief Event USB Device Connect
  295. *
  296. * FIXME: Needs doc
  297. */
  298. void EVENT_USB_Device_Suspend()
  299. {
  300. print("[S]");
  301. #ifdef SLEEP_LED_ENABLE
  302. sleep_led_enable();
  303. #endif
  304. }
  305. /** \brief Event USB Device Connect
  306. *
  307. * FIXME: Needs doc
  308. */
  309. void EVENT_USB_Device_WakeUp()
  310. {
  311. print("[W]");
  312. suspend_wakeup_init();
  313. #ifdef SLEEP_LED_ENABLE
  314. sleep_led_disable();
  315. // NOTE: converters may not accept this
  316. led_set(host_keyboard_leds());
  317. #endif
  318. }
  319. #ifdef CONSOLE_ENABLE
  320. static bool console_flush = false;
  321. #define CONSOLE_FLUSH_SET(b) do { \
  322. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {\
  323. console_flush = b; \
  324. } \
  325. } while (0)
  326. /** \brief Event USB Device Start Of Frame
  327. *
  328. * FIXME: Needs doc
  329. * called every 1ms
  330. */
  331. void EVENT_USB_Device_StartOfFrame(void)
  332. {
  333. static uint8_t count;
  334. if (++count % 50) return;
  335. count = 0;
  336. if (!console_flush) return;
  337. Console_Task();
  338. console_flush = false;
  339. }
  340. #endif
  341. /** \brief Event handler for the USB_ConfigurationChanged event.
  342. *
  343. * This is fired when the host sets the current configuration of the USB device after enumeration.
  344. *
  345. * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
  346. * it is safe to use single bank for all endpoints.
  347. */
  348. void EVENT_USB_Device_ConfigurationChanged(void)
  349. {
  350. bool ConfigSuccess = true;
  351. /* Setup Keyboard HID Report Endpoints */
  352. ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  353. KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
  354. #ifdef MOUSE_ENABLE
  355. /* Setup Mouse HID Report Endpoint */
  356. ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  357. MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
  358. #endif
  359. #ifdef EXTRAKEY_ENABLE
  360. /* Setup Extra HID Report Endpoint */
  361. ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  362. EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
  363. #endif
  364. #ifdef RAW_ENABLE
  365. /* Setup Raw HID Report Endpoints */
  366. ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  367. RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
  368. ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
  369. RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
  370. #endif
  371. #ifdef CONSOLE_ENABLE
  372. /* Setup Console HID Report Endpoints */
  373. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  374. CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
  375. #if 0
  376. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
  377. CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
  378. #endif
  379. #endif
  380. #ifdef NKRO_ENABLE
  381. /* Setup NKRO HID Report Endpoints */
  382. ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  383. NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
  384. #endif
  385. #ifdef MIDI_ENABLE
  386. ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_IN_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
  387. ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_OUT_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
  388. #endif
  389. #ifdef VIRTSER_ENABLE
  390. ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, ENDPOINT_BANK_SINGLE);
  391. ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_OUT_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
  392. ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_IN_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
  393. #endif
  394. }
  395. /* FIXME: Expose this table in the docs somehow
  396. Appendix G: HID Request Support Requirements
  397. The following table enumerates the requests that need to be supported by various types of HID class devices.
  398. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  399. ------------------------------------------------------------------------------------------
  400. Boot Mouse Required Optional Optional Optional Required Required
  401. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  402. Boot Keyboard Required Optional Required Required Required Required
  403. Non-Boot Keybrd Required Optional Required Required Optional Optional
  404. Other Device Required Optional Optional Optional Optional Optional
  405. */
  406. /** \brief Event handler for the USB_ControlRequest event.
  407. *
  408. * This is fired before passing along unhandled control requests to the library for processing internally.
  409. */
  410. void EVENT_USB_Device_ControlRequest(void)
  411. {
  412. uint8_t* ReportData = NULL;
  413. uint8_t ReportSize = 0;
  414. /* Handle HID Class specific requests */
  415. switch (USB_ControlRequest.bRequest)
  416. {
  417. case HID_REQ_GetReport:
  418. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  419. {
  420. Endpoint_ClearSETUP();
  421. // Interface
  422. switch (USB_ControlRequest.wIndex) {
  423. case KEYBOARD_INTERFACE:
  424. // TODO: test/check
  425. ReportData = (uint8_t*)&keyboard_report_sent;
  426. ReportSize = sizeof(keyboard_report_sent);
  427. break;
  428. }
  429. /* Write the report data to the control endpoint */
  430. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  431. Endpoint_ClearOUT();
  432. }
  433. break;
  434. case HID_REQ_SetReport:
  435. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  436. {
  437. // Interface
  438. switch (USB_ControlRequest.wIndex) {
  439. case KEYBOARD_INTERFACE:
  440. #ifdef NKRO_ENABLE
  441. case NKRO_INTERFACE:
  442. #endif
  443. Endpoint_ClearSETUP();
  444. while (!(Endpoint_IsOUTReceived())) {
  445. if (USB_DeviceState == DEVICE_STATE_Unattached)
  446. return;
  447. }
  448. keyboard_led_stats = Endpoint_Read_8();
  449. Endpoint_ClearOUT();
  450. Endpoint_ClearStatusStage();
  451. break;
  452. }
  453. }
  454. break;
  455. case HID_REQ_GetProtocol:
  456. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  457. {
  458. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  459. Endpoint_ClearSETUP();
  460. while (!(Endpoint_IsINReady()));
  461. Endpoint_Write_8(keyboard_protocol);
  462. Endpoint_ClearIN();
  463. Endpoint_ClearStatusStage();
  464. }
  465. }
  466. break;
  467. case HID_REQ_SetProtocol:
  468. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  469. {
  470. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  471. Endpoint_ClearSETUP();
  472. Endpoint_ClearStatusStage();
  473. keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
  474. clear_keyboard();
  475. }
  476. }
  477. break;
  478. case HID_REQ_SetIdle:
  479. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  480. {
  481. Endpoint_ClearSETUP();
  482. Endpoint_ClearStatusStage();
  483. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  484. }
  485. break;
  486. case HID_REQ_GetIdle:
  487. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  488. {
  489. Endpoint_ClearSETUP();
  490. while (!(Endpoint_IsINReady()));
  491. Endpoint_Write_8(keyboard_idle);
  492. Endpoint_ClearIN();
  493. Endpoint_ClearStatusStage();
  494. }
  495. break;
  496. }
  497. #ifdef VIRTSER_ENABLE
  498. CDC_Device_ProcessControlRequest(&cdc_device);
  499. #endif
  500. }
  501. /*******************************************************************************
  502. * Host driver
  503. ******************************************************************************/
  504. /** \brief Keyboard LEDs
  505. *
  506. * FIXME: Needs doc
  507. */
  508. static uint8_t keyboard_leds(void)
  509. {
  510. return keyboard_led_stats;
  511. }
  512. /** \brief Send Keyboard
  513. *
  514. * FIXME: Needs doc
  515. */
  516. static void send_keyboard(report_keyboard_t *report)
  517. {
  518. uint8_t timeout = 255;
  519. uint8_t where = where_to_send();
  520. #ifdef BLUETOOTH_ENABLE
  521. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  522. #ifdef MODULE_ADAFRUIT_BLE
  523. adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
  524. #elif MODULE_RN42
  525. bluefruit_serial_send(0xFD);
  526. bluefruit_serial_send(0x09);
  527. bluefruit_serial_send(0x01);
  528. for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
  529. bluefruit_serial_send(report->raw[i]);
  530. }
  531. #else
  532. bluefruit_serial_send(0xFD);
  533. for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
  534. bluefruit_serial_send(report->raw[i]);
  535. }
  536. #endif
  537. }
  538. #endif
  539. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  540. return;
  541. }
  542. /* Select the Keyboard Report Endpoint */
  543. #ifdef NKRO_ENABLE
  544. if (keyboard_protocol && keymap_config.nkro) {
  545. /* Report protocol - NKRO */
  546. Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
  547. /* Check if write ready for a polling interval around 1ms */
  548. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
  549. if (!Endpoint_IsReadWriteAllowed()) return;
  550. /* Write Keyboard Report Data */
  551. Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
  552. }
  553. else
  554. #endif
  555. {
  556. /* Boot protocol */
  557. Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
  558. /* Check if write ready for a polling interval around 10ms */
  559. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  560. if (!Endpoint_IsReadWriteAllowed()) return;
  561. /* Write Keyboard Report Data */
  562. Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
  563. }
  564. /* Finalize the stream transfer to send the last packet */
  565. Endpoint_ClearIN();
  566. keyboard_report_sent = *report;
  567. }
  568. /** \brief Send Mouse
  569. *
  570. * FIXME: Needs doc
  571. */
  572. static void send_mouse(report_mouse_t *report)
  573. {
  574. #ifdef MOUSE_ENABLE
  575. uint8_t timeout = 255;
  576. uint8_t where = where_to_send();
  577. #ifdef BLUETOOTH_ENABLE
  578. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  579. #ifdef MODULE_ADAFRUIT_BLE
  580. // FIXME: mouse buttons
  581. adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
  582. #else
  583. bluefruit_serial_send(0xFD);
  584. bluefruit_serial_send(0x00);
  585. bluefruit_serial_send(0x03);
  586. bluefruit_serial_send(report->buttons);
  587. bluefruit_serial_send(report->x);
  588. bluefruit_serial_send(report->y);
  589. bluefruit_serial_send(report->v); // should try sending the wheel v here
  590. bluefruit_serial_send(report->h); // should try sending the wheel h here
  591. bluefruit_serial_send(0x00);
  592. #endif
  593. }
  594. #endif
  595. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  596. return;
  597. }
  598. /* Select the Mouse Report Endpoint */
  599. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  600. /* Check if write ready for a polling interval around 10ms */
  601. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  602. if (!Endpoint_IsReadWriteAllowed()) return;
  603. /* Write Mouse Report Data */
  604. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  605. /* Finalize the stream transfer to send the last packet */
  606. Endpoint_ClearIN();
  607. #endif
  608. }
  609. /** \brief Send System
  610. *
  611. * FIXME: Needs doc
  612. */
  613. static void send_system(uint16_t data)
  614. {
  615. uint8_t timeout = 255;
  616. if (USB_DeviceState != DEVICE_STATE_Configured)
  617. return;
  618. report_extra_t r = {
  619. .report_id = REPORT_ID_SYSTEM,
  620. .usage = data - SYSTEM_POWER_DOWN + 1
  621. };
  622. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  623. /* Check if write ready for a polling interval around 10ms */
  624. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  625. if (!Endpoint_IsReadWriteAllowed()) return;
  626. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  627. Endpoint_ClearIN();
  628. }
  629. /** \brief Send Consumer
  630. *
  631. * FIXME: Needs doc
  632. */
  633. static void send_consumer(uint16_t data)
  634. {
  635. uint8_t timeout = 255;
  636. uint8_t where = where_to_send();
  637. #ifdef BLUETOOTH_ENABLE
  638. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  639. #ifdef MODULE_ADAFRUIT_BLE
  640. adafruit_ble_send_consumer_key(data, 0);
  641. #elif MODULE_RN42
  642. static uint16_t last_data = 0;
  643. if (data == last_data) return;
  644. last_data = data;
  645. uint16_t bitmap = CONSUMER2RN42(data);
  646. bluefruit_serial_send(0xFD);
  647. bluefruit_serial_send(0x03);
  648. bluefruit_serial_send(0x03);
  649. bluefruit_serial_send(bitmap&0xFF);
  650. bluefruit_serial_send((bitmap>>8)&0xFF);
  651. #else
  652. static uint16_t last_data = 0;
  653. if (data == last_data) return;
  654. last_data = data;
  655. uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
  656. bluefruit_serial_send(0xFD);
  657. bluefruit_serial_send(0x00);
  658. bluefruit_serial_send(0x02);
  659. bluefruit_serial_send((bitmap>>8)&0xFF);
  660. bluefruit_serial_send(bitmap&0xFF);
  661. bluefruit_serial_send(0x00);
  662. bluefruit_serial_send(0x00);
  663. bluefruit_serial_send(0x00);
  664. bluefruit_serial_send(0x00);
  665. #endif
  666. }
  667. #endif
  668. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  669. return;
  670. }
  671. report_extra_t r = {
  672. .report_id = REPORT_ID_CONSUMER,
  673. .usage = data
  674. };
  675. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  676. /* Check if write ready for a polling interval around 10ms */
  677. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  678. if (!Endpoint_IsReadWriteAllowed()) return;
  679. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  680. Endpoint_ClearIN();
  681. }
  682. /*******************************************************************************
  683. * sendchar
  684. ******************************************************************************/
  685. #ifdef CONSOLE_ENABLE
  686. #define SEND_TIMEOUT 5
  687. /** \brief Send Char
  688. *
  689. * FIXME: Needs doc
  690. */
  691. int8_t sendchar(uint8_t c)
  692. {
  693. // Not wait once timeouted.
  694. // Because sendchar() is called so many times, waiting each call causes big lag.
  695. static bool timeouted = false;
  696. // prevents Console_Task() from running during sendchar() runs.
  697. // or char will be lost. These two function is mutually exclusive.
  698. CONSOLE_FLUSH_SET(false);
  699. if (USB_DeviceState != DEVICE_STATE_Configured)
  700. return -1;
  701. uint8_t ep = Endpoint_GetCurrentEndpoint();
  702. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  703. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  704. goto ERROR_EXIT;
  705. }
  706. if (timeouted && !Endpoint_IsReadWriteAllowed()) {
  707. goto ERROR_EXIT;
  708. }
  709. timeouted = false;
  710. uint8_t timeout = SEND_TIMEOUT;
  711. while (!Endpoint_IsReadWriteAllowed()) {
  712. if (USB_DeviceState != DEVICE_STATE_Configured) {
  713. goto ERROR_EXIT;
  714. }
  715. if (Endpoint_IsStalled()) {
  716. goto ERROR_EXIT;
  717. }
  718. if (!(timeout--)) {
  719. timeouted = true;
  720. goto ERROR_EXIT;
  721. }
  722. _delay_ms(1);
  723. }
  724. Endpoint_Write_8(c);
  725. // send when bank is full
  726. if (!Endpoint_IsReadWriteAllowed()) {
  727. while (!(Endpoint_IsINReady()));
  728. Endpoint_ClearIN();
  729. } else {
  730. CONSOLE_FLUSH_SET(true);
  731. }
  732. Endpoint_SelectEndpoint(ep);
  733. return 0;
  734. ERROR_EXIT:
  735. Endpoint_SelectEndpoint(ep);
  736. return -1;
  737. }
  738. #else
  739. int8_t sendchar(uint8_t c)
  740. {
  741. return 0;
  742. }
  743. #endif
  744. /*******************************************************************************
  745. * MIDI
  746. ******************************************************************************/
  747. #ifdef MIDI_ENABLE
  748. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
  749. {
  750. .Config =
  751. {
  752. .StreamingInterfaceNumber = AS_INTERFACE,
  753. .DataINEndpoint =
  754. {
  755. .Address = MIDI_STREAM_IN_EPADDR,
  756. .Size = MIDI_STREAM_EPSIZE,
  757. .Banks = 1,
  758. },
  759. .DataOUTEndpoint =
  760. {
  761. .Address = MIDI_STREAM_OUT_EPADDR,
  762. .Size = MIDI_STREAM_EPSIZE,
  763. .Banks = 1,
  764. },
  765. },
  766. };
  767. void send_midi_packet(MIDI_EventPacket_t* event) {
  768. MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
  769. }
  770. bool recv_midi_packet(MIDI_EventPacket_t* const event) {
  771. return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
  772. }
  773. #endif
  774. /*******************************************************************************
  775. * VIRTUAL SERIAL
  776. ******************************************************************************/
  777. #ifdef VIRTSER_ENABLE
  778. /** \brief Virtual Serial Init
  779. *
  780. * FIXME: Needs doc
  781. */
  782. void virtser_init(void)
  783. {
  784. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
  785. CDC_Device_SendControlLineStateChange(&cdc_device);
  786. }
  787. /** \brief Virtual Serial Receive
  788. *
  789. * FIXME: Needs doc
  790. */
  791. void virtser_recv(uint8_t c) __attribute__ ((weak));
  792. void virtser_recv(uint8_t c)
  793. {
  794. // Ignore by default
  795. }
  796. /** \brief Virtual Serial Task
  797. *
  798. * FIXME: Needs doc
  799. */
  800. void virtser_task(void)
  801. {
  802. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  803. uint8_t ch;
  804. if (count)
  805. {
  806. ch = CDC_Device_ReceiveByte(&cdc_device);
  807. virtser_recv(ch);
  808. }
  809. }
  810. /** \brief Virtual Serial Send
  811. *
  812. * FIXME: Needs doc
  813. */
  814. void virtser_send(const uint8_t byte)
  815. {
  816. uint8_t timeout = 255;
  817. uint8_t ep = Endpoint_GetCurrentEndpoint();
  818. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
  819. {
  820. /* IN packet */
  821. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  822. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  823. Endpoint_SelectEndpoint(ep);
  824. return;
  825. }
  826. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  827. Endpoint_Write_8(byte);
  828. CDC_Device_Flush(&cdc_device);
  829. if (Endpoint_IsINReady()) {
  830. Endpoint_ClearIN();
  831. }
  832. Endpoint_SelectEndpoint(ep);
  833. }
  834. }
  835. #endif
  836. /*******************************************************************************
  837. * main
  838. ******************************************************************************/
  839. /** \brief Setup MCU
  840. *
  841. * FIXME: Needs doc
  842. */
  843. static void setup_mcu(void)
  844. {
  845. /* Disable watchdog if enabled by bootloader/fuses */
  846. MCUSR &= ~(1 << WDRF);
  847. wdt_disable();
  848. /* Disable clock division */
  849. // clock_prescale_set(clock_div_1);
  850. CLKPR = (1 << CLKPCE);
  851. CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
  852. }
  853. /** \brief Setup USB
  854. *
  855. * FIXME: Needs doc
  856. */
  857. static void setup_usb(void)
  858. {
  859. // Leonardo needs. Without this USB device is not recognized.
  860. USB_Disable();
  861. USB_Init();
  862. // for Console_Task
  863. USB_Device_EnableSOFEvents();
  864. print_set_sendchar(sendchar);
  865. }
  866. /** \brief Main
  867. *
  868. * FIXME: Needs doc
  869. */
  870. int main(void) __attribute__ ((weak));
  871. int main(void)
  872. {
  873. #ifdef MIDI_ENABLE
  874. setup_midi();
  875. #endif
  876. setup_mcu();
  877. keyboard_setup();
  878. setup_usb();
  879. sei();
  880. #if defined(MODULE_ADAFRUIT_EZKEY) || defined(MODULE_RN42)
  881. serial_init();
  882. #endif
  883. /* wait for USB startup & debug output */
  884. #ifdef WAIT_FOR_USB
  885. while (USB_DeviceState != DEVICE_STATE_Configured) {
  886. #if defined(INTERRUPT_CONTROL_ENDPOINT)
  887. ;
  888. #else
  889. USB_USBTask();
  890. #endif
  891. }
  892. print("USB configured.\n");
  893. #else
  894. USB_USBTask();
  895. #endif
  896. /* init modules */
  897. keyboard_init();
  898. host_set_driver(&lufa_driver);
  899. #ifdef SLEEP_LED_ENABLE
  900. sleep_led_init();
  901. #endif
  902. #ifdef VIRTSER_ENABLE
  903. virtser_init();
  904. #endif
  905. print("Keyboard start.\n");
  906. while (1) {
  907. #if !defined(NO_USB_STARTUP_CHECK)
  908. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  909. print("[s]");
  910. suspend_power_down();
  911. if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
  912. USB_Device_SendRemoteWakeup();
  913. }
  914. }
  915. #endif
  916. keyboard_task();
  917. #ifdef MIDI_ENABLE
  918. MIDI_Device_USBTask(&USB_MIDI_Interface);
  919. #endif
  920. #if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
  921. rgblight_task();
  922. #endif
  923. #ifdef MODULE_ADAFRUIT_BLE
  924. adafruit_ble_task();
  925. #endif
  926. #ifdef VIRTSER_ENABLE
  927. virtser_task();
  928. CDC_Device_USBTask(&cdc_device);
  929. #endif
  930. #ifdef RAW_ENABLE
  931. raw_hid_task();
  932. #endif
  933. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  934. USB_USBTask();
  935. #endif
  936. }
  937. }
  938. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
  939. const uint16_t wIndex,
  940. const void** const DescriptorAddress)
  941. {
  942. return get_usb_descriptor(wValue, wIndex, DescriptorAddress);
  943. }