lufa.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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 CONSOLE_ENABLE
  298. /* Setup console endpoint */
  299. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  300. #endif
  301. #ifdef MIDI_ENABLE
  302. /* Setup MIDI stream endpoints */
  303. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  304. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  305. #endif
  306. #ifdef VIRTSER_ENABLE
  307. /* Setup virtual serial endpoints */
  308. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
  309. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, CDC_EPSIZE, 1);
  310. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, CDC_EPSIZE, 1);
  311. #endif
  312. #if defined(JOYSTICK_ENABLE) && !defined(JOYSTICK_SHARED_EP)
  313. /* Setup joystick endpoint */
  314. ConfigSuccess &= Endpoint_ConfigureEndpoint((JOYSTICK_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
  315. #endif
  316. #if defined(DIGITIZER_ENABLE) && !defined(DIGITIZER_SHARED_EP)
  317. /* Setup digitizer endpoint */
  318. ConfigSuccess &= Endpoint_ConfigureEndpoint((DIGITIZER_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, DIGITIZER_EPSIZE, 1);
  319. #endif
  320. usb_device_state_set_configuration(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  321. }
  322. /* FIXME: Expose this table in the docs somehow
  323. Appendix G: HID Request Support Requirements
  324. The following table enumerates the requests that need to be supported by various types of HID class devices.
  325. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  326. ------------------------------------------------------------------------------------------
  327. Boot Mouse Required Optional Optional Optional Required Required
  328. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  329. Boot Keyboard Required Optional Required Required Required Required
  330. Non-Boot Keybrd Required Optional Required Required Optional Optional
  331. Other Device Required Optional Optional Optional Optional Optional
  332. */
  333. /** \brief Event handler for the USB_ControlRequest event.
  334. *
  335. * This is fired before passing along unhandled control requests to the library for processing internally.
  336. */
  337. void EVENT_USB_Device_ControlRequest(void) {
  338. uint8_t *ReportData = NULL;
  339. uint8_t ReportSize = 0;
  340. /* Handle HID Class specific requests */
  341. switch (USB_ControlRequest.bRequest) {
  342. case HID_REQ_GetReport:
  343. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  344. Endpoint_ClearSETUP();
  345. // Interface
  346. switch (USB_ControlRequest.wIndex) {
  347. case KEYBOARD_INTERFACE:
  348. // TODO: test/check
  349. ReportData = (uint8_t *)&keyboard_report_sent;
  350. ReportSize = sizeof(keyboard_report_sent);
  351. break;
  352. }
  353. /* Write the report data to the control endpoint */
  354. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  355. Endpoint_ClearOUT();
  356. }
  357. break;
  358. case HID_REQ_SetReport:
  359. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  360. // Interface
  361. switch (USB_ControlRequest.wIndex) {
  362. case KEYBOARD_INTERFACE:
  363. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  364. case SHARED_INTERFACE:
  365. #endif
  366. Endpoint_ClearSETUP();
  367. while (!(Endpoint_IsOUTReceived())) {
  368. if (USB_DeviceState == DEVICE_STATE_Unattached) return;
  369. }
  370. if (Endpoint_BytesInEndpoint() == 2) {
  371. uint8_t report_id = Endpoint_Read_8();
  372. if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
  373. usb_device_state_set_leds(Endpoint_Read_8());
  374. }
  375. } else {
  376. usb_device_state_set_leds(Endpoint_Read_8());
  377. }
  378. Endpoint_ClearOUT();
  379. Endpoint_ClearStatusStage();
  380. break;
  381. }
  382. }
  383. break;
  384. case HID_REQ_GetProtocol:
  385. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  386. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  387. Endpoint_ClearSETUP();
  388. while (!(Endpoint_IsINReady()))
  389. ;
  390. Endpoint_Write_8(usb_device_state_get_protocol());
  391. Endpoint_ClearIN();
  392. Endpoint_ClearStatusStage();
  393. }
  394. }
  395. break;
  396. case HID_REQ_SetProtocol:
  397. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  398. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  399. Endpoint_ClearSETUP();
  400. Endpoint_ClearStatusStage();
  401. usb_device_state_set_protocol(USB_ControlRequest.wValue & 0xFF);
  402. clear_keyboard();
  403. }
  404. }
  405. break;
  406. case HID_REQ_SetIdle:
  407. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  408. Endpoint_ClearSETUP();
  409. Endpoint_ClearStatusStage();
  410. usb_device_state_set_idle_rate(USB_ControlRequest.wValue >> 8);
  411. }
  412. break;
  413. case HID_REQ_GetIdle:
  414. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  415. Endpoint_ClearSETUP();
  416. while (!(Endpoint_IsINReady()))
  417. ;
  418. Endpoint_Write_8(usb_device_state_get_idle_rate());
  419. Endpoint_ClearIN();
  420. Endpoint_ClearStatusStage();
  421. }
  422. break;
  423. }
  424. #ifdef VIRTSER_ENABLE
  425. CDC_Device_ProcessControlRequest(&cdc_device);
  426. #endif
  427. }
  428. /*******************************************************************************
  429. * Host driver
  430. ******************************************************************************/
  431. /** \brief Send Keyboard
  432. *
  433. * FIXME: Needs doc
  434. */
  435. static void send_keyboard(report_keyboard_t *report) {
  436. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  437. if (usb_device_state_get_protocol() == USB_PROTOCOL_BOOT) {
  438. send_report(KEYBOARD_IN_EPNUM, &report->mods, 8);
  439. } else {
  440. send_report(KEYBOARD_IN_EPNUM, report, KEYBOARD_REPORT_SIZE);
  441. }
  442. keyboard_report_sent = *report;
  443. }
  444. /** \brief Send NKRO
  445. *
  446. * FIXME: Needs doc
  447. */
  448. static void send_nkro(report_nkro_t *report) {
  449. #ifdef NKRO_ENABLE
  450. send_report(SHARED_IN_EPNUM, report, sizeof(report_nkro_t));
  451. #endif
  452. }
  453. /** \brief Send Mouse
  454. *
  455. * FIXME: Needs doc
  456. */
  457. static void send_mouse(report_mouse_t *report) {
  458. #ifdef MOUSE_ENABLE
  459. send_report(MOUSE_IN_EPNUM, report, sizeof(report_mouse_t));
  460. #endif
  461. }
  462. /** \brief Send Extra
  463. *
  464. * FIXME: Needs doc
  465. */
  466. static void send_extra(report_extra_t *report) {
  467. #ifdef EXTRAKEY_ENABLE
  468. send_report(SHARED_IN_EPNUM, report, sizeof(report_extra_t));
  469. #endif
  470. }
  471. void send_joystick(report_joystick_t *report) {
  472. #ifdef JOYSTICK_ENABLE
  473. send_report(JOYSTICK_IN_EPNUM, report, sizeof(report_joystick_t));
  474. #endif
  475. }
  476. void send_programmable_button(report_programmable_button_t *report) {
  477. #ifdef PROGRAMMABLE_BUTTON_ENABLE
  478. send_report(SHARED_IN_EPNUM, report, sizeof(report_programmable_button_t));
  479. #endif
  480. }
  481. void send_digitizer(report_digitizer_t *report) {
  482. #ifdef DIGITIZER_ENABLE
  483. send_report(DIGITIZER_IN_EPNUM, report, sizeof(report_digitizer_t));
  484. #endif
  485. }
  486. /*******************************************************************************
  487. * sendchar
  488. ******************************************************************************/
  489. #ifdef CONSOLE_ENABLE
  490. # define SEND_TIMEOUT 5
  491. /** \brief Send Char
  492. *
  493. * FIXME: Needs doc
  494. */
  495. int8_t sendchar(uint8_t c) {
  496. // Do not wait if the previous write has timed_out.
  497. // Because sendchar() is called so many times, waiting each call causes big lag.
  498. // The `timed_out` state is an approximation of the ideal `is_listener_disconnected?` state.
  499. static bool timed_out = false;
  500. // prevents console_flush_task() from running during sendchar() runs.
  501. // or char will be lost. These two function is mutually exclusive.
  502. CONSOLE_FLUSH_SET(false);
  503. if (USB_DeviceState != DEVICE_STATE_Configured) return -1;
  504. uint8_t ep = Endpoint_GetCurrentEndpoint();
  505. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  506. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  507. goto ERROR_EXIT;
  508. }
  509. if (timed_out && !Endpoint_IsReadWriteAllowed()) {
  510. goto ERROR_EXIT;
  511. }
  512. timed_out = false;
  513. uint8_t timeout = SEND_TIMEOUT;
  514. while (!Endpoint_IsReadWriteAllowed()) {
  515. if (USB_DeviceState != DEVICE_STATE_Configured) {
  516. goto ERROR_EXIT;
  517. }
  518. if (Endpoint_IsStalled()) {
  519. goto ERROR_EXIT;
  520. }
  521. if (!(timeout--)) {
  522. timed_out = true;
  523. goto ERROR_EXIT;
  524. }
  525. _delay_ms(1);
  526. }
  527. Endpoint_Write_8(c);
  528. // send when bank is full
  529. if (!Endpoint_IsReadWriteAllowed()) {
  530. while (!(Endpoint_IsINReady()))
  531. ;
  532. Endpoint_ClearIN();
  533. } else {
  534. CONSOLE_FLUSH_SET(true);
  535. }
  536. Endpoint_SelectEndpoint(ep);
  537. return 0;
  538. ERROR_EXIT:
  539. Endpoint_SelectEndpoint(ep);
  540. return -1;
  541. }
  542. #endif
  543. /*******************************************************************************
  544. * MIDI
  545. ******************************************************************************/
  546. #ifdef MIDI_ENABLE
  547. // clang-format off
  548. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface = {
  549. .Config = {
  550. .StreamingInterfaceNumber = AS_INTERFACE,
  551. .DataINEndpoint = {
  552. .Address = (MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN),
  553. .Size = MIDI_STREAM_EPSIZE,
  554. .Banks = 1
  555. },
  556. .DataOUTEndpoint = {
  557. .Address = (MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT),
  558. .Size = MIDI_STREAM_EPSIZE,
  559. .Banks = 1
  560. }
  561. }
  562. };
  563. // clang-format on
  564. void send_midi_packet(MIDI_EventPacket_t *event) {
  565. MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
  566. }
  567. bool recv_midi_packet(MIDI_EventPacket_t *const event) {
  568. return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
  569. }
  570. #endif
  571. /*******************************************************************************
  572. * VIRTUAL SERIAL
  573. ******************************************************************************/
  574. #ifdef VIRTSER_ENABLE
  575. /** \brief Virtual Serial Init
  576. *
  577. * FIXME: Needs doc
  578. */
  579. void virtser_init(void) {
  580. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR;
  581. CDC_Device_SendControlLineStateChange(&cdc_device);
  582. }
  583. /** \brief Virtual Serial Receive
  584. *
  585. * FIXME: Needs doc
  586. */
  587. void virtser_recv(uint8_t c) __attribute__((weak));
  588. void virtser_recv(uint8_t c) {
  589. // Ignore by default
  590. }
  591. /** \brief Virtual Serial Task
  592. *
  593. * FIXME: Needs doc
  594. */
  595. void virtser_task(void) {
  596. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  597. uint8_t ch;
  598. for (; count; --count) {
  599. ch = CDC_Device_ReceiveByte(&cdc_device);
  600. virtser_recv(ch);
  601. }
  602. }
  603. /** \brief Virtual Serial Send
  604. *
  605. * FIXME: Needs doc
  606. */
  607. void virtser_send(const uint8_t byte) {
  608. uint8_t timeout = 255;
  609. uint8_t ep = Endpoint_GetCurrentEndpoint();
  610. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) {
  611. /* IN packet */
  612. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  613. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  614. Endpoint_SelectEndpoint(ep);
  615. return;
  616. }
  617. while (timeout-- && !Endpoint_IsReadWriteAllowed())
  618. _delay_us(40);
  619. Endpoint_Write_8(byte);
  620. CDC_Device_Flush(&cdc_device);
  621. if (Endpoint_IsINReady()) {
  622. Endpoint_ClearIN();
  623. }
  624. Endpoint_SelectEndpoint(ep);
  625. }
  626. }
  627. #endif
  628. /*******************************************************************************
  629. * main
  630. ******************************************************************************/
  631. /** \brief Setup MCU
  632. *
  633. * FIXME: Needs doc
  634. */
  635. static void setup_mcu(void) {
  636. /* Disable watchdog if enabled by bootloader/fuses */
  637. MCUSR &= ~_BV(WDRF);
  638. wdt_disable();
  639. // For boards running at 3.3V and crystal at 16 MHz
  640. #if (F_CPU == 8000000 && F_USB == 16000000)
  641. /* Divide clock by 2 */
  642. clock_prescale_set(clock_div_2);
  643. #else /* Disable clock division */
  644. clock_prescale_set(clock_div_1);
  645. #endif
  646. }
  647. /** \brief Setup USB
  648. *
  649. * FIXME: Needs doc
  650. */
  651. static void setup_usb(void) {
  652. // Leonardo needs. Without this USB device is not recognized.
  653. USB_Disable();
  654. USB_Init();
  655. // for console_flush_task
  656. USB_Device_EnableSOFEvents();
  657. }
  658. void protocol_setup(void) {
  659. #ifdef MIDI_ENABLE
  660. setup_midi();
  661. #endif
  662. setup_mcu();
  663. usb_device_state_init();
  664. }
  665. void protocol_pre_init(void) {
  666. setup_usb();
  667. sei();
  668. /* wait for USB startup & debug output */
  669. #ifdef USB_WAIT_FOR_ENUMERATION
  670. while (USB_DeviceState != DEVICE_STATE_Configured) {
  671. # if defined(INTERRUPT_CONTROL_ENDPOINT)
  672. ;
  673. # else
  674. USB_USBTask();
  675. # endif
  676. }
  677. print("USB configured.\n");
  678. #else
  679. USB_USBTask();
  680. #endif
  681. }
  682. void protocol_post_init(void) {
  683. host_set_driver(&lufa_driver);
  684. }
  685. void protocol_pre_task(void) {
  686. #if !defined(NO_USB_STARTUP_CHECK)
  687. if (USB_DeviceState == DEVICE_STATE_Suspended) {
  688. dprintln("suspending keyboard");
  689. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  690. suspend_power_down();
  691. if (suspend_wakeup_condition() && USB_Device_RemoteWakeupEnabled) {
  692. USB_Device_SendRemoteWakeup();
  693. clear_keyboard();
  694. # if USB_SUSPEND_WAKEUP_DELAY > 0
  695. // Some hubs, kvm switches, and monitors do
  696. // weird things, with USB device state bouncing
  697. // around wildly on wakeup, yielding race
  698. // conditions that can corrupt the keyboard state.
  699. //
  700. // Pause for a while to let things settle...
  701. wait_ms(USB_SUSPEND_WAKEUP_DELAY);
  702. // ...and then update the wakeup matrix again as the waking key
  703. // might have been released during the delay
  704. update_matrix_state_after_wakeup();
  705. # endif
  706. }
  707. }
  708. suspend_wakeup_init();
  709. }
  710. #endif
  711. }
  712. void protocol_post_task(void) {
  713. #ifdef CONSOLE_ENABLE
  714. console_task();
  715. #endif
  716. #ifdef MIDI_ENABLE
  717. MIDI_Device_USBTask(&USB_MIDI_Interface);
  718. #endif
  719. #ifdef VIRTSER_ENABLE
  720. virtser_task();
  721. CDC_Device_USBTask(&cdc_device);
  722. #endif
  723. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  724. USB_USBTask();
  725. #endif
  726. }
  727. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, const uint16_t wIndex, const void **const DescriptorAddress) {
  728. return get_usb_descriptor(wValue, wIndex, USB_ControlRequest.wLength, DescriptorAddress);
  729. }