lufa.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. /*
  2. * Copyright 2012 Jun Wako <wakojun@gmail.com>
  3. * This file is based on:
  4. * LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
  5. * LUFA-120219/Demos/Device/Lowlevel/GenericHID
  6. */
  7. /*
  8. LUFA Library
  9. Copyright (C) Dean Camera, 2012.
  10. dean [at] fourwalledcubicle [dot] com
  11. www.lufa-lib.org
  12. */
  13. /*
  14. Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  15. Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
  16. Permission to use, copy, modify, distribute, and sell this
  17. software and its documentation for any purpose is hereby granted
  18. without fee, provided that the above copyright notice appear in
  19. all copies and that both that the copyright notice and this
  20. permission notice and warranty disclaimer appear in supporting
  21. documentation, and that the name of the author not be used in
  22. advertising or publicity pertaining to distribution of the
  23. software without specific, written prior permission.
  24. The author disclaim all warranties with regard to this
  25. software, including all implied warranties of merchantability
  26. and fitness. In no event shall the author be liable for any
  27. special, indirect or consequential damages or any damages
  28. whatsoever resulting from loss of use, data or profits, whether
  29. in an action of contract, negligence or other tortious action,
  30. arising out of or in connection with the use or performance of
  31. this software.
  32. */
  33. #include "report.h"
  34. #include "host.h"
  35. #include "host_driver.h"
  36. #include "keyboard.h"
  37. #include "action.h"
  38. #include "led.h"
  39. #include "sendchar.h"
  40. #include "debug.h"
  41. #ifdef SLEEP_LED_ENABLE
  42. # include "sleep_led.h"
  43. #endif
  44. #include "suspend.h"
  45. #include "usb_descriptor.h"
  46. #include "lufa.h"
  47. #include "quantum.h"
  48. #include "usb_device_state.h"
  49. #include <util/atomic.h>
  50. #ifdef NKRO_ENABLE
  51. # include "keycode_config.h"
  52. extern keymap_config_t keymap_config;
  53. #endif
  54. #ifdef AUDIO_ENABLE
  55. # include "audio.h"
  56. #endif
  57. #ifdef BLUETOOTH_ENABLE
  58. # include "outputselect.h"
  59. # ifdef MODULE_ADAFRUIT_BLE
  60. # include "adafruit_ble.h"
  61. # else
  62. # include "../serial.h"
  63. # endif
  64. #endif
  65. #ifdef VIRTSER_ENABLE
  66. # include "virtser.h"
  67. #endif
  68. #ifdef MIDI_ENABLE
  69. # include "qmk_midi.h"
  70. #endif
  71. #ifdef RAW_ENABLE
  72. # include "raw_hid.h"
  73. #endif
  74. #ifdef JOYSTICK_ENABLE
  75. # include "joystick.h"
  76. #endif
  77. // https://cdn.sparkfun.com/datasheets/Wireless/Bluetooth/bluetooth_cr_UG-v1.0r.pdf#G7.663734
  78. static inline uint16_t CONSUMER2RN42(uint16_t usage) {
  79. switch (usage) {
  80. case AC_HOME:
  81. return 0x0001;
  82. case AL_EMAIL:
  83. return 0x0002;
  84. case AC_SEARCH:
  85. return 0x0004;
  86. case AL_KEYBOARD_LAYOUT:
  87. return 0x0008;
  88. case AUDIO_VOL_UP:
  89. return 0x0010;
  90. case AUDIO_VOL_DOWN:
  91. return 0x0020;
  92. case AUDIO_MUTE:
  93. return 0x0040;
  94. case TRANSPORT_PLAY_PAUSE:
  95. return 0x0080;
  96. case TRANSPORT_NEXT_TRACK:
  97. return 0x0100;
  98. case TRANSPORT_PREV_TRACK:
  99. return 0x0200;
  100. case TRANSPORT_STOP:
  101. return 0x0400;
  102. case TRANSPORT_EJECT:
  103. return 0x0800;
  104. case TRANSPORT_FAST_FORWARD:
  105. return 0x1000;
  106. case TRANSPORT_REWIND:
  107. return 0x2000;
  108. case TRANSPORT_STOP_EJECT:
  109. return 0x4000;
  110. case AL_LOCAL_BROWSER:
  111. return 0x8000;
  112. default:
  113. return 0;
  114. }
  115. }
  116. uint8_t keyboard_idle = 0;
  117. /* 0: Boot Protocol, 1: Report Protocol(default) */
  118. uint8_t keyboard_protocol = 1;
  119. static uint8_t keyboard_led_state = 0;
  120. static report_keyboard_t keyboard_report_sent;
  121. /* Host driver */
  122. static uint8_t keyboard_leds(void);
  123. static void send_keyboard(report_keyboard_t *report);
  124. static void send_mouse(report_mouse_t *report);
  125. static void send_system(uint16_t data);
  126. static void send_consumer(uint16_t data);
  127. static void send_programmable_button(uint32_t data);
  128. host_driver_t lufa_driver = {keyboard_leds, send_keyboard, send_mouse, send_system, send_consumer, send_programmable_button};
  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 r;
  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) {
  360. print("[R]");
  361. usb_device_state_set_reset();
  362. }
  363. /** \brief Event USB Device Connect
  364. *
  365. * FIXME: Needs doc
  366. */
  367. void EVENT_USB_Device_Suspend() {
  368. print("[S]");
  369. usb_device_state_set_suspend(USB_Device_ConfigurationNumber != 0, USB_Device_ConfigurationNumber);
  370. #ifdef SLEEP_LED_ENABLE
  371. sleep_led_enable();
  372. #endif
  373. }
  374. /** \brief Event USB Device Connect
  375. *
  376. * FIXME: Needs doc
  377. */
  378. void EVENT_USB_Device_WakeUp() {
  379. print("[W]");
  380. #if defined(NO_USB_STARTUP_CHECK)
  381. suspend_wakeup_init();
  382. #endif
  383. usb_device_state_set_resume(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  384. #ifdef SLEEP_LED_ENABLE
  385. sleep_led_disable();
  386. // NOTE: converters may not accept this
  387. led_set(host_keyboard_leds());
  388. #endif
  389. }
  390. #ifdef CONSOLE_ENABLE
  391. static bool console_flush = false;
  392. # define CONSOLE_FLUSH_SET(b) \
  393. do { \
  394. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { console_flush = b; } \
  395. } while (0)
  396. /** \brief Event USB Device Start Of Frame
  397. *
  398. * FIXME: Needs doc
  399. * called every 1ms
  400. */
  401. void EVENT_USB_Device_StartOfFrame(void) {
  402. static uint8_t count;
  403. if (++count % 50) return;
  404. count = 0;
  405. if (!console_flush) return;
  406. Console_Task();
  407. console_flush = false;
  408. }
  409. #endif
  410. /** \brief Event handler for the USB_ConfigurationChanged event.
  411. *
  412. * This is fired when the host sets the current configuration of the USB device after enumeration.
  413. *
  414. * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
  415. * it is safe to use single bank for all endpoints.
  416. */
  417. void EVENT_USB_Device_ConfigurationChanged(void) {
  418. bool ConfigSuccess = true;
  419. #ifndef KEYBOARD_SHARED_EP
  420. /* Setup keyboard report endpoint */
  421. ConfigSuccess &= Endpoint_ConfigureEndpoint((KEYBOARD_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, KEYBOARD_EPSIZE, 1);
  422. #endif
  423. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  424. /* Setup mouse report endpoint */
  425. ConfigSuccess &= Endpoint_ConfigureEndpoint((MOUSE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, MOUSE_EPSIZE, 1);
  426. #endif
  427. #ifdef SHARED_EP_ENABLE
  428. /* Setup shared report endpoint */
  429. ConfigSuccess &= Endpoint_ConfigureEndpoint((SHARED_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, SHARED_EPSIZE, 1);
  430. #endif
  431. #ifdef RAW_ENABLE
  432. /* Setup raw HID endpoints */
  433. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  434. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  435. #endif
  436. #ifdef CONSOLE_ENABLE
  437. /* Setup console endpoint */
  438. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  439. # if 0
  440. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  441. # endif
  442. #endif
  443. #ifdef MIDI_ENABLE
  444. /* Setup MIDI stream endpoints */
  445. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  446. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  447. #endif
  448. #ifdef VIRTSER_ENABLE
  449. /* Setup virtual serial endpoints */
  450. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
  451. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, CDC_EPSIZE, 1);
  452. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, CDC_EPSIZE, 1);
  453. #endif
  454. #ifdef JOYSTICK_ENABLE
  455. /* Setup joystick endpoint */
  456. ConfigSuccess &= Endpoint_ConfigureEndpoint((JOYSTICK_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
  457. #endif
  458. #if defined(DIGITIZER_ENABLE) && !defined(DIGITIZER_SHARED_EP)
  459. /* Setup digitizer endpoint */
  460. ConfigSuccess &= Endpoint_ConfigureEndpoint((DIGITIZER_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, DIGITIZER_EPSIZE, 1);
  461. #endif
  462. usb_device_state_set_configuration(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  463. }
  464. /* FIXME: Expose this table in the docs somehow
  465. Appendix G: HID Request Support Requirements
  466. The following table enumerates the requests that need to be supported by various types of HID class devices.
  467. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  468. ------------------------------------------------------------------------------------------
  469. Boot Mouse Required Optional Optional Optional Required Required
  470. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  471. Boot Keyboard Required Optional Required Required Required Required
  472. Non-Boot Keybrd Required Optional Required Required Optional Optional
  473. Other Device Required Optional Optional Optional Optional Optional
  474. */
  475. /** \brief Event handler for the USB_ControlRequest event.
  476. *
  477. * This is fired before passing along unhandled control requests to the library for processing internally.
  478. */
  479. void EVENT_USB_Device_ControlRequest(void) {
  480. uint8_t *ReportData = NULL;
  481. uint8_t ReportSize = 0;
  482. /* Handle HID Class specific requests */
  483. switch (USB_ControlRequest.bRequest) {
  484. case HID_REQ_GetReport:
  485. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  486. Endpoint_ClearSETUP();
  487. // Interface
  488. switch (USB_ControlRequest.wIndex) {
  489. case KEYBOARD_INTERFACE:
  490. // TODO: test/check
  491. ReportData = (uint8_t *)&keyboard_report_sent;
  492. ReportSize = sizeof(keyboard_report_sent);
  493. break;
  494. }
  495. /* Write the report data to the control endpoint */
  496. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  497. Endpoint_ClearOUT();
  498. }
  499. break;
  500. case HID_REQ_SetReport:
  501. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  502. // Interface
  503. switch (USB_ControlRequest.wIndex) {
  504. case KEYBOARD_INTERFACE:
  505. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  506. case SHARED_INTERFACE:
  507. #endif
  508. Endpoint_ClearSETUP();
  509. while (!(Endpoint_IsOUTReceived())) {
  510. if (USB_DeviceState == DEVICE_STATE_Unattached) return;
  511. }
  512. if (Endpoint_BytesInEndpoint() == 2) {
  513. uint8_t report_id = Endpoint_Read_8();
  514. if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
  515. keyboard_led_state = Endpoint_Read_8();
  516. }
  517. } else {
  518. keyboard_led_state = Endpoint_Read_8();
  519. }
  520. Endpoint_ClearOUT();
  521. Endpoint_ClearStatusStage();
  522. break;
  523. }
  524. }
  525. break;
  526. case HID_REQ_GetProtocol:
  527. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  528. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  529. Endpoint_ClearSETUP();
  530. while (!(Endpoint_IsINReady()))
  531. ;
  532. Endpoint_Write_8(keyboard_protocol);
  533. Endpoint_ClearIN();
  534. Endpoint_ClearStatusStage();
  535. }
  536. }
  537. break;
  538. case HID_REQ_SetProtocol:
  539. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  540. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  541. Endpoint_ClearSETUP();
  542. Endpoint_ClearStatusStage();
  543. keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
  544. clear_keyboard();
  545. }
  546. }
  547. break;
  548. case HID_REQ_SetIdle:
  549. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  550. Endpoint_ClearSETUP();
  551. Endpoint_ClearStatusStage();
  552. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  553. }
  554. break;
  555. case HID_REQ_GetIdle:
  556. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  557. Endpoint_ClearSETUP();
  558. while (!(Endpoint_IsINReady()))
  559. ;
  560. Endpoint_Write_8(keyboard_idle);
  561. Endpoint_ClearIN();
  562. Endpoint_ClearStatusStage();
  563. }
  564. break;
  565. }
  566. #ifdef VIRTSER_ENABLE
  567. CDC_Device_ProcessControlRequest(&cdc_device);
  568. #endif
  569. }
  570. /*******************************************************************************
  571. * Host driver
  572. ******************************************************************************/
  573. /** \brief Keyboard LEDs
  574. *
  575. * FIXME: Needs doc
  576. */
  577. static uint8_t keyboard_leds(void) { return keyboard_led_state; }
  578. /** \brief Send Keyboard
  579. *
  580. * FIXME: Needs doc
  581. */
  582. static void send_keyboard(report_keyboard_t *report) {
  583. uint8_t timeout = 255;
  584. #ifdef BLUETOOTH_ENABLE
  585. if (where_to_send() == OUTPUT_BLUETOOTH) {
  586. # ifdef MODULE_ADAFRUIT_BLE
  587. adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
  588. # elif MODULE_RN42
  589. serial_send(0xFD);
  590. serial_send(0x09);
  591. serial_send(0x01);
  592. serial_send(report->mods);
  593. serial_send(report->reserved);
  594. for (uint8_t i = 0; i < KEYBOARD_REPORT_KEYS; i++) {
  595. serial_send(report->keys[i]);
  596. }
  597. # endif
  598. return;
  599. }
  600. #endif
  601. /* Select the Keyboard Report Endpoint */
  602. uint8_t ep = KEYBOARD_IN_EPNUM;
  603. uint8_t size = KEYBOARD_REPORT_SIZE;
  604. #ifdef NKRO_ENABLE
  605. if (keyboard_protocol && keymap_config.nkro) {
  606. ep = SHARED_IN_EPNUM;
  607. size = sizeof(struct nkro_report);
  608. }
  609. #endif
  610. Endpoint_SelectEndpoint(ep);
  611. /* Check if write ready for a polling interval around 10ms */
  612. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  613. if (!Endpoint_IsReadWriteAllowed()) return;
  614. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  615. if (!keyboard_protocol) {
  616. Endpoint_Write_Stream_LE(&report->mods, 8, NULL);
  617. } else {
  618. Endpoint_Write_Stream_LE(report, size, NULL);
  619. }
  620. /* Finalize the stream transfer to send the last packet */
  621. Endpoint_ClearIN();
  622. keyboard_report_sent = *report;
  623. }
  624. /** \brief Send Mouse
  625. *
  626. * FIXME: Needs doc
  627. */
  628. static void send_mouse(report_mouse_t *report) {
  629. #ifdef MOUSE_ENABLE
  630. uint8_t timeout = 255;
  631. # ifdef BLUETOOTH_ENABLE
  632. if (where_to_send() == OUTPUT_BLUETOOTH) {
  633. # ifdef MODULE_ADAFRUIT_BLE
  634. // FIXME: mouse buttons
  635. adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
  636. # else
  637. serial_send(0xFD);
  638. serial_send(0x00);
  639. serial_send(0x03);
  640. serial_send(report->buttons);
  641. serial_send(report->x);
  642. serial_send(report->y);
  643. serial_send(report->v); // should try sending the wheel v here
  644. serial_send(report->h); // should try sending the wheel h here
  645. serial_send(0x00);
  646. # endif
  647. return;
  648. }
  649. # endif
  650. /* Select the Mouse Report Endpoint */
  651. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  652. /* Check if write ready for a polling interval around 10ms */
  653. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  654. if (!Endpoint_IsReadWriteAllowed()) return;
  655. /* Write Mouse Report Data */
  656. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  657. /* Finalize the stream transfer to send the last packet */
  658. Endpoint_ClearIN();
  659. #endif
  660. }
  661. #if defined(EXTRAKEY_ENABLE) || defined(PROGRAMMABLE_BUTTON_ENABLE)
  662. static void send_report(void *report, size_t size) {
  663. uint8_t timeout = 255;
  664. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  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(report, size, NULL);
  670. Endpoint_ClearIN();
  671. }
  672. #endif
  673. /** \brief Send Extra
  674. *
  675. * FIXME: Needs doc
  676. */
  677. #ifdef EXTRAKEY_ENABLE
  678. static void send_extra(uint8_t report_id, uint16_t data) {
  679. static report_extra_t r;
  680. r = (report_extra_t){.report_id = report_id, .usage = data};
  681. send_report(&r, sizeof(r));
  682. }
  683. #endif
  684. /** \brief Send System
  685. *
  686. * FIXME: Needs doc
  687. */
  688. static void send_system(uint16_t data) {
  689. #ifdef EXTRAKEY_ENABLE
  690. send_extra(REPORT_ID_SYSTEM, data);
  691. #endif
  692. }
  693. /** \brief Send Consumer
  694. *
  695. * FIXME: Needs doc
  696. */
  697. static void send_consumer(uint16_t data) {
  698. #ifdef EXTRAKEY_ENABLE
  699. # ifdef BLUETOOTH_ENABLE
  700. if (where_to_send() == OUTPUT_BLUETOOTH) {
  701. # ifdef MODULE_ADAFRUIT_BLE
  702. adafruit_ble_send_consumer_key(data);
  703. # elif MODULE_RN42
  704. static uint16_t last_data = 0;
  705. if (data == last_data) return;
  706. last_data = data;
  707. uint16_t bitmap = CONSUMER2RN42(data);
  708. serial_send(0xFD);
  709. serial_send(0x03);
  710. serial_send(0x03);
  711. serial_send(bitmap & 0xFF);
  712. serial_send((bitmap >> 8) & 0xFF);
  713. # endif
  714. return;
  715. }
  716. # endif
  717. send_extra(REPORT_ID_CONSUMER, data);
  718. #endif
  719. }
  720. static void send_programmable_button(uint32_t data) {
  721. #ifdef PROGRAMMABLE_BUTTON_ENABLE
  722. static report_programmable_button_t r;
  723. r = (report_programmable_button_t){.report_id = REPORT_ID_PROGRAMMABLE_BUTTON, .usage = data};
  724. send_report(&r, sizeof(r));
  725. #endif
  726. }
  727. /*******************************************************************************
  728. * sendchar
  729. ******************************************************************************/
  730. #ifdef CONSOLE_ENABLE
  731. # define SEND_TIMEOUT 5
  732. /** \brief Send Char
  733. *
  734. * FIXME: Needs doc
  735. */
  736. int8_t sendchar(uint8_t c) {
  737. // Do not wait if the previous write has timed_out.
  738. // Because sendchar() is called so many times, waiting each call causes big lag.
  739. // The `timed_out` state is an approximation of the ideal `is_listener_disconnected?` state.
  740. static bool timed_out = false;
  741. // prevents Console_Task() from running during sendchar() runs.
  742. // or char will be lost. These two function is mutually exclusive.
  743. CONSOLE_FLUSH_SET(false);
  744. if (USB_DeviceState != DEVICE_STATE_Configured) return -1;
  745. uint8_t ep = Endpoint_GetCurrentEndpoint();
  746. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  747. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  748. goto ERROR_EXIT;
  749. }
  750. if (timed_out && !Endpoint_IsReadWriteAllowed()) {
  751. goto ERROR_EXIT;
  752. }
  753. timed_out = false;
  754. uint8_t timeout = SEND_TIMEOUT;
  755. while (!Endpoint_IsReadWriteAllowed()) {
  756. if (USB_DeviceState != DEVICE_STATE_Configured) {
  757. goto ERROR_EXIT;
  758. }
  759. if (Endpoint_IsStalled()) {
  760. goto ERROR_EXIT;
  761. }
  762. if (!(timeout--)) {
  763. timed_out = true;
  764. goto ERROR_EXIT;
  765. }
  766. _delay_ms(1);
  767. }
  768. Endpoint_Write_8(c);
  769. // send when bank is full
  770. if (!Endpoint_IsReadWriteAllowed()) {
  771. while (!(Endpoint_IsINReady()))
  772. ;
  773. Endpoint_ClearIN();
  774. } else {
  775. CONSOLE_FLUSH_SET(true);
  776. }
  777. Endpoint_SelectEndpoint(ep);
  778. return 0;
  779. ERROR_EXIT:
  780. Endpoint_SelectEndpoint(ep);
  781. return -1;
  782. }
  783. #endif
  784. /*******************************************************************************
  785. * MIDI
  786. ******************************************************************************/
  787. #ifdef MIDI_ENABLE
  788. // clang-format off
  789. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface = {
  790. .Config = {
  791. .StreamingInterfaceNumber = AS_INTERFACE,
  792. .DataINEndpoint = {
  793. .Address = (MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN),
  794. .Size = MIDI_STREAM_EPSIZE,
  795. .Banks = 1
  796. },
  797. .DataOUTEndpoint = {
  798. .Address = (MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT),
  799. .Size = MIDI_STREAM_EPSIZE,
  800. .Banks = 1
  801. }
  802. }
  803. };
  804. // clang-format on
  805. void send_midi_packet(MIDI_EventPacket_t *event) { MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event); }
  806. bool recv_midi_packet(MIDI_EventPacket_t *const event) { return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event); }
  807. #endif
  808. /*******************************************************************************
  809. * VIRTUAL SERIAL
  810. ******************************************************************************/
  811. #ifdef VIRTSER_ENABLE
  812. /** \brief Virtual Serial Init
  813. *
  814. * FIXME: Needs doc
  815. */
  816. void virtser_init(void) {
  817. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR;
  818. CDC_Device_SendControlLineStateChange(&cdc_device);
  819. }
  820. /** \brief Virtual Serial Receive
  821. *
  822. * FIXME: Needs doc
  823. */
  824. void virtser_recv(uint8_t c) __attribute__((weak));
  825. void virtser_recv(uint8_t c) {
  826. // Ignore by default
  827. }
  828. /** \brief Virtual Serial Task
  829. *
  830. * FIXME: Needs doc
  831. */
  832. void virtser_task(void) {
  833. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  834. uint8_t ch;
  835. for (; count; --count) {
  836. ch = CDC_Device_ReceiveByte(&cdc_device);
  837. virtser_recv(ch);
  838. }
  839. }
  840. /** \brief Virtual Serial Send
  841. *
  842. * FIXME: Needs doc
  843. */
  844. void virtser_send(const uint8_t byte) {
  845. uint8_t timeout = 255;
  846. uint8_t ep = Endpoint_GetCurrentEndpoint();
  847. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) {
  848. /* IN packet */
  849. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  850. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  851. Endpoint_SelectEndpoint(ep);
  852. return;
  853. }
  854. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  855. Endpoint_Write_8(byte);
  856. CDC_Device_Flush(&cdc_device);
  857. if (Endpoint_IsINReady()) {
  858. Endpoint_ClearIN();
  859. }
  860. Endpoint_SelectEndpoint(ep);
  861. }
  862. }
  863. #endif
  864. void send_digitizer(report_digitizer_t *report) {
  865. #ifdef DIGITIZER_ENABLE
  866. uint8_t timeout = 255;
  867. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  868. Endpoint_SelectEndpoint(DIGITIZER_IN_EPNUM);
  869. /* Check if write ready for a polling interval around 10ms */
  870. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  871. if (!Endpoint_IsReadWriteAllowed()) return;
  872. Endpoint_Write_Stream_LE(report, sizeof(report_digitizer_t), NULL);
  873. Endpoint_ClearIN();
  874. #endif
  875. }
  876. /*******************************************************************************
  877. * main
  878. ******************************************************************************/
  879. /** \brief Setup MCU
  880. *
  881. * FIXME: Needs doc
  882. */
  883. static void setup_mcu(void) {
  884. /* Disable watchdog if enabled by bootloader/fuses */
  885. MCUSR &= ~_BV(WDRF);
  886. wdt_disable();
  887. // For boards running at 3.3V and crystal at 16 MHz
  888. #if (F_CPU == 8000000 && F_USB == 16000000)
  889. /* Divide clock by 2 */
  890. clock_prescale_set(clock_div_2);
  891. #else /* Disable clock division */
  892. clock_prescale_set(clock_div_1);
  893. #endif
  894. }
  895. /** \brief Setup USB
  896. *
  897. * FIXME: Needs doc
  898. */
  899. static void setup_usb(void) {
  900. // Leonardo needs. Without this USB device is not recognized.
  901. USB_Disable();
  902. USB_Init();
  903. // for Console_Task
  904. USB_Device_EnableSOFEvents();
  905. }
  906. void protocol_setup(void) {
  907. #ifdef MIDI_ENABLE
  908. setup_midi();
  909. #endif
  910. setup_mcu();
  911. usb_device_state_init();
  912. keyboard_setup();
  913. }
  914. void protocol_init(void) {
  915. setup_usb();
  916. sei();
  917. #if defined(MODULE_RN42)
  918. serial_init();
  919. #endif
  920. /* wait for USB startup & debug output */
  921. #ifdef WAIT_FOR_USB
  922. while (USB_DeviceState != DEVICE_STATE_Configured) {
  923. # if defined(INTERRUPT_CONTROL_ENDPOINT)
  924. ;
  925. # else
  926. USB_USBTask();
  927. # endif
  928. }
  929. print("USB configured.\n");
  930. #else
  931. USB_USBTask();
  932. #endif
  933. /* init modules */
  934. keyboard_init();
  935. host_set_driver(&lufa_driver);
  936. #ifdef SLEEP_LED_ENABLE
  937. sleep_led_init();
  938. #endif
  939. #ifdef VIRTSER_ENABLE
  940. virtser_init();
  941. #endif
  942. print("Keyboard start.\n");
  943. }
  944. void protocol_task(void) {
  945. #if !defined(NO_USB_STARTUP_CHECK)
  946. if (USB_DeviceState == DEVICE_STATE_Suspended) {
  947. print("[s]");
  948. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  949. suspend_power_down();
  950. if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
  951. USB_Device_SendRemoteWakeup();
  952. clear_keyboard();
  953. # if USB_SUSPEND_WAKEUP_DELAY > 0
  954. // Some hubs, kvm switches, and monitors do
  955. // weird things, with USB device state bouncing
  956. // around wildly on wakeup, yielding race
  957. // conditions that can corrupt the keyboard state.
  958. //
  959. // Pause for a while to let things settle...
  960. wait_ms(USB_SUSPEND_WAKEUP_DELAY);
  961. # endif
  962. }
  963. }
  964. suspend_wakeup_init();
  965. }
  966. #endif
  967. keyboard_task();
  968. #ifdef MIDI_ENABLE
  969. MIDI_Device_USBTask(&USB_MIDI_Interface);
  970. #endif
  971. #ifdef MODULE_ADAFRUIT_BLE
  972. adafruit_ble_task();
  973. #endif
  974. #ifdef VIRTSER_ENABLE
  975. virtser_task();
  976. CDC_Device_USBTask(&cdc_device);
  977. #endif
  978. #ifdef RAW_ENABLE
  979. raw_hid_task();
  980. #endif
  981. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  982. USB_USBTask();
  983. #endif
  984. }
  985. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, const uint16_t wIndex, const void **const DescriptorAddress) { return get_usb_descriptor(wValue, wIndex, DescriptorAddress); }