lufa.c 25 KB

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