lufa.c 31 KB

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