lufa.c 28 KB

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