lufa.c 31 KB

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