lufa.c 29 KB

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