lufa.c 26 KB

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