lufa.c 25 KB

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