logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

lufa.c (25641B)


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