lufa.c 25 KB

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