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 "usb_device_state.h"
  49. #include <util/atomic.h>
  50. #ifdef NKRO_ENABLE
  51. # include "keycode_config.h"
  52. extern keymap_config_t keymap_config;
  53. #endif
  54. #ifdef AUDIO_ENABLE
  55. # include "audio.h"
  56. #endif
  57. #ifdef BLUETOOTH_ENABLE
  58. # include "outputselect.h"
  59. # ifdef BLUETOOTH_BLUEFRUIT_LE
  60. # include "bluefruit_le.h"
  61. # elif BLUETOOTH_RN42
  62. # include "rn42.h"
  63. # endif
  64. #endif
  65. #ifdef VIRTSER_ENABLE
  66. # include "virtser.h"
  67. #endif
  68. #ifdef MIDI_ENABLE
  69. # include "qmk_midi.h"
  70. #endif
  71. #ifdef RAW_ENABLE
  72. # include "raw_hid.h"
  73. #endif
  74. #ifdef JOYSTICK_ENABLE
  75. # include "joystick.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_state = 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. static void send_programmable_button(uint32_t data);
  89. host_driver_t lufa_driver = {keyboard_leds, send_keyboard, send_mouse, send_system, send_consumer, send_programmable_button};
  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. static joystick_report_t r;
  230. r = (joystick_report_t) {
  231. # if JOYSTICK_AXES_COUNT > 0
  232. .axes =
  233. { joystick->axes[0],
  234. # if JOYSTICK_AXES_COUNT >= 2
  235. joystick->axes[1],
  236. # endif
  237. # if JOYSTICK_AXES_COUNT >= 3
  238. joystick->axes[2],
  239. # endif
  240. # if JOYSTICK_AXES_COUNT >= 4
  241. joystick->axes[3],
  242. # endif
  243. # if JOYSTICK_AXES_COUNT >= 5
  244. joystick->axes[4],
  245. # endif
  246. # if JOYSTICK_AXES_COUNT >= 6
  247. joystick->axes[5],
  248. # endif
  249. },
  250. # endif // JOYSTICK_AXES_COUNT>0
  251. # if JOYSTICK_BUTTON_COUNT > 0
  252. .buttons = {
  253. joystick->buttons[0],
  254. # if JOYSTICK_BUTTON_COUNT > 8
  255. joystick->buttons[1],
  256. # endif
  257. # if JOYSTICK_BUTTON_COUNT > 16
  258. joystick->buttons[2],
  259. # endif
  260. # if JOYSTICK_BUTTON_COUNT > 24
  261. joystick->buttons[3],
  262. # endif
  263. }
  264. # endif // JOYSTICK_BUTTON_COUNT>0
  265. };
  266. /* Select the Joystick Report Endpoint */
  267. Endpoint_SelectEndpoint(JOYSTICK_IN_EPNUM);
  268. /* Check if write ready for a polling interval around 10ms */
  269. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  270. if (!Endpoint_IsReadWriteAllowed()) return;
  271. /* Write Joystick Report Data */
  272. Endpoint_Write_Stream_LE(&r, sizeof(joystick_report_t), NULL);
  273. /* Finalize the stream transfer to send the last packet */
  274. Endpoint_ClearIN();
  275. }
  276. #endif
  277. /*******************************************************************************
  278. * USB Events
  279. ******************************************************************************/
  280. /*
  281. * Event Order of Plug in:
  282. * 0) EVENT_USB_Device_Connect
  283. * 1) EVENT_USB_Device_Suspend
  284. * 2) EVENT_USB_Device_Reset
  285. * 3) EVENT_USB_Device_Wake
  286. */
  287. /** \brief Event USB Device Connect
  288. *
  289. * FIXME: Needs doc
  290. */
  291. void EVENT_USB_Device_Connect(void) {
  292. print("[C]");
  293. /* For battery powered device */
  294. if (!USB_IsInitialized) {
  295. USB_Disable();
  296. USB_Init();
  297. USB_Device_EnableSOFEvents();
  298. }
  299. }
  300. /** \brief Event USB Device Connect
  301. *
  302. * FIXME: Needs doc
  303. */
  304. void EVENT_USB_Device_Disconnect(void) {
  305. print("[D]");
  306. /* For battery powered device */
  307. USB_IsInitialized = false;
  308. /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
  309. if (USB_IsInitialized) {
  310. USB_Disable(); // Disable all interrupts
  311. USB_Controller_Enable();
  312. USB_INT_Enable(USB_INT_VBUSTI);
  313. }
  314. */
  315. }
  316. /** \brief Event USB Device Connect
  317. *
  318. * FIXME: Needs doc
  319. */
  320. void EVENT_USB_Device_Reset(void) {
  321. print("[R]");
  322. usb_device_state_set_reset();
  323. }
  324. /** \brief Event USB Device Connect
  325. *
  326. * FIXME: Needs doc
  327. */
  328. void EVENT_USB_Device_Suspend() {
  329. print("[S]");
  330. usb_device_state_set_suspend(USB_Device_ConfigurationNumber != 0, USB_Device_ConfigurationNumber);
  331. #ifdef SLEEP_LED_ENABLE
  332. sleep_led_enable();
  333. #endif
  334. }
  335. /** \brief Event USB Device Connect
  336. *
  337. * FIXME: Needs doc
  338. */
  339. void EVENT_USB_Device_WakeUp() {
  340. print("[W]");
  341. #if defined(NO_USB_STARTUP_CHECK)
  342. suspend_wakeup_init();
  343. #endif
  344. usb_device_state_set_resume(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  345. #ifdef SLEEP_LED_ENABLE
  346. sleep_led_disable();
  347. // NOTE: converters may not accept this
  348. led_set(host_keyboard_leds());
  349. #endif
  350. }
  351. #ifdef CONSOLE_ENABLE
  352. static bool console_flush = false;
  353. # define CONSOLE_FLUSH_SET(b) \
  354. do { \
  355. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { console_flush = b; } \
  356. } while (0)
  357. /** \brief Event USB Device Start Of Frame
  358. *
  359. * FIXME: Needs doc
  360. * called every 1ms
  361. */
  362. void EVENT_USB_Device_StartOfFrame(void) {
  363. static uint8_t count;
  364. if (++count % 50) return;
  365. count = 0;
  366. if (!console_flush) return;
  367. Console_Task();
  368. console_flush = false;
  369. }
  370. #endif
  371. /** \brief Event handler for the USB_ConfigurationChanged event.
  372. *
  373. * This is fired when the host sets the current configuration of the USB device after enumeration.
  374. *
  375. * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
  376. * it is safe to use single bank for all endpoints.
  377. */
  378. void EVENT_USB_Device_ConfigurationChanged(void) {
  379. bool ConfigSuccess = true;
  380. #ifndef KEYBOARD_SHARED_EP
  381. /* Setup keyboard report endpoint */
  382. ConfigSuccess &= Endpoint_ConfigureEndpoint((KEYBOARD_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, KEYBOARD_EPSIZE, 1);
  383. #endif
  384. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  385. /* Setup mouse report endpoint */
  386. ConfigSuccess &= Endpoint_ConfigureEndpoint((MOUSE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, MOUSE_EPSIZE, 1);
  387. #endif
  388. #ifdef SHARED_EP_ENABLE
  389. /* Setup shared report endpoint */
  390. ConfigSuccess &= Endpoint_ConfigureEndpoint((SHARED_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, SHARED_EPSIZE, 1);
  391. #endif
  392. #ifdef RAW_ENABLE
  393. /* Setup raw HID endpoints */
  394. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  395. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  396. #endif
  397. #ifdef CONSOLE_ENABLE
  398. /* Setup console endpoint */
  399. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  400. # if 0
  401. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  402. # endif
  403. #endif
  404. #ifdef MIDI_ENABLE
  405. /* Setup MIDI stream endpoints */
  406. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  407. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  408. #endif
  409. #ifdef VIRTSER_ENABLE
  410. /* Setup virtual serial endpoints */
  411. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
  412. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, CDC_EPSIZE, 1);
  413. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, CDC_EPSIZE, 1);
  414. #endif
  415. #ifdef JOYSTICK_ENABLE
  416. /* Setup joystick endpoint */
  417. ConfigSuccess &= Endpoint_ConfigureEndpoint((JOYSTICK_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
  418. #endif
  419. #if defined(DIGITIZER_ENABLE) && !defined(DIGITIZER_SHARED_EP)
  420. /* Setup digitizer endpoint */
  421. ConfigSuccess &= Endpoint_ConfigureEndpoint((DIGITIZER_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, DIGITIZER_EPSIZE, 1);
  422. #endif
  423. usb_device_state_set_configuration(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  424. }
  425. /* FIXME: Expose this table in the docs somehow
  426. Appendix G: HID Request Support Requirements
  427. The following table enumerates the requests that need to be supported by various types of HID class devices.
  428. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  429. ------------------------------------------------------------------------------------------
  430. Boot Mouse Required Optional Optional Optional Required Required
  431. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  432. Boot Keyboard Required Optional Required Required Required Required
  433. Non-Boot Keybrd Required Optional Required Required Optional Optional
  434. Other Device Required Optional Optional Optional Optional Optional
  435. */
  436. /** \brief Event handler for the USB_ControlRequest event.
  437. *
  438. * This is fired before passing along unhandled control requests to the library for processing internally.
  439. */
  440. void EVENT_USB_Device_ControlRequest(void) {
  441. uint8_t *ReportData = NULL;
  442. uint8_t ReportSize = 0;
  443. /* Handle HID Class specific requests */
  444. switch (USB_ControlRequest.bRequest) {
  445. case HID_REQ_GetReport:
  446. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  447. Endpoint_ClearSETUP();
  448. // Interface
  449. switch (USB_ControlRequest.wIndex) {
  450. case KEYBOARD_INTERFACE:
  451. // TODO: test/check
  452. ReportData = (uint8_t *)&keyboard_report_sent;
  453. ReportSize = sizeof(keyboard_report_sent);
  454. break;
  455. }
  456. /* Write the report data to the control endpoint */
  457. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  458. Endpoint_ClearOUT();
  459. }
  460. break;
  461. case HID_REQ_SetReport:
  462. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  463. // Interface
  464. switch (USB_ControlRequest.wIndex) {
  465. case KEYBOARD_INTERFACE:
  466. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  467. case SHARED_INTERFACE:
  468. #endif
  469. Endpoint_ClearSETUP();
  470. while (!(Endpoint_IsOUTReceived())) {
  471. if (USB_DeviceState == DEVICE_STATE_Unattached) return;
  472. }
  473. if (Endpoint_BytesInEndpoint() == 2) {
  474. uint8_t report_id = Endpoint_Read_8();
  475. if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
  476. keyboard_led_state = Endpoint_Read_8();
  477. }
  478. } else {
  479. keyboard_led_state = Endpoint_Read_8();
  480. }
  481. Endpoint_ClearOUT();
  482. Endpoint_ClearStatusStage();
  483. break;
  484. }
  485. }
  486. break;
  487. case HID_REQ_GetProtocol:
  488. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  489. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  490. Endpoint_ClearSETUP();
  491. while (!(Endpoint_IsINReady()))
  492. ;
  493. Endpoint_Write_8(keyboard_protocol);
  494. Endpoint_ClearIN();
  495. Endpoint_ClearStatusStage();
  496. }
  497. }
  498. break;
  499. case HID_REQ_SetProtocol:
  500. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  501. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  502. Endpoint_ClearSETUP();
  503. Endpoint_ClearStatusStage();
  504. keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
  505. clear_keyboard();
  506. }
  507. }
  508. break;
  509. case HID_REQ_SetIdle:
  510. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  511. Endpoint_ClearSETUP();
  512. Endpoint_ClearStatusStage();
  513. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  514. }
  515. break;
  516. case HID_REQ_GetIdle:
  517. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  518. Endpoint_ClearSETUP();
  519. while (!(Endpoint_IsINReady()))
  520. ;
  521. Endpoint_Write_8(keyboard_idle);
  522. Endpoint_ClearIN();
  523. Endpoint_ClearStatusStage();
  524. }
  525. break;
  526. }
  527. #ifdef VIRTSER_ENABLE
  528. CDC_Device_ProcessControlRequest(&cdc_device);
  529. #endif
  530. }
  531. /*******************************************************************************
  532. * Host driver
  533. ******************************************************************************/
  534. /** \brief Keyboard LEDs
  535. *
  536. * FIXME: Needs doc
  537. */
  538. static uint8_t keyboard_leds(void) { return keyboard_led_state; }
  539. /** \brief Send Keyboard
  540. *
  541. * FIXME: Needs doc
  542. */
  543. static void send_keyboard(report_keyboard_t *report) {
  544. uint8_t timeout = 255;
  545. #ifdef BLUETOOTH_ENABLE
  546. if (where_to_send() == OUTPUT_BLUETOOTH) {
  547. # ifdef BLUETOOTH_BLUEFRUIT_LE
  548. bluefruit_le_send_keys(report->mods, report->keys, sizeof(report->keys));
  549. # elif BLUETOOTH_RN42
  550. rn42_send_keyboard(report);
  551. # endif
  552. return;
  553. }
  554. #endif
  555. /* Select the Keyboard Report Endpoint */
  556. uint8_t ep = KEYBOARD_IN_EPNUM;
  557. uint8_t size = KEYBOARD_REPORT_SIZE;
  558. #ifdef NKRO_ENABLE
  559. if (keyboard_protocol && keymap_config.nkro) {
  560. ep = SHARED_IN_EPNUM;
  561. size = sizeof(struct nkro_report);
  562. }
  563. #endif
  564. Endpoint_SelectEndpoint(ep);
  565. /* Check if write ready for a polling interval around 10ms */
  566. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  567. if (!Endpoint_IsReadWriteAllowed()) return;
  568. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  569. if (!keyboard_protocol) {
  570. Endpoint_Write_Stream_LE(&report->mods, 8, NULL);
  571. } else {
  572. Endpoint_Write_Stream_LE(report, size, NULL);
  573. }
  574. /* Finalize the stream transfer to send the last packet */
  575. Endpoint_ClearIN();
  576. keyboard_report_sent = *report;
  577. }
  578. /** \brief Send Mouse
  579. *
  580. * FIXME: Needs doc
  581. */
  582. static void send_mouse(report_mouse_t *report) {
  583. #ifdef MOUSE_ENABLE
  584. uint8_t timeout = 255;
  585. # ifdef BLUETOOTH_ENABLE
  586. if (where_to_send() == OUTPUT_BLUETOOTH) {
  587. # ifdef BLUETOOTH_BLUEFRUIT_LE
  588. // FIXME: mouse buttons
  589. bluefruit_le_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
  590. # elif BLUETOOTH_RN42
  591. rn42_send_mouse(report);
  592. # endif
  593. return;
  594. }
  595. # endif
  596. /* Select the Mouse Report Endpoint */
  597. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  598. /* Check if write ready for a polling interval around 10ms */
  599. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  600. if (!Endpoint_IsReadWriteAllowed()) return;
  601. /* Write Mouse Report Data */
  602. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  603. /* Finalize the stream transfer to send the last packet */
  604. Endpoint_ClearIN();
  605. #endif
  606. }
  607. #if defined(EXTRAKEY_ENABLE) || defined(PROGRAMMABLE_BUTTON_ENABLE)
  608. static void send_report(void *report, size_t size) {
  609. uint8_t timeout = 255;
  610. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  611. Endpoint_SelectEndpoint(SHARED_IN_EPNUM);
  612. /* Check if write ready for a polling interval around 10ms */
  613. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  614. if (!Endpoint_IsReadWriteAllowed()) return;
  615. Endpoint_Write_Stream_LE(report, size, NULL);
  616. Endpoint_ClearIN();
  617. }
  618. #endif
  619. /** \brief Send Extra
  620. *
  621. * FIXME: Needs doc
  622. */
  623. #ifdef EXTRAKEY_ENABLE
  624. static void send_extra(uint8_t report_id, uint16_t data) {
  625. static report_extra_t r;
  626. r = (report_extra_t){.report_id = report_id, .usage = data};
  627. send_report(&r, sizeof(r));
  628. }
  629. #endif
  630. /** \brief Send System
  631. *
  632. * FIXME: Needs doc
  633. */
  634. static void send_system(uint16_t data) {
  635. #ifdef EXTRAKEY_ENABLE
  636. send_extra(REPORT_ID_SYSTEM, data);
  637. #endif
  638. }
  639. /** \brief Send Consumer
  640. *
  641. * FIXME: Needs doc
  642. */
  643. static void send_consumer(uint16_t data) {
  644. #ifdef EXTRAKEY_ENABLE
  645. # ifdef BLUETOOTH_ENABLE
  646. if (where_to_send() == OUTPUT_BLUETOOTH) {
  647. # ifdef BLUETOOTH_BLUEFRUIT_LE
  648. bluefruit_le_send_consumer_key(data);
  649. # elif BLUETOOTH_RN42
  650. rn42_send_consumer(data);
  651. # endif
  652. return;
  653. }
  654. # endif
  655. send_extra(REPORT_ID_CONSUMER, data);
  656. #endif
  657. }
  658. static void send_programmable_button(uint32_t data) {
  659. #ifdef PROGRAMMABLE_BUTTON_ENABLE
  660. static report_programmable_button_t r;
  661. r = (report_programmable_button_t){.report_id = REPORT_ID_PROGRAMMABLE_BUTTON, .usage = data};
  662. send_report(&r, sizeof(r));
  663. #endif
  664. }
  665. /*******************************************************************************
  666. * sendchar
  667. ******************************************************************************/
  668. #ifdef CONSOLE_ENABLE
  669. # define SEND_TIMEOUT 5
  670. /** \brief Send Char
  671. *
  672. * FIXME: Needs doc
  673. */
  674. int8_t sendchar(uint8_t c) {
  675. // Do not wait if the previous write has timed_out.
  676. // Because sendchar() is called so many times, waiting each call causes big lag.
  677. // The `timed_out` state is an approximation of the ideal `is_listener_disconnected?` state.
  678. static bool timed_out = false;
  679. // prevents Console_Task() from running during sendchar() runs.
  680. // or char will be lost. These two function is mutually exclusive.
  681. CONSOLE_FLUSH_SET(false);
  682. if (USB_DeviceState != DEVICE_STATE_Configured) return -1;
  683. uint8_t ep = Endpoint_GetCurrentEndpoint();
  684. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  685. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  686. goto ERROR_EXIT;
  687. }
  688. if (timed_out && !Endpoint_IsReadWriteAllowed()) {
  689. goto ERROR_EXIT;
  690. }
  691. timed_out = false;
  692. uint8_t timeout = SEND_TIMEOUT;
  693. while (!Endpoint_IsReadWriteAllowed()) {
  694. if (USB_DeviceState != DEVICE_STATE_Configured) {
  695. goto ERROR_EXIT;
  696. }
  697. if (Endpoint_IsStalled()) {
  698. goto ERROR_EXIT;
  699. }
  700. if (!(timeout--)) {
  701. timed_out = true;
  702. goto ERROR_EXIT;
  703. }
  704. _delay_ms(1);
  705. }
  706. Endpoint_Write_8(c);
  707. // send when bank is full
  708. if (!Endpoint_IsReadWriteAllowed()) {
  709. while (!(Endpoint_IsINReady()))
  710. ;
  711. Endpoint_ClearIN();
  712. } else {
  713. CONSOLE_FLUSH_SET(true);
  714. }
  715. Endpoint_SelectEndpoint(ep);
  716. return 0;
  717. ERROR_EXIT:
  718. Endpoint_SelectEndpoint(ep);
  719. return -1;
  720. }
  721. #endif
  722. /*******************************************************************************
  723. * MIDI
  724. ******************************************************************************/
  725. #ifdef MIDI_ENABLE
  726. // clang-format off
  727. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface = {
  728. .Config = {
  729. .StreamingInterfaceNumber = AS_INTERFACE,
  730. .DataINEndpoint = {
  731. .Address = (MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN),
  732. .Size = MIDI_STREAM_EPSIZE,
  733. .Banks = 1
  734. },
  735. .DataOUTEndpoint = {
  736. .Address = (MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT),
  737. .Size = MIDI_STREAM_EPSIZE,
  738. .Banks = 1
  739. }
  740. }
  741. };
  742. // clang-format on
  743. void send_midi_packet(MIDI_EventPacket_t *event) { MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event); }
  744. bool recv_midi_packet(MIDI_EventPacket_t *const event) { return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event); }
  745. #endif
  746. /*******************************************************************************
  747. * VIRTUAL SERIAL
  748. ******************************************************************************/
  749. #ifdef VIRTSER_ENABLE
  750. /** \brief Virtual Serial Init
  751. *
  752. * FIXME: Needs doc
  753. */
  754. void virtser_init(void) {
  755. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR;
  756. CDC_Device_SendControlLineStateChange(&cdc_device);
  757. }
  758. /** \brief Virtual Serial Receive
  759. *
  760. * FIXME: Needs doc
  761. */
  762. void virtser_recv(uint8_t c) __attribute__((weak));
  763. void virtser_recv(uint8_t c) {
  764. // Ignore by default
  765. }
  766. /** \brief Virtual Serial Task
  767. *
  768. * FIXME: Needs doc
  769. */
  770. void virtser_task(void) {
  771. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  772. uint8_t ch;
  773. for (; count; --count) {
  774. ch = CDC_Device_ReceiveByte(&cdc_device);
  775. virtser_recv(ch);
  776. }
  777. }
  778. /** \brief Virtual Serial Send
  779. *
  780. * FIXME: Needs doc
  781. */
  782. void virtser_send(const uint8_t byte) {
  783. uint8_t timeout = 255;
  784. uint8_t ep = Endpoint_GetCurrentEndpoint();
  785. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) {
  786. /* IN packet */
  787. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  788. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  789. Endpoint_SelectEndpoint(ep);
  790. return;
  791. }
  792. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  793. Endpoint_Write_8(byte);
  794. CDC_Device_Flush(&cdc_device);
  795. if (Endpoint_IsINReady()) {
  796. Endpoint_ClearIN();
  797. }
  798. Endpoint_SelectEndpoint(ep);
  799. }
  800. }
  801. #endif
  802. void send_digitizer(report_digitizer_t *report) {
  803. #ifdef DIGITIZER_ENABLE
  804. uint8_t timeout = 255;
  805. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  806. Endpoint_SelectEndpoint(DIGITIZER_IN_EPNUM);
  807. /* Check if write ready for a polling interval around 10ms */
  808. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  809. if (!Endpoint_IsReadWriteAllowed()) return;
  810. Endpoint_Write_Stream_LE(report, sizeof(report_digitizer_t), NULL);
  811. Endpoint_ClearIN();
  812. #endif
  813. }
  814. /*******************************************************************************
  815. * main
  816. ******************************************************************************/
  817. /** \brief Setup MCU
  818. *
  819. * FIXME: Needs doc
  820. */
  821. static void setup_mcu(void) {
  822. /* Disable watchdog if enabled by bootloader/fuses */
  823. MCUSR &= ~_BV(WDRF);
  824. wdt_disable();
  825. // For boards running at 3.3V and crystal at 16 MHz
  826. #if (F_CPU == 8000000 && F_USB == 16000000)
  827. /* Divide clock by 2 */
  828. clock_prescale_set(clock_div_2);
  829. #else /* Disable clock division */
  830. clock_prescale_set(clock_div_1);
  831. #endif
  832. }
  833. /** \brief Setup USB
  834. *
  835. * FIXME: Needs doc
  836. */
  837. static void setup_usb(void) {
  838. // Leonardo needs. Without this USB device is not recognized.
  839. USB_Disable();
  840. USB_Init();
  841. // for Console_Task
  842. USB_Device_EnableSOFEvents();
  843. }
  844. void protocol_setup(void) {
  845. #ifdef MIDI_ENABLE
  846. setup_midi();
  847. #endif
  848. setup_mcu();
  849. usb_device_state_init();
  850. }
  851. void protocol_pre_init(void) {
  852. setup_usb();
  853. sei();
  854. #if defined(BLUETOOTH_RN42)
  855. rn42_init();
  856. #endif
  857. /* wait for USB startup & debug output */
  858. #ifdef WAIT_FOR_USB
  859. while (USB_DeviceState != DEVICE_STATE_Configured) {
  860. # if defined(INTERRUPT_CONTROL_ENDPOINT)
  861. ;
  862. # else
  863. USB_USBTask();
  864. # endif
  865. }
  866. print("USB configured.\n");
  867. #else
  868. USB_USBTask();
  869. #endif
  870. }
  871. void protocol_post_init(void) { host_set_driver(&lufa_driver); }
  872. void protocol_pre_task(void) {
  873. #if !defined(NO_USB_STARTUP_CHECK)
  874. if (USB_DeviceState == DEVICE_STATE_Suspended) {
  875. print("[s]");
  876. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  877. suspend_power_down();
  878. if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
  879. USB_Device_SendRemoteWakeup();
  880. clear_keyboard();
  881. # if USB_SUSPEND_WAKEUP_DELAY > 0
  882. // Some hubs, kvm switches, and monitors do
  883. // weird things, with USB device state bouncing
  884. // around wildly on wakeup, yielding race
  885. // conditions that can corrupt the keyboard state.
  886. //
  887. // Pause for a while to let things settle...
  888. wait_ms(USB_SUSPEND_WAKEUP_DELAY);
  889. # endif
  890. }
  891. }
  892. suspend_wakeup_init();
  893. }
  894. #endif
  895. }
  896. void protocol_post_task(void) {
  897. #ifdef MIDI_ENABLE
  898. MIDI_Device_USBTask(&USB_MIDI_Interface);
  899. #endif
  900. #ifdef BLUETOOTH_BLUEFRUIT_LE
  901. bluefruit_le_task();
  902. #endif
  903. #ifdef VIRTSER_ENABLE
  904. virtser_task();
  905. CDC_Device_USBTask(&cdc_device);
  906. #endif
  907. #ifdef RAW_ENABLE
  908. raw_hid_task();
  909. #endif
  910. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  911. USB_USBTask();
  912. #endif
  913. }
  914. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, const uint16_t wIndex, const void **const DescriptorAddress) { return get_usb_descriptor(wValue, wIndex, DescriptorAddress); }