lufa.c 29 KB

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