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. static joystick_report_t;
  269. r = (joystick_report_t) {
  270. # if JOYSTICK_AXES_COUNT > 0
  271. .axes =
  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. joystick->buttons[0],
  293. # if JOYSTICK_BUTTON_COUNT > 8
  294. joystick->buttons[1],
  295. # endif
  296. # if JOYSTICK_BUTTON_COUNT > 16
  297. joystick->buttons[2],
  298. # endif
  299. # if JOYSTICK_BUTTON_COUNT > 24
  300. joystick->buttons[3],
  301. # endif
  302. }
  303. # endif // JOYSTICK_BUTTON_COUNT>0
  304. };
  305. /* Select the Joystick Report Endpoint */
  306. Endpoint_SelectEndpoint(JOYSTICK_IN_EPNUM);
  307. /* Check if write ready for a polling interval around 10ms */
  308. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  309. if (!Endpoint_IsReadWriteAllowed()) return;
  310. /* Write Joystick Report Data */
  311. Endpoint_Write_Stream_LE(&r, sizeof(joystick_report_t), NULL);
  312. /* Finalize the stream transfer to send the last packet */
  313. Endpoint_ClearIN();
  314. }
  315. #endif
  316. /*******************************************************************************
  317. * USB Events
  318. ******************************************************************************/
  319. /*
  320. * Event Order of Plug in:
  321. * 0) EVENT_USB_Device_Connect
  322. * 1) EVENT_USB_Device_Suspend
  323. * 2) EVENT_USB_Device_Reset
  324. * 3) EVENT_USB_Device_Wake
  325. */
  326. /** \brief Event USB Device Connect
  327. *
  328. * FIXME: Needs doc
  329. */
  330. void EVENT_USB_Device_Connect(void) {
  331. print("[C]");
  332. /* For battery powered device */
  333. if (!USB_IsInitialized) {
  334. USB_Disable();
  335. USB_Init();
  336. USB_Device_EnableSOFEvents();
  337. }
  338. }
  339. /** \brief Event USB Device Connect
  340. *
  341. * FIXME: Needs doc
  342. */
  343. void EVENT_USB_Device_Disconnect(void) {
  344. print("[D]");
  345. /* For battery powered device */
  346. USB_IsInitialized = false;
  347. /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
  348. if (USB_IsInitialized) {
  349. USB_Disable(); // Disable all interrupts
  350. USB_Controller_Enable();
  351. USB_INT_Enable(USB_INT_VBUSTI);
  352. }
  353. */
  354. }
  355. /** \brief Event USB Device Connect
  356. *
  357. * FIXME: Needs doc
  358. */
  359. void EVENT_USB_Device_Reset(void) { print("[R]"); }
  360. /** \brief Event USB Device Connect
  361. *
  362. * FIXME: Needs doc
  363. */
  364. void EVENT_USB_Device_Suspend() {
  365. print("[S]");
  366. #ifdef SLEEP_LED_ENABLE
  367. sleep_led_enable();
  368. #endif
  369. }
  370. /** \brief Event USB Device Connect
  371. *
  372. * FIXME: Needs doc
  373. */
  374. void EVENT_USB_Device_WakeUp() {
  375. print("[W]");
  376. #if defined(NO_USB_STARTUP_CHECK)
  377. suspend_wakeup_init();
  378. #endif
  379. #ifdef SLEEP_LED_ENABLE
  380. sleep_led_disable();
  381. // NOTE: converters may not accept this
  382. led_set(host_keyboard_leds());
  383. #endif
  384. }
  385. #ifdef CONSOLE_ENABLE
  386. static bool console_flush = false;
  387. # define CONSOLE_FLUSH_SET(b) \
  388. do { \
  389. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { console_flush = b; } \
  390. } while (0)
  391. /** \brief Event USB Device Start Of Frame
  392. *
  393. * FIXME: Needs doc
  394. * called every 1ms
  395. */
  396. void EVENT_USB_Device_StartOfFrame(void) {
  397. static uint8_t count;
  398. if (++count % 50) return;
  399. count = 0;
  400. if (!console_flush) return;
  401. Console_Task();
  402. console_flush = false;
  403. }
  404. #endif
  405. /** \brief Event handler for the USB_ConfigurationChanged event.
  406. *
  407. * This is fired when the host sets the current configuration of the USB device after enumeration.
  408. *
  409. * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
  410. * it is safe to use single bank for all endpoints.
  411. */
  412. void EVENT_USB_Device_ConfigurationChanged(void) {
  413. bool ConfigSuccess = true;
  414. #ifndef KEYBOARD_SHARED_EP
  415. /* Setup keyboard report endpoint */
  416. ConfigSuccess &= Endpoint_ConfigureEndpoint((KEYBOARD_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, KEYBOARD_EPSIZE, 1);
  417. #endif
  418. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  419. /* Setup mouse report endpoint */
  420. ConfigSuccess &= Endpoint_ConfigureEndpoint((MOUSE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, MOUSE_EPSIZE, 1);
  421. #endif
  422. #ifdef SHARED_EP_ENABLE
  423. /* Setup shared report endpoint */
  424. ConfigSuccess &= Endpoint_ConfigureEndpoint((SHARED_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, SHARED_EPSIZE, 1);
  425. #endif
  426. #ifdef RAW_ENABLE
  427. /* Setup raw HID endpoints */
  428. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  429. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  430. #endif
  431. #ifdef CONSOLE_ENABLE
  432. /* Setup console endpoint */
  433. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  434. # if 0
  435. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  436. # endif
  437. #endif
  438. #ifdef MIDI_ENABLE
  439. /* Setup MIDI stream endpoints */
  440. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  441. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  442. #endif
  443. #ifdef VIRTSER_ENABLE
  444. /* Setup virtual serial endpoints */
  445. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
  446. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, CDC_EPSIZE, 1);
  447. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, CDC_EPSIZE, 1);
  448. #endif
  449. #ifdef JOYSTICK_ENABLE
  450. /* Setup joystick endpoint */
  451. ConfigSuccess &= Endpoint_ConfigureEndpoint((JOYSTICK_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
  452. #endif
  453. }
  454. /* FIXME: Expose this table in the docs somehow
  455. Appendix G: HID Request Support Requirements
  456. The following table enumerates the requests that need to be supported by various types of HID class devices.
  457. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  458. ------------------------------------------------------------------------------------------
  459. Boot Mouse Required Optional Optional Optional Required Required
  460. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  461. Boot Keyboard Required Optional Required Required Required Required
  462. Non-Boot Keybrd Required Optional Required Required Optional Optional
  463. Other Device Required Optional Optional Optional Optional Optional
  464. */
  465. /** \brief Event handler for the USB_ControlRequest event.
  466. *
  467. * This is fired before passing along unhandled control requests to the library for processing internally.
  468. */
  469. void EVENT_USB_Device_ControlRequest(void) {
  470. uint8_t *ReportData = NULL;
  471. uint8_t ReportSize = 0;
  472. /* Handle HID Class specific requests */
  473. switch (USB_ControlRequest.bRequest) {
  474. case HID_REQ_GetReport:
  475. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  476. Endpoint_ClearSETUP();
  477. // Interface
  478. switch (USB_ControlRequest.wIndex) {
  479. case KEYBOARD_INTERFACE:
  480. // TODO: test/check
  481. ReportData = (uint8_t *)&keyboard_report_sent;
  482. ReportSize = sizeof(keyboard_report_sent);
  483. break;
  484. }
  485. /* Write the report data to the control endpoint */
  486. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  487. Endpoint_ClearOUT();
  488. }
  489. break;
  490. case HID_REQ_SetReport:
  491. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  492. // Interface
  493. switch (USB_ControlRequest.wIndex) {
  494. case KEYBOARD_INTERFACE:
  495. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  496. case SHARED_INTERFACE:
  497. #endif
  498. Endpoint_ClearSETUP();
  499. while (!(Endpoint_IsOUTReceived())) {
  500. if (USB_DeviceState == DEVICE_STATE_Unattached) return;
  501. }
  502. if (Endpoint_BytesInEndpoint() == 2) {
  503. uint8_t report_id = Endpoint_Read_8();
  504. if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
  505. keyboard_led_state = Endpoint_Read_8();
  506. }
  507. } else {
  508. keyboard_led_state = Endpoint_Read_8();
  509. }
  510. Endpoint_ClearOUT();
  511. Endpoint_ClearStatusStage();
  512. break;
  513. }
  514. }
  515. break;
  516. case HID_REQ_GetProtocol:
  517. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  518. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  519. Endpoint_ClearSETUP();
  520. while (!(Endpoint_IsINReady()))
  521. ;
  522. Endpoint_Write_8(keyboard_protocol);
  523. Endpoint_ClearIN();
  524. Endpoint_ClearStatusStage();
  525. }
  526. }
  527. break;
  528. case HID_REQ_SetProtocol:
  529. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  530. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  531. Endpoint_ClearSETUP();
  532. Endpoint_ClearStatusStage();
  533. keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
  534. clear_keyboard();
  535. }
  536. }
  537. break;
  538. case HID_REQ_SetIdle:
  539. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  540. Endpoint_ClearSETUP();
  541. Endpoint_ClearStatusStage();
  542. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  543. }
  544. break;
  545. case HID_REQ_GetIdle:
  546. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  547. Endpoint_ClearSETUP();
  548. while (!(Endpoint_IsINReady()))
  549. ;
  550. Endpoint_Write_8(keyboard_idle);
  551. Endpoint_ClearIN();
  552. Endpoint_ClearStatusStage();
  553. }
  554. break;
  555. }
  556. #ifdef VIRTSER_ENABLE
  557. CDC_Device_ProcessControlRequest(&cdc_device);
  558. #endif
  559. }
  560. /*******************************************************************************
  561. * Host driver
  562. ******************************************************************************/
  563. /** \brief Keyboard LEDs
  564. *
  565. * FIXME: Needs doc
  566. */
  567. static uint8_t keyboard_leds(void) { return keyboard_led_state; }
  568. /** \brief Send Keyboard
  569. *
  570. * FIXME: Needs doc
  571. */
  572. static void send_keyboard(report_keyboard_t *report) {
  573. uint8_t timeout = 255;
  574. #ifdef BLUETOOTH_ENABLE
  575. if (where_to_send() == OUTPUT_BLUETOOTH) {
  576. # ifdef MODULE_ADAFRUIT_BLE
  577. adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
  578. # elif MODULE_RN42
  579. serial_send(0xFD);
  580. serial_send(0x09);
  581. serial_send(0x01);
  582. serial_send(report->mods);
  583. serial_send(report->reserved);
  584. for (uint8_t i = 0; i < KEYBOARD_REPORT_KEYS; i++) {
  585. serial_send(report->keys[i]);
  586. }
  587. # endif
  588. return;
  589. }
  590. #endif
  591. /* Select the Keyboard Report Endpoint */
  592. uint8_t ep = KEYBOARD_IN_EPNUM;
  593. uint8_t size = KEYBOARD_REPORT_SIZE;
  594. #ifdef NKRO_ENABLE
  595. if (keyboard_protocol && keymap_config.nkro) {
  596. ep = SHARED_IN_EPNUM;
  597. size = sizeof(struct nkro_report);
  598. }
  599. #endif
  600. Endpoint_SelectEndpoint(ep);
  601. /* Check if write ready for a polling interval around 10ms */
  602. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  603. if (!Endpoint_IsReadWriteAllowed()) return;
  604. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  605. if (!keyboard_protocol) {
  606. Endpoint_Write_Stream_LE(&report->mods, 8, NULL);
  607. } else {
  608. Endpoint_Write_Stream_LE(report, size, NULL);
  609. }
  610. /* Finalize the stream transfer to send the last packet */
  611. Endpoint_ClearIN();
  612. keyboard_report_sent = *report;
  613. }
  614. /** \brief Send Mouse
  615. *
  616. * FIXME: Needs doc
  617. */
  618. static void send_mouse(report_mouse_t *report) {
  619. #ifdef MOUSE_ENABLE
  620. uint8_t timeout = 255;
  621. # ifdef BLUETOOTH_ENABLE
  622. if (where_to_send() == OUTPUT_BLUETOOTH) {
  623. # ifdef MODULE_ADAFRUIT_BLE
  624. // FIXME: mouse buttons
  625. adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
  626. # else
  627. serial_send(0xFD);
  628. serial_send(0x00);
  629. serial_send(0x03);
  630. serial_send(report->buttons);
  631. serial_send(report->x);
  632. serial_send(report->y);
  633. serial_send(report->v); // should try sending the wheel v here
  634. serial_send(report->h); // should try sending the wheel h here
  635. serial_send(0x00);
  636. # endif
  637. return;
  638. }
  639. # endif
  640. /* Select the Mouse Report Endpoint */
  641. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  642. /* Check if write ready for a polling interval around 10ms */
  643. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  644. if (!Endpoint_IsReadWriteAllowed()) return;
  645. /* Write Mouse Report Data */
  646. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  647. /* Finalize the stream transfer to send the last packet */
  648. Endpoint_ClearIN();
  649. #endif
  650. }
  651. /** \brief Send Extra
  652. *
  653. * FIXME: Needs doc
  654. */
  655. #ifdef EXTRAKEY_ENABLE
  656. static void send_extra(uint8_t report_id, uint16_t data) {
  657. uint8_t timeout = 255;
  658. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  659. static report_extra_t r;
  660. r = (report_extra_t){.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); }