lufa.c 32 KB

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