lufa.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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. #ifdef WAIT_FOR_USB
  63. // TODO: Remove backwards compatibility with old define
  64. # define USB_WAIT_FOR_ENUMERATION
  65. #endif
  66. static report_keyboard_t keyboard_report_sent;
  67. /* Host driver */
  68. static void send_keyboard(report_keyboard_t *report);
  69. static void send_nkro(report_nkro_t *report);
  70. static void send_mouse(report_mouse_t *report);
  71. static void send_extra(report_extra_t *report);
  72. host_driver_t lufa_driver = {.keyboard_leds = usb_device_state_get_leds, .send_keyboard = send_keyboard, .send_nkro = send_nkro, .send_mouse = send_mouse, .send_extra = send_extra};
  73. void send_report(uint8_t endpoint, void *report, size_t size) {
  74. uint8_t timeout = 255;
  75. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  76. Endpoint_SelectEndpoint(endpoint);
  77. /* Check if write ready for a polling interval around 10ms */
  78. while (timeout-- && !Endpoint_IsReadWriteAllowed()) {
  79. _delay_us(40);
  80. }
  81. if (!Endpoint_IsReadWriteAllowed()) return;
  82. Endpoint_Write_Stream_LE(report, size, NULL);
  83. Endpoint_ClearIN();
  84. }
  85. #ifdef VIRTSER_ENABLE
  86. // clang-format off
  87. USB_ClassInfo_CDC_Device_t cdc_device = {
  88. .Config = {
  89. .ControlInterfaceNumber = CCI_INTERFACE,
  90. .DataINEndpoint = {
  91. .Address = (CDC_IN_EPNUM | ENDPOINT_DIR_IN),
  92. .Size = CDC_EPSIZE,
  93. .Banks = 1
  94. },
  95. .DataOUTEndpoint = {
  96. .Address = (CDC_OUT_EPNUM | ENDPOINT_DIR_OUT),
  97. .Size = CDC_EPSIZE,
  98. .Banks = 1
  99. },
  100. .NotificationEndpoint = {
  101. .Address = (CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN),
  102. .Size = CDC_NOTIFICATION_EPSIZE,
  103. .Banks = 1
  104. }
  105. }
  106. };
  107. // clang-format on
  108. #endif
  109. #ifdef RAW_ENABLE
  110. /** \brief Raw HID Send
  111. *
  112. * FIXME: Needs doc
  113. */
  114. void raw_hid_send(uint8_t *data, uint8_t length) {
  115. if (length != RAW_EPSIZE) return;
  116. send_report(RAW_IN_EPNUM, data, RAW_EPSIZE);
  117. }
  118. /** \brief Raw HID Receive
  119. *
  120. * FIXME: Needs doc
  121. */
  122. __attribute__((weak)) void raw_hid_receive(uint8_t *data, uint8_t length) {
  123. // Users should #include "raw_hid.h" in their own code
  124. // and implement this function there. Leave this as weak linkage
  125. // so users can opt to not handle data coming in.
  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. #ifdef XAP_ENABLE
  155. extern void xap_receive(xap_token_t token, const uint8_t *data, size_t length);
  156. void xap_send_base(uint8_t *data, uint8_t length) {
  157. // TODO: implement variable size packet
  158. if (length != XAP_EPSIZE) {
  159. return;
  160. }
  161. if (USB_DeviceState != DEVICE_STATE_Configured) {
  162. return;
  163. }
  164. // TODO: decide if we allow calls to raw_hid_send() in the middle
  165. // of other endpoint usage.
  166. uint8_t ep = Endpoint_GetCurrentEndpoint();
  167. Endpoint_SelectEndpoint(XAP_IN_EPNUM);
  168. // Check to see if the host is ready to accept another packet
  169. if (Endpoint_IsINReady()) {
  170. // Write data
  171. Endpoint_Write_Stream_LE(data, XAP_EPSIZE, NULL);
  172. // Finalize the stream transfer to send the last packet
  173. Endpoint_ClearIN();
  174. }
  175. Endpoint_SelectEndpoint(ep);
  176. }
  177. void xap_send(xap_token_t token, xap_response_flags_t response_flags, const void *data, size_t length) {
  178. uint8_t rdata[XAP_EPSIZE] = {0};
  179. xap_response_header_t *header = (xap_response_header_t *)&rdata[0];
  180. header->token = token;
  181. if (length > (XAP_EPSIZE - sizeof(xap_response_header_t))) response_flags &= ~(XAP_RESPONSE_FLAG_SUCCESS);
  182. header->flags = response_flags;
  183. if (response_flags & (XAP_RESPONSE_FLAG_SUCCESS)) {
  184. header->length = (uint8_t)length;
  185. if (data != NULL) {
  186. memcpy(&rdata[sizeof(xap_response_header_t)], data, length);
  187. }
  188. }
  189. xap_send_base(rdata, sizeof(rdata));
  190. }
  191. void xap_broadcast(uint8_t type, const void *data, size_t length) {
  192. uint8_t rdata[XAP_EPSIZE] = {0};
  193. xap_broadcast_header_t *header = (xap_broadcast_header_t *)&rdata[0];
  194. header->token = XAP_BROADCAST_TOKEN;
  195. header->type = type;
  196. if (length > (XAP_EPSIZE - sizeof(xap_broadcast_header_t))) return;
  197. header->length = (uint8_t)length;
  198. if (data != NULL) {
  199. memcpy(&rdata[sizeof(xap_broadcast_header_t)], data, length);
  200. }
  201. xap_send_base(rdata, sizeof(rdata));
  202. }
  203. void xap_receive_base(const void *data) {
  204. const uint8_t * u8data = (const uint8_t *)data;
  205. xap_request_header_t *header = (xap_request_header_t *)&u8data[0];
  206. if (header->length <= (XAP_EPSIZE - sizeof(xap_request_header_t))) {
  207. xap_receive(header->token, &u8data[sizeof(xap_request_header_t)], header->length);
  208. }
  209. }
  210. void xap_task(void) {
  211. // Create a temporary buffer to hold the read in data from the host
  212. uint8_t data[XAP_EPSIZE];
  213. bool data_read = false;
  214. // Device must be connected and configured for the task to run
  215. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  216. Endpoint_SelectEndpoint(XAP_OUT_EPNUM);
  217. // Check to see if a packet has been sent from the host
  218. if (Endpoint_IsOUTReceived()) {
  219. // Check to see if the packet contains data
  220. if (Endpoint_IsReadWriteAllowed()) {
  221. /* Read data */
  222. Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
  223. data_read = true;
  224. }
  225. // Finalize the stream transfer to receive the last packet
  226. Endpoint_ClearOUT();
  227. if (data_read) {
  228. xap_receive_base(data);
  229. }
  230. }
  231. }
  232. #endif // XAP_ENABLE
  233. /*******************************************************************************
  234. * Console
  235. ******************************************************************************/
  236. #ifdef CONSOLE_ENABLE
  237. /** \brief Console Tasks
  238. *
  239. * FIXME: Needs doc
  240. */
  241. static void console_flush_task(void) {
  242. /* Device must be connected and configured for the task to run */
  243. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  244. uint8_t ep = Endpoint_GetCurrentEndpoint();
  245. /* IN packet */
  246. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  247. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  248. Endpoint_SelectEndpoint(ep);
  249. return;
  250. }
  251. // fill empty bank
  252. while (Endpoint_IsReadWriteAllowed())
  253. Endpoint_Write_8(0);
  254. // flush sendchar packet
  255. if (Endpoint_IsINReady()) {
  256. Endpoint_ClearIN();
  257. }
  258. Endpoint_SelectEndpoint(ep);
  259. }
  260. void console_task(void) {
  261. // do nothing
  262. }
  263. #endif
  264. /*******************************************************************************
  265. * USB Events
  266. ******************************************************************************/
  267. /*
  268. * Event Order of Plug in:
  269. * 0) EVENT_USB_Device_Connect
  270. * 1) EVENT_USB_Device_Suspend
  271. * 2) EVENT_USB_Device_Reset
  272. * 3) EVENT_USB_Device_Wake
  273. */
  274. /** \brief Event USB Device Connect
  275. *
  276. * FIXME: Needs doc
  277. */
  278. void EVENT_USB_Device_Connect(void) {
  279. print("[C]");
  280. /* For battery powered device */
  281. if (!USB_IsInitialized) {
  282. USB_Disable();
  283. USB_Init();
  284. USB_Device_EnableSOFEvents();
  285. }
  286. }
  287. /** \brief Event USB Device Connect
  288. *
  289. * FIXME: Needs doc
  290. */
  291. void EVENT_USB_Device_Disconnect(void) {
  292. print("[D]");
  293. /* For battery powered device */
  294. USB_IsInitialized = false;
  295. /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
  296. if (USB_IsInitialized) {
  297. USB_Disable(); // Disable all interrupts
  298. USB_Controller_Enable();
  299. USB_INT_Enable(USB_INT_VBUSTI);
  300. }
  301. */
  302. }
  303. /** \brief Event USB Device Connect
  304. *
  305. * FIXME: Needs doc
  306. */
  307. void EVENT_USB_Device_Reset(void) {
  308. print("[R]");
  309. usb_device_state_set_reset();
  310. usb_device_state_set_protocol(USB_PROTOCOL_REPORT);
  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. usb_device_state_set_leds(Endpoint_Read_8());
  469. }
  470. } else {
  471. usb_device_state_set_leds(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(usb_device_state_get_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. usb_device_state_set_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. usb_device_state_set_idle_rate(USB_ControlRequest.wValue >> 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(usb_device_state_get_idle_rate());
  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 Send Keyboard
  527. *
  528. * FIXME: Needs doc
  529. */
  530. static void send_keyboard(report_keyboard_t *report) {
  531. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  532. if (usb_device_state_get_protocol() == USB_PROTOCOL_BOOT) {
  533. send_report(KEYBOARD_IN_EPNUM, &report->mods, 8);
  534. } else {
  535. send_report(KEYBOARD_IN_EPNUM, report, KEYBOARD_REPORT_SIZE);
  536. }
  537. keyboard_report_sent = *report;
  538. }
  539. /** \brief Send NKRO
  540. *
  541. * FIXME: Needs doc
  542. */
  543. static void send_nkro(report_nkro_t *report) {
  544. #ifdef NKRO_ENABLE
  545. send_report(SHARED_IN_EPNUM, report, sizeof(report_nkro_t));
  546. #endif
  547. }
  548. /** \brief Send Mouse
  549. *
  550. * FIXME: Needs doc
  551. */
  552. static void send_mouse(report_mouse_t *report) {
  553. #ifdef MOUSE_ENABLE
  554. send_report(MOUSE_IN_EPNUM, report, sizeof(report_mouse_t));
  555. #endif
  556. }
  557. /** \brief Send Extra
  558. *
  559. * FIXME: Needs doc
  560. */
  561. static void send_extra(report_extra_t *report) {
  562. #ifdef EXTRAKEY_ENABLE
  563. send_report(SHARED_IN_EPNUM, report, sizeof(report_extra_t));
  564. #endif
  565. }
  566. void send_joystick(report_joystick_t *report) {
  567. #ifdef JOYSTICK_ENABLE
  568. send_report(JOYSTICK_IN_EPNUM, report, sizeof(report_joystick_t));
  569. #endif
  570. }
  571. void send_programmable_button(report_programmable_button_t *report) {
  572. #ifdef PROGRAMMABLE_BUTTON_ENABLE
  573. send_report(SHARED_IN_EPNUM, report, sizeof(report_programmable_button_t));
  574. #endif
  575. }
  576. void send_digitizer(report_digitizer_t *report) {
  577. #ifdef DIGITIZER_ENABLE
  578. send_report(DIGITIZER_IN_EPNUM, report, sizeof(report_digitizer_t));
  579. #endif
  580. }
  581. /*******************************************************************************
  582. * sendchar
  583. ******************************************************************************/
  584. #ifdef CONSOLE_ENABLE
  585. # define SEND_TIMEOUT 5
  586. /** \brief Send Char
  587. *
  588. * FIXME: Needs doc
  589. */
  590. int8_t sendchar(uint8_t c) {
  591. // Do not wait if the previous write has timed_out.
  592. // Because sendchar() is called so many times, waiting each call causes big lag.
  593. // The `timed_out` state is an approximation of the ideal `is_listener_disconnected?` state.
  594. static bool timed_out = false;
  595. // prevents console_flush_task() from running during sendchar() runs.
  596. // or char will be lost. These two function is mutually exclusive.
  597. CONSOLE_FLUSH_SET(false);
  598. if (USB_DeviceState != DEVICE_STATE_Configured) return -1;
  599. uint8_t ep = Endpoint_GetCurrentEndpoint();
  600. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  601. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  602. goto ERROR_EXIT;
  603. }
  604. if (timed_out && !Endpoint_IsReadWriteAllowed()) {
  605. goto ERROR_EXIT;
  606. }
  607. timed_out = false;
  608. uint8_t timeout = SEND_TIMEOUT;
  609. while (!Endpoint_IsReadWriteAllowed()) {
  610. if (USB_DeviceState != DEVICE_STATE_Configured) {
  611. goto ERROR_EXIT;
  612. }
  613. if (Endpoint_IsStalled()) {
  614. goto ERROR_EXIT;
  615. }
  616. if (!(timeout--)) {
  617. timed_out = true;
  618. goto ERROR_EXIT;
  619. }
  620. _delay_ms(1);
  621. }
  622. Endpoint_Write_8(c);
  623. // send when bank is full
  624. if (!Endpoint_IsReadWriteAllowed()) {
  625. while (!(Endpoint_IsINReady()))
  626. ;
  627. Endpoint_ClearIN();
  628. } else {
  629. CONSOLE_FLUSH_SET(true);
  630. }
  631. Endpoint_SelectEndpoint(ep);
  632. return 0;
  633. ERROR_EXIT:
  634. Endpoint_SelectEndpoint(ep);
  635. return -1;
  636. }
  637. #endif
  638. /*******************************************************************************
  639. * MIDI
  640. ******************************************************************************/
  641. #ifdef MIDI_ENABLE
  642. // clang-format off
  643. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface = {
  644. .Config = {
  645. .StreamingInterfaceNumber = AS_INTERFACE,
  646. .DataINEndpoint = {
  647. .Address = (MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN),
  648. .Size = MIDI_STREAM_EPSIZE,
  649. .Banks = 1
  650. },
  651. .DataOUTEndpoint = {
  652. .Address = (MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT),
  653. .Size = MIDI_STREAM_EPSIZE,
  654. .Banks = 1
  655. }
  656. }
  657. };
  658. // clang-format on
  659. void send_midi_packet(MIDI_EventPacket_t *event) {
  660. MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
  661. }
  662. bool recv_midi_packet(MIDI_EventPacket_t *const event) {
  663. return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
  664. }
  665. #endif
  666. /*******************************************************************************
  667. * VIRTUAL SERIAL
  668. ******************************************************************************/
  669. #ifdef VIRTSER_ENABLE
  670. /** \brief Virtual Serial Init
  671. *
  672. * FIXME: Needs doc
  673. */
  674. void virtser_init(void) {
  675. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR;
  676. CDC_Device_SendControlLineStateChange(&cdc_device);
  677. }
  678. /** \brief Virtual Serial Receive
  679. *
  680. * FIXME: Needs doc
  681. */
  682. void virtser_recv(uint8_t c) __attribute__((weak));
  683. void virtser_recv(uint8_t c) {
  684. // Ignore by default
  685. }
  686. /** \brief Virtual Serial Task
  687. *
  688. * FIXME: Needs doc
  689. */
  690. void virtser_task(void) {
  691. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  692. uint8_t ch;
  693. for (; count; --count) {
  694. ch = CDC_Device_ReceiveByte(&cdc_device);
  695. virtser_recv(ch);
  696. }
  697. }
  698. /** \brief Virtual Serial Send
  699. *
  700. * FIXME: Needs doc
  701. */
  702. void virtser_send(const uint8_t byte) {
  703. uint8_t timeout = 255;
  704. uint8_t ep = Endpoint_GetCurrentEndpoint();
  705. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) {
  706. /* IN packet */
  707. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  708. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  709. Endpoint_SelectEndpoint(ep);
  710. return;
  711. }
  712. while (timeout-- && !Endpoint_IsReadWriteAllowed())
  713. _delay_us(40);
  714. Endpoint_Write_8(byte);
  715. CDC_Device_Flush(&cdc_device);
  716. if (Endpoint_IsINReady()) {
  717. Endpoint_ClearIN();
  718. }
  719. Endpoint_SelectEndpoint(ep);
  720. }
  721. }
  722. #endif
  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_flush_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 USB_WAIT_FOR_ENUMERATION
  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. dprintln("suspending keyboard");
  784. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  785. suspend_power_down();
  786. if (suspend_wakeup_condition() && USB_Device_RemoteWakeupEnabled) {
  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 CONSOLE_ENABLE
  806. console_task();
  807. #endif
  808. #ifdef MIDI_ENABLE
  809. MIDI_Device_USBTask(&USB_MIDI_Interface);
  810. #endif
  811. #ifdef VIRTSER_ENABLE
  812. virtser_task();
  813. CDC_Device_USBTask(&cdc_device);
  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, USB_ControlRequest.wLength, DescriptorAddress);
  821. }