lufa.c 31 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. suspend_wakeup_init();
  378. #ifdef SLEEP_LED_ENABLE
  379. sleep_led_disable();
  380. // NOTE: converters may not accept this
  381. led_set(host_keyboard_leds());
  382. #endif
  383. }
  384. #ifdef CONSOLE_ENABLE
  385. static bool console_flush = false;
  386. # define CONSOLE_FLUSH_SET(b) \
  387. do { \
  388. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { console_flush = b; } \
  389. } while (0)
  390. /** \brief Event USB Device Start Of Frame
  391. *
  392. * FIXME: Needs doc
  393. * called every 1ms
  394. */
  395. void EVENT_USB_Device_StartOfFrame(void) {
  396. static uint8_t count;
  397. if (++count % 50) return;
  398. count = 0;
  399. if (!console_flush) return;
  400. Console_Task();
  401. console_flush = false;
  402. }
  403. #endif
  404. /** \brief Event handler for the USB_ConfigurationChanged event.
  405. *
  406. * This is fired when the host sets the current configuration of the USB device after enumeration.
  407. *
  408. * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
  409. * it is safe to use single bank for all endpoints.
  410. */
  411. void EVENT_USB_Device_ConfigurationChanged(void) {
  412. bool ConfigSuccess = true;
  413. #ifndef KEYBOARD_SHARED_EP
  414. /* Setup keyboard report endpoint */
  415. ConfigSuccess &= Endpoint_ConfigureEndpoint((KEYBOARD_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, KEYBOARD_EPSIZE, 1);
  416. #endif
  417. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  418. /* Setup mouse report endpoint */
  419. ConfigSuccess &= Endpoint_ConfigureEndpoint((MOUSE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, MOUSE_EPSIZE, 1);
  420. #endif
  421. #ifdef SHARED_EP_ENABLE
  422. /* Setup shared report endpoint */
  423. ConfigSuccess &= Endpoint_ConfigureEndpoint((SHARED_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, SHARED_EPSIZE, 1);
  424. #endif
  425. #ifdef RAW_ENABLE
  426. /* Setup raw HID endpoints */
  427. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  428. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  429. #endif
  430. #ifdef CONSOLE_ENABLE
  431. /* Setup console endpoint */
  432. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  433. # if 0
  434. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  435. # endif
  436. #endif
  437. #ifdef MIDI_ENABLE
  438. /* Setup MIDI stream endpoints */
  439. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  440. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  441. #endif
  442. #ifdef VIRTSER_ENABLE
  443. /* Setup virtual serial endpoints */
  444. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
  445. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, CDC_EPSIZE, 1);
  446. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, CDC_EPSIZE, 1);
  447. #endif
  448. #ifdef JOYSTICK_ENABLE
  449. /* Setup joystick endpoint */
  450. ConfigSuccess &= Endpoint_ConfigureEndpoint((JOYSTICK_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
  451. #endif
  452. }
  453. /* FIXME: Expose this table in the docs somehow
  454. Appendix G: HID Request Support Requirements
  455. The following table enumerates the requests that need to be supported by various types of HID class devices.
  456. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  457. ------------------------------------------------------------------------------------------
  458. Boot Mouse Required Optional Optional Optional Required Required
  459. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  460. Boot Keyboard Required Optional Required Required Required Required
  461. Non-Boot Keybrd Required Optional Required Required Optional Optional
  462. Other Device Required Optional Optional Optional Optional Optional
  463. */
  464. /** \brief Event handler for the USB_ControlRequest event.
  465. *
  466. * This is fired before passing along unhandled control requests to the library for processing internally.
  467. */
  468. void EVENT_USB_Device_ControlRequest(void) {
  469. uint8_t *ReportData = NULL;
  470. uint8_t ReportSize = 0;
  471. /* Handle HID Class specific requests */
  472. switch (USB_ControlRequest.bRequest) {
  473. case HID_REQ_GetReport:
  474. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  475. Endpoint_ClearSETUP();
  476. // Interface
  477. switch (USB_ControlRequest.wIndex) {
  478. case KEYBOARD_INTERFACE:
  479. // TODO: test/check
  480. ReportData = (uint8_t *)&keyboard_report_sent;
  481. ReportSize = sizeof(keyboard_report_sent);
  482. break;
  483. }
  484. /* Write the report data to the control endpoint */
  485. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  486. Endpoint_ClearOUT();
  487. }
  488. break;
  489. case HID_REQ_SetReport:
  490. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  491. // Interface
  492. switch (USB_ControlRequest.wIndex) {
  493. case KEYBOARD_INTERFACE:
  494. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  495. case SHARED_INTERFACE:
  496. #endif
  497. Endpoint_ClearSETUP();
  498. while (!(Endpoint_IsOUTReceived())) {
  499. if (USB_DeviceState == DEVICE_STATE_Unattached) return;
  500. }
  501. if (Endpoint_BytesInEndpoint() == 2) {
  502. uint8_t report_id = Endpoint_Read_8();
  503. if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
  504. keyboard_led_state = Endpoint_Read_8();
  505. }
  506. } else {
  507. keyboard_led_state = Endpoint_Read_8();
  508. }
  509. Endpoint_ClearOUT();
  510. Endpoint_ClearStatusStage();
  511. break;
  512. }
  513. }
  514. break;
  515. case HID_REQ_GetProtocol:
  516. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  517. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  518. Endpoint_ClearSETUP();
  519. while (!(Endpoint_IsINReady()))
  520. ;
  521. Endpoint_Write_8(keyboard_protocol);
  522. Endpoint_ClearIN();
  523. Endpoint_ClearStatusStage();
  524. }
  525. }
  526. break;
  527. case HID_REQ_SetProtocol:
  528. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  529. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  530. Endpoint_ClearSETUP();
  531. Endpoint_ClearStatusStage();
  532. keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
  533. clear_keyboard();
  534. }
  535. }
  536. break;
  537. case HID_REQ_SetIdle:
  538. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  539. Endpoint_ClearSETUP();
  540. Endpoint_ClearStatusStage();
  541. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  542. }
  543. break;
  544. case HID_REQ_GetIdle:
  545. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  546. Endpoint_ClearSETUP();
  547. while (!(Endpoint_IsINReady()))
  548. ;
  549. Endpoint_Write_8(keyboard_idle);
  550. Endpoint_ClearIN();
  551. Endpoint_ClearStatusStage();
  552. }
  553. break;
  554. }
  555. #ifdef VIRTSER_ENABLE
  556. CDC_Device_ProcessControlRequest(&cdc_device);
  557. #endif
  558. }
  559. /*******************************************************************************
  560. * Host driver
  561. ******************************************************************************/
  562. /** \brief Keyboard LEDs
  563. *
  564. * FIXME: Needs doc
  565. */
  566. static uint8_t keyboard_leds(void) { return keyboard_led_state; }
  567. /** \brief Send Keyboard
  568. *
  569. * FIXME: Needs doc
  570. */
  571. static void send_keyboard(report_keyboard_t *report) {
  572. uint8_t timeout = 255;
  573. #ifdef BLUETOOTH_ENABLE
  574. uint8_t where = where_to_send();
  575. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  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. }
  589. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  590. return;
  591. }
  592. #endif
  593. /* Select the Keyboard Report Endpoint */
  594. uint8_t ep = KEYBOARD_IN_EPNUM;
  595. uint8_t size = KEYBOARD_REPORT_SIZE;
  596. #ifdef NKRO_ENABLE
  597. if (keyboard_protocol && keymap_config.nkro) {
  598. ep = SHARED_IN_EPNUM;
  599. size = sizeof(struct nkro_report);
  600. }
  601. #endif
  602. Endpoint_SelectEndpoint(ep);
  603. /* Check if write ready for a polling interval around 10ms */
  604. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  605. if (!Endpoint_IsReadWriteAllowed()) return;
  606. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  607. if (!keyboard_protocol) {
  608. Endpoint_Write_Stream_LE(&report->mods, 8, NULL);
  609. } else {
  610. Endpoint_Write_Stream_LE(report, size, NULL);
  611. }
  612. /* Finalize the stream transfer to send the last packet */
  613. Endpoint_ClearIN();
  614. keyboard_report_sent = *report;
  615. }
  616. /** \brief Send Mouse
  617. *
  618. * FIXME: Needs doc
  619. */
  620. static void send_mouse(report_mouse_t *report) {
  621. #ifdef MOUSE_ENABLE
  622. uint8_t timeout = 255;
  623. # ifdef BLUETOOTH_ENABLE
  624. uint8_t where = where_to_send();
  625. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  626. # ifdef MODULE_ADAFRUIT_BLE
  627. // FIXME: mouse buttons
  628. adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
  629. # else
  630. serial_send(0xFD);
  631. serial_send(0x00);
  632. serial_send(0x03);
  633. serial_send(report->buttons);
  634. serial_send(report->x);
  635. serial_send(report->y);
  636. serial_send(report->v); // should try sending the wheel v here
  637. serial_send(report->h); // should try sending the wheel h here
  638. serial_send(0x00);
  639. # endif
  640. }
  641. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  642. return;
  643. }
  644. # endif
  645. /* Select the Mouse Report Endpoint */
  646. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  647. /* Check if write ready for a polling interval around 10ms */
  648. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  649. if (!Endpoint_IsReadWriteAllowed()) return;
  650. /* Write Mouse Report Data */
  651. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  652. /* Finalize the stream transfer to send the last packet */
  653. Endpoint_ClearIN();
  654. #endif
  655. }
  656. /** \brief Send Extra
  657. *
  658. * FIXME: Needs doc
  659. */
  660. #ifdef EXTRAKEY_ENABLE
  661. static void send_extra(uint8_t report_id, uint16_t data) {
  662. uint8_t timeout = 255;
  663. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  664. report_extra_t r = {.report_id = report_id, .usage = data};
  665. Endpoint_SelectEndpoint(SHARED_IN_EPNUM);
  666. /* Check if write ready for a polling interval around 10ms */
  667. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  668. if (!Endpoint_IsReadWriteAllowed()) return;
  669. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  670. Endpoint_ClearIN();
  671. }
  672. #endif
  673. /** \brief Send System
  674. *
  675. * FIXME: Needs doc
  676. */
  677. static void send_system(uint16_t data) {
  678. #ifdef EXTRAKEY_ENABLE
  679. send_extra(REPORT_ID_SYSTEM, data);
  680. #endif
  681. }
  682. /** \brief Send Consumer
  683. *
  684. * FIXME: Needs doc
  685. */
  686. static void send_consumer(uint16_t data) {
  687. #ifdef EXTRAKEY_ENABLE
  688. # ifdef BLUETOOTH_ENABLE
  689. uint8_t where = where_to_send();
  690. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  691. # ifdef MODULE_ADAFRUIT_BLE
  692. adafruit_ble_send_consumer_key(data);
  693. # elif MODULE_RN42
  694. static uint16_t last_data = 0;
  695. if (data == last_data) return;
  696. last_data = data;
  697. uint16_t bitmap = CONSUMER2RN42(data);
  698. serial_send(0xFD);
  699. serial_send(0x03);
  700. serial_send(0x03);
  701. serial_send(bitmap & 0xFF);
  702. serial_send((bitmap >> 8) & 0xFF);
  703. # endif
  704. }
  705. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  706. return;
  707. }
  708. # endif
  709. send_extra(REPORT_ID_CONSUMER, data);
  710. #endif
  711. }
  712. /*******************************************************************************
  713. * sendchar
  714. ******************************************************************************/
  715. #ifdef CONSOLE_ENABLE
  716. # define SEND_TIMEOUT 5
  717. /** \brief Send Char
  718. *
  719. * FIXME: Needs doc
  720. */
  721. int8_t sendchar(uint8_t c) {
  722. // Not wait once timeouted.
  723. // Because sendchar() is called so many times, waiting each call causes big lag.
  724. static bool timeouted = false;
  725. // prevents Console_Task() from running during sendchar() runs.
  726. // or char will be lost. These two function is mutually exclusive.
  727. CONSOLE_FLUSH_SET(false);
  728. if (USB_DeviceState != DEVICE_STATE_Configured) return -1;
  729. uint8_t ep = Endpoint_GetCurrentEndpoint();
  730. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  731. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  732. goto ERROR_EXIT;
  733. }
  734. if (timeouted && !Endpoint_IsReadWriteAllowed()) {
  735. goto ERROR_EXIT;
  736. }
  737. timeouted = false;
  738. uint8_t timeout = SEND_TIMEOUT;
  739. while (!Endpoint_IsReadWriteAllowed()) {
  740. if (USB_DeviceState != DEVICE_STATE_Configured) {
  741. goto ERROR_EXIT;
  742. }
  743. if (Endpoint_IsStalled()) {
  744. goto ERROR_EXIT;
  745. }
  746. if (!(timeout--)) {
  747. timeouted = true;
  748. goto ERROR_EXIT;
  749. }
  750. _delay_ms(1);
  751. }
  752. Endpoint_Write_8(c);
  753. // send when bank is full
  754. if (!Endpoint_IsReadWriteAllowed()) {
  755. while (!(Endpoint_IsINReady()))
  756. ;
  757. Endpoint_ClearIN();
  758. } else {
  759. CONSOLE_FLUSH_SET(true);
  760. }
  761. Endpoint_SelectEndpoint(ep);
  762. return 0;
  763. ERROR_EXIT:
  764. Endpoint_SelectEndpoint(ep);
  765. return -1;
  766. }
  767. #endif
  768. /*******************************************************************************
  769. * MIDI
  770. ******************************************************************************/
  771. #ifdef MIDI_ENABLE
  772. // clang-format off
  773. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface = {
  774. .Config = {
  775. .StreamingInterfaceNumber = AS_INTERFACE,
  776. .DataINEndpoint = {
  777. .Address = (MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN),
  778. .Size = MIDI_STREAM_EPSIZE,
  779. .Banks = 1
  780. },
  781. .DataOUTEndpoint = {
  782. .Address = (MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT),
  783. .Size = MIDI_STREAM_EPSIZE,
  784. .Banks = 1
  785. }
  786. }
  787. };
  788. // clang-format on
  789. void send_midi_packet(MIDI_EventPacket_t *event) { MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event); }
  790. bool recv_midi_packet(MIDI_EventPacket_t *const event) { return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event); }
  791. #endif
  792. /*******************************************************************************
  793. * VIRTUAL SERIAL
  794. ******************************************************************************/
  795. #ifdef VIRTSER_ENABLE
  796. /** \brief Virtual Serial Init
  797. *
  798. * FIXME: Needs doc
  799. */
  800. void virtser_init(void) {
  801. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR;
  802. CDC_Device_SendControlLineStateChange(&cdc_device);
  803. }
  804. /** \brief Virtual Serial Receive
  805. *
  806. * FIXME: Needs doc
  807. */
  808. void virtser_recv(uint8_t c) __attribute__((weak));
  809. void virtser_recv(uint8_t c) {
  810. // Ignore by default
  811. }
  812. /** \brief Virtual Serial Task
  813. *
  814. * FIXME: Needs doc
  815. */
  816. void virtser_task(void) {
  817. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  818. uint8_t ch;
  819. for (; count; --count) {
  820. ch = CDC_Device_ReceiveByte(&cdc_device);
  821. virtser_recv(ch);
  822. }
  823. }
  824. /** \brief Virtual Serial Send
  825. *
  826. * FIXME: Needs doc
  827. */
  828. void virtser_send(const uint8_t byte) {
  829. uint8_t timeout = 255;
  830. uint8_t ep = Endpoint_GetCurrentEndpoint();
  831. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) {
  832. /* IN packet */
  833. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  834. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  835. Endpoint_SelectEndpoint(ep);
  836. return;
  837. }
  838. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  839. Endpoint_Write_8(byte);
  840. CDC_Device_Flush(&cdc_device);
  841. if (Endpoint_IsINReady()) {
  842. Endpoint_ClearIN();
  843. }
  844. Endpoint_SelectEndpoint(ep);
  845. }
  846. }
  847. #endif
  848. /*******************************************************************************
  849. * main
  850. ******************************************************************************/
  851. /** \brief Setup MCU
  852. *
  853. * FIXME: Needs doc
  854. */
  855. static void setup_mcu(void) {
  856. /* Disable watchdog if enabled by bootloader/fuses */
  857. MCUSR &= ~_BV(WDRF);
  858. wdt_disable();
  859. /* Disable clock division */
  860. clock_prescale_set(clock_div_1);
  861. }
  862. /** \brief Setup USB
  863. *
  864. * FIXME: Needs doc
  865. */
  866. static void setup_usb(void) {
  867. // Leonardo needs. Without this USB device is not recognized.
  868. USB_Disable();
  869. USB_Init();
  870. // for Console_Task
  871. USB_Device_EnableSOFEvents();
  872. print_set_sendchar(sendchar);
  873. }
  874. /** \brief Main
  875. *
  876. * FIXME: Needs doc
  877. */
  878. int main(void) __attribute__((weak));
  879. int main(void) {
  880. #ifdef MIDI_ENABLE
  881. setup_midi();
  882. #endif
  883. setup_mcu();
  884. keyboard_setup();
  885. setup_usb();
  886. sei();
  887. #if defined(MODULE_RN42)
  888. serial_init();
  889. #endif
  890. /* wait for USB startup & debug output */
  891. #ifdef WAIT_FOR_USB
  892. while (USB_DeviceState != DEVICE_STATE_Configured) {
  893. # if defined(INTERRUPT_CONTROL_ENDPOINT)
  894. ;
  895. # else
  896. USB_USBTask();
  897. # endif
  898. }
  899. print("USB configured.\n");
  900. #else
  901. USB_USBTask();
  902. #endif
  903. /* init modules */
  904. keyboard_init();
  905. host_set_driver(&lufa_driver);
  906. #ifdef SLEEP_LED_ENABLE
  907. sleep_led_init();
  908. #endif
  909. #ifdef VIRTSER_ENABLE
  910. virtser_init();
  911. #endif
  912. print("Keyboard start.\n");
  913. while (1) {
  914. #if !defined(NO_USB_STARTUP_CHECK)
  915. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  916. print("[s]");
  917. suspend_power_down();
  918. if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
  919. USB_Device_SendRemoteWakeup();
  920. }
  921. }
  922. #endif
  923. keyboard_task();
  924. #ifdef MIDI_ENABLE
  925. MIDI_Device_USBTask(&USB_MIDI_Interface);
  926. #endif
  927. #ifdef MODULE_ADAFRUIT_BLE
  928. adafruit_ble_task();
  929. #endif
  930. #ifdef VIRTSER_ENABLE
  931. virtser_task();
  932. CDC_Device_USBTask(&cdc_device);
  933. #endif
  934. #ifdef RAW_ENABLE
  935. raw_hid_task();
  936. #endif
  937. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  938. USB_USBTask();
  939. #endif
  940. // Run housekeeping
  941. housekeeping_task_kb();
  942. housekeeping_task_user();
  943. }
  944. }
  945. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, const uint16_t wIndex, const void **const DescriptorAddress) { return get_usb_descriptor(wValue, wIndex, DescriptorAddress); }