lufa.c 29 KB

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