lufa.c 26 KB

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