lufa.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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. #include "suspend.h"
  42. #include "wait.h"
  43. #include "usb_descriptor.h"
  44. #include "lufa.h"
  45. #include "usb_device_state.h"
  46. #include <util/atomic.h>
  47. #ifdef VIRTSER_ENABLE
  48. # include "virtser.h"
  49. #endif
  50. #ifdef MIDI_ENABLE
  51. # include "qmk_midi.h"
  52. #endif
  53. #ifdef RAW_ENABLE
  54. # include "raw_hid.h"
  55. #endif
  56. #ifdef XAP_ENABLE
  57. # include "xap.h"
  58. #endif
  59. #ifdef WAIT_FOR_USB
  60. // TODO: Remove backwards compatibility with old define
  61. # define USB_WAIT_FOR_ENUMERATION
  62. #endif
  63. static report_keyboard_t keyboard_report_sent;
  64. /* Host driver */
  65. static void send_keyboard(report_keyboard_t *report);
  66. static void send_nkro(report_nkro_t *report);
  67. static void send_mouse(report_mouse_t *report);
  68. static void send_extra(report_extra_t *report);
  69. #ifdef RAW_ENABLE
  70. static void send_raw_hid(uint8_t *data, uint8_t length);
  71. #endif
  72. host_driver_t lufa_driver = {
  73. .keyboard_leds = usb_device_state_get_leds,
  74. .send_keyboard = send_keyboard,
  75. .send_nkro = send_nkro,
  76. .send_mouse = send_mouse,
  77. .send_extra = send_extra,
  78. #ifdef RAW_ENABLE
  79. .send_raw_hid = send_raw_hid,
  80. #endif
  81. };
  82. void send_report(uint8_t endpoint, void *report, size_t size) {
  83. uint8_t timeout = 255;
  84. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  85. Endpoint_SelectEndpoint(endpoint);
  86. /* Check if write ready for a polling interval around 10ms */
  87. while (timeout-- && !Endpoint_IsReadWriteAllowed()) {
  88. _delay_us(40);
  89. }
  90. if (!Endpoint_IsReadWriteAllowed()) return;
  91. Endpoint_Write_Stream_LE(report, size, NULL);
  92. Endpoint_ClearIN();
  93. }
  94. #ifdef VIRTSER_ENABLE
  95. // clang-format off
  96. USB_ClassInfo_CDC_Device_t cdc_device = {
  97. .Config = {
  98. .ControlInterfaceNumber = CCI_INTERFACE,
  99. .DataINEndpoint = {
  100. .Address = (CDC_IN_EPNUM | ENDPOINT_DIR_IN),
  101. .Size = CDC_EPSIZE,
  102. .Banks = 1
  103. },
  104. .DataOUTEndpoint = {
  105. .Address = (CDC_OUT_EPNUM | ENDPOINT_DIR_OUT),
  106. .Size = CDC_EPSIZE,
  107. .Banks = 1
  108. },
  109. .NotificationEndpoint = {
  110. .Address = (CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN),
  111. .Size = CDC_NOTIFICATION_EPSIZE,
  112. .Banks = 1
  113. }
  114. }
  115. };
  116. // clang-format on
  117. #endif
  118. #ifdef RAW_ENABLE
  119. /** \brief Raw HID Send
  120. *
  121. * FIXME: Needs doc
  122. */
  123. static void send_raw_hid(uint8_t *data, uint8_t length) {
  124. if (length != RAW_EPSIZE) return;
  125. send_report(RAW_IN_EPNUM, data, RAW_EPSIZE);
  126. }
  127. /** \brief Raw HID Task
  128. *
  129. * FIXME: Needs doc
  130. */
  131. void raw_hid_task(void) {
  132. // Create a temporary buffer to hold the read in data from the host
  133. uint8_t data[RAW_EPSIZE];
  134. bool data_read = false;
  135. // Device must be connected and configured for the task to run
  136. if (USB_DeviceState != DEVICE_STATE_Configured) return;
  137. Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
  138. // Check to see if a packet has been sent from the host
  139. if (Endpoint_IsOUTReceived()) {
  140. // Check to see if the packet contains data
  141. if (Endpoint_IsReadWriteAllowed()) {
  142. /* Read data */
  143. Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
  144. data_read = true;
  145. }
  146. // Finalize the stream transfer to receive the last packet
  147. Endpoint_ClearOUT();
  148. if (data_read) {
  149. raw_hid_receive(data, sizeof(data));
  150. }
  151. }
  152. }
  153. #endif
  154. #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. }
  320. /** \brief Event USB Device Connect
  321. *
  322. * FIXME: Needs doc
  323. */
  324. void EVENT_USB_Device_WakeUp(void) {
  325. print("[W]");
  326. #if defined(NO_USB_STARTUP_CHECK)
  327. suspend_wakeup_init();
  328. #endif
  329. usb_device_state_set_resume(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  330. }
  331. #ifdef CONSOLE_ENABLE
  332. static bool console_flush = false;
  333. # define CONSOLE_FLUSH_SET(b) \
  334. do { \
  335. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { \
  336. console_flush = b; \
  337. } \
  338. } while (0)
  339. /** \brief Event USB Device Start Of Frame
  340. *
  341. * FIXME: Needs doc
  342. * called every 1ms
  343. */
  344. void EVENT_USB_Device_StartOfFrame(void) {
  345. static uint8_t count;
  346. if (++count % 50) return;
  347. count = 0;
  348. if (!console_flush) return;
  349. console_flush_task();
  350. console_flush = false;
  351. }
  352. #endif
  353. /** \brief Event handler for the USB_ConfigurationChanged event.
  354. *
  355. * This is fired when the host sets the current configuration of the USB device after enumeration.
  356. *
  357. * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
  358. * it is safe to use single bank for all endpoints.
  359. */
  360. void EVENT_USB_Device_ConfigurationChanged(void) {
  361. bool ConfigSuccess = true;
  362. #ifndef KEYBOARD_SHARED_EP
  363. /* Setup keyboard report endpoint */
  364. ConfigSuccess &= Endpoint_ConfigureEndpoint((KEYBOARD_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, KEYBOARD_EPSIZE, 1);
  365. #endif
  366. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  367. /* Setup mouse report endpoint */
  368. ConfigSuccess &= Endpoint_ConfigureEndpoint((MOUSE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, MOUSE_EPSIZE, 1);
  369. #endif
  370. #ifdef SHARED_EP_ENABLE
  371. /* Setup shared report endpoint */
  372. ConfigSuccess &= Endpoint_ConfigureEndpoint((SHARED_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, SHARED_EPSIZE, 1);
  373. #endif
  374. #ifdef RAW_ENABLE
  375. /* Setup raw HID endpoints */
  376. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  377. ConfigSuccess &= Endpoint_ConfigureEndpoint((RAW_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, RAW_EPSIZE, 1);
  378. #endif
  379. #ifdef PLOVER_HID_ENABLE
  380. /* Setup plover HID endpoints */
  381. ConfigSuccess &= Endpoint_ConfigureEndpoint((PLOVER_HID_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, PLOVER_HID_EPSIZE, 1);
  382. #endif
  383. #ifdef CONSOLE_ENABLE
  384. /* Setup console endpoint */
  385. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  386. #endif
  387. #ifdef MIDI_ENABLE
  388. /* Setup MIDI stream endpoints */
  389. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  390. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  391. #endif
  392. #ifdef VIRTSER_ENABLE
  393. /* Setup virtual serial endpoints */
  394. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
  395. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, CDC_EPSIZE, 1);
  396. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, CDC_EPSIZE, 1);
  397. #endif
  398. #if defined(JOYSTICK_ENABLE) && !defined(JOYSTICK_SHARED_EP)
  399. /* Setup joystick endpoint */
  400. ConfigSuccess &= Endpoint_ConfigureEndpoint((JOYSTICK_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
  401. #endif
  402. #if defined(DIGITIZER_ENABLE) && !defined(DIGITIZER_SHARED_EP)
  403. /* Setup digitizer endpoint */
  404. ConfigSuccess &= Endpoint_ConfigureEndpoint((DIGITIZER_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, DIGITIZER_EPSIZE, 1);
  405. #endif
  406. #ifdef XAP_ENABLE
  407. /* Setup XAP endpoints */
  408. ConfigSuccess &= Endpoint_ConfigureEndpoint((XAP_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, XAP_EPSIZE, 1);
  409. ConfigSuccess &= Endpoint_ConfigureEndpoint((XAP_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, XAP_EPSIZE, 1);
  410. #endif // XAP_ENABLE
  411. usb_device_state_set_configuration(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  412. }
  413. /* FIXME: Expose this table in the docs somehow
  414. Appendix G: HID Request Support Requirements
  415. The following table enumerates the requests that need to be supported by various types of HID class devices.
  416. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  417. ------------------------------------------------------------------------------------------
  418. Boot Mouse Required Optional Optional Optional Required Required
  419. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  420. Boot Keyboard Required Optional Required Required Required Required
  421. Non-Boot Keybrd Required Optional Required Required Optional Optional
  422. Other Device Required Optional Optional Optional Optional Optional
  423. */
  424. /** \brief Event handler for the USB_ControlRequest event.
  425. *
  426. * This is fired before passing along unhandled control requests to the library for processing internally.
  427. */
  428. void EVENT_USB_Device_ControlRequest(void) {
  429. uint8_t *ReportData = NULL;
  430. uint8_t ReportSize = 0;
  431. /* Handle HID Class specific requests */
  432. switch (USB_ControlRequest.bRequest) {
  433. case HID_REQ_GetReport:
  434. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  435. Endpoint_ClearSETUP();
  436. // Interface
  437. switch (USB_ControlRequest.wIndex) {
  438. case KEYBOARD_INTERFACE:
  439. // TODO: test/check
  440. ReportData = (uint8_t *)&keyboard_report_sent;
  441. ReportSize = sizeof(keyboard_report_sent);
  442. break;
  443. }
  444. /* Write the report data to the control endpoint */
  445. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  446. Endpoint_ClearOUT();
  447. }
  448. break;
  449. case HID_REQ_SetReport:
  450. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  451. // Interface
  452. switch (USB_ControlRequest.wIndex) {
  453. case KEYBOARD_INTERFACE:
  454. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  455. case SHARED_INTERFACE:
  456. #endif
  457. Endpoint_ClearSETUP();
  458. while (!(Endpoint_IsOUTReceived())) {
  459. if (USB_DeviceState == DEVICE_STATE_Unattached) return;
  460. }
  461. if (Endpoint_BytesInEndpoint() == 2) {
  462. uint8_t report_id = Endpoint_Read_8();
  463. if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
  464. usb_device_state_set_leds(Endpoint_Read_8());
  465. }
  466. } else {
  467. usb_device_state_set_leds(Endpoint_Read_8());
  468. }
  469. Endpoint_ClearOUT();
  470. Endpoint_ClearStatusStage();
  471. break;
  472. }
  473. }
  474. break;
  475. case HID_REQ_GetProtocol:
  476. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  477. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  478. Endpoint_ClearSETUP();
  479. while (!(Endpoint_IsINReady()))
  480. ;
  481. Endpoint_Write_8(usb_device_state_get_protocol());
  482. Endpoint_ClearIN();
  483. Endpoint_ClearStatusStage();
  484. }
  485. }
  486. break;
  487. case HID_REQ_SetProtocol:
  488. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  489. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  490. Endpoint_ClearSETUP();
  491. Endpoint_ClearStatusStage();
  492. usb_device_state_set_protocol(USB_ControlRequest.wValue & 0xFF);
  493. clear_keyboard();
  494. }
  495. }
  496. break;
  497. case HID_REQ_SetIdle:
  498. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  499. Endpoint_ClearSETUP();
  500. Endpoint_ClearStatusStage();
  501. usb_device_state_set_idle_rate(USB_ControlRequest.wValue >> 8);
  502. }
  503. break;
  504. case HID_REQ_GetIdle:
  505. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  506. Endpoint_ClearSETUP();
  507. while (!(Endpoint_IsINReady()))
  508. ;
  509. Endpoint_Write_8(usb_device_state_get_idle_rate());
  510. Endpoint_ClearIN();
  511. Endpoint_ClearStatusStage();
  512. }
  513. break;
  514. }
  515. #ifdef VIRTSER_ENABLE
  516. CDC_Device_ProcessControlRequest(&cdc_device);
  517. #endif
  518. }
  519. /*******************************************************************************
  520. * Host driver
  521. ******************************************************************************/
  522. /** \brief Send Keyboard
  523. *
  524. * FIXME: Needs doc
  525. */
  526. static void send_keyboard(report_keyboard_t *report) {
  527. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  528. if (usb_device_state_get_protocol() == USB_PROTOCOL_BOOT) {
  529. send_report(KEYBOARD_IN_EPNUM, &report->mods, 8);
  530. } else {
  531. send_report(KEYBOARD_IN_EPNUM, report, KEYBOARD_REPORT_SIZE);
  532. }
  533. keyboard_report_sent = *report;
  534. }
  535. /** \brief Send NKRO
  536. *
  537. * FIXME: Needs doc
  538. */
  539. static void send_nkro(report_nkro_t *report) {
  540. #ifdef NKRO_ENABLE
  541. send_report(SHARED_IN_EPNUM, report, sizeof(report_nkro_t));
  542. #endif
  543. }
  544. /** \brief Send Mouse
  545. *
  546. * FIXME: Needs doc
  547. */
  548. static void send_mouse(report_mouse_t *report) {
  549. #ifdef MOUSE_ENABLE
  550. send_report(MOUSE_IN_EPNUM, report, sizeof(report_mouse_t));
  551. #endif
  552. }
  553. /** \brief Send Extra
  554. *
  555. * FIXME: Needs doc
  556. */
  557. static void send_extra(report_extra_t *report) {
  558. #ifdef EXTRAKEY_ENABLE
  559. send_report(SHARED_IN_EPNUM, report, sizeof(report_extra_t));
  560. #endif
  561. }
  562. void send_joystick(report_joystick_t *report) {
  563. #ifdef JOYSTICK_ENABLE
  564. send_report(JOYSTICK_IN_EPNUM, report, sizeof(report_joystick_t));
  565. #endif
  566. }
  567. void send_programmable_button(report_programmable_button_t *report) {
  568. #ifdef PROGRAMMABLE_BUTTON_ENABLE
  569. send_report(SHARED_IN_EPNUM, report, sizeof(report_programmable_button_t));
  570. #endif
  571. }
  572. void send_digitizer(report_digitizer_t *report) {
  573. #ifdef DIGITIZER_ENABLE
  574. send_report(DIGITIZER_IN_EPNUM, report, sizeof(report_digitizer_t));
  575. #endif
  576. }
  577. void send_plover_hid(report_plover_hid_t *report) {
  578. #ifdef PLOVER_HID_ENABLE
  579. send_report(PLOVER_HID_IN_EPNUM, report, sizeof(report_plover_hid_t));
  580. #endif
  581. }
  582. /*******************************************************************************
  583. * sendchar
  584. ******************************************************************************/
  585. #ifdef CONSOLE_ENABLE
  586. # define SEND_TIMEOUT 5
  587. /** \brief Send Char
  588. *
  589. * FIXME: Needs doc
  590. */
  591. int8_t sendchar(uint8_t c) {
  592. // Do not wait if the previous write has timed_out.
  593. // Because sendchar() is called so many times, waiting each call causes big lag.
  594. // The `timed_out` state is an approximation of the ideal `is_listener_disconnected?` state.
  595. static bool timed_out = false;
  596. // prevents console_flush_task() from running during sendchar() runs.
  597. // or char will be lost. These two function is mutually exclusive.
  598. CONSOLE_FLUSH_SET(false);
  599. if (USB_DeviceState != DEVICE_STATE_Configured) return -1;
  600. uint8_t ep = Endpoint_GetCurrentEndpoint();
  601. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  602. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  603. goto ERROR_EXIT;
  604. }
  605. if (timed_out && !Endpoint_IsReadWriteAllowed()) {
  606. goto ERROR_EXIT;
  607. }
  608. timed_out = false;
  609. uint8_t timeout = SEND_TIMEOUT;
  610. while (!Endpoint_IsReadWriteAllowed()) {
  611. if (USB_DeviceState != DEVICE_STATE_Configured) {
  612. goto ERROR_EXIT;
  613. }
  614. if (Endpoint_IsStalled()) {
  615. goto ERROR_EXIT;
  616. }
  617. if (!(timeout--)) {
  618. timed_out = true;
  619. goto ERROR_EXIT;
  620. }
  621. _delay_ms(1);
  622. }
  623. Endpoint_Write_8(c);
  624. // send when bank is full
  625. if (!Endpoint_IsReadWriteAllowed()) {
  626. while (!(Endpoint_IsINReady()))
  627. ;
  628. Endpoint_ClearIN();
  629. } else {
  630. CONSOLE_FLUSH_SET(true);
  631. }
  632. Endpoint_SelectEndpoint(ep);
  633. return 0;
  634. ERROR_EXIT:
  635. Endpoint_SelectEndpoint(ep);
  636. return -1;
  637. }
  638. #endif
  639. /*******************************************************************************
  640. * MIDI
  641. ******************************************************************************/
  642. #ifdef MIDI_ENABLE
  643. // clang-format off
  644. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface = {
  645. .Config = {
  646. .StreamingInterfaceNumber = AS_INTERFACE,
  647. .DataINEndpoint = {
  648. .Address = (MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN),
  649. .Size = MIDI_STREAM_EPSIZE,
  650. .Banks = 1
  651. },
  652. .DataOUTEndpoint = {
  653. .Address = (MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT),
  654. .Size = MIDI_STREAM_EPSIZE,
  655. .Banks = 1
  656. }
  657. }
  658. };
  659. // clang-format on
  660. void send_midi_packet(MIDI_EventPacket_t *event) {
  661. MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
  662. }
  663. bool recv_midi_packet(MIDI_EventPacket_t *const event) {
  664. return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
  665. }
  666. #endif
  667. /*******************************************************************************
  668. * VIRTUAL SERIAL
  669. ******************************************************************************/
  670. #ifdef VIRTSER_ENABLE
  671. /** \brief Virtual Serial Init
  672. *
  673. * FIXME: Needs doc
  674. */
  675. void virtser_init(void) {
  676. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR;
  677. CDC_Device_SendControlLineStateChange(&cdc_device);
  678. }
  679. /** \brief Virtual Serial Receive
  680. *
  681. * FIXME: Needs doc
  682. */
  683. void virtser_recv(uint8_t c) __attribute__((weak));
  684. void virtser_recv(uint8_t c) {
  685. // Ignore by default
  686. }
  687. /** \brief Virtual Serial Task
  688. *
  689. * FIXME: Needs doc
  690. */
  691. void virtser_task(void) {
  692. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  693. uint8_t ch;
  694. for (; count; --count) {
  695. ch = CDC_Device_ReceiveByte(&cdc_device);
  696. virtser_recv(ch);
  697. }
  698. }
  699. /** \brief Virtual Serial Send
  700. *
  701. * FIXME: Needs doc
  702. */
  703. void virtser_send(const uint8_t byte) {
  704. uint8_t timeout = 255;
  705. uint8_t ep = Endpoint_GetCurrentEndpoint();
  706. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) {
  707. /* IN packet */
  708. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  709. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  710. Endpoint_SelectEndpoint(ep);
  711. return;
  712. }
  713. while (timeout-- && !Endpoint_IsReadWriteAllowed())
  714. _delay_us(40);
  715. Endpoint_Write_8(byte);
  716. CDC_Device_Flush(&cdc_device);
  717. if (Endpoint_IsINReady()) {
  718. Endpoint_ClearIN();
  719. }
  720. Endpoint_SelectEndpoint(ep);
  721. }
  722. }
  723. #endif
  724. /*******************************************************************************
  725. * main
  726. ******************************************************************************/
  727. /** \brief Setup MCU
  728. *
  729. * FIXME: Needs doc
  730. */
  731. static void setup_mcu(void) {
  732. /* Disable watchdog if enabled by bootloader/fuses */
  733. MCUSR &= ~_BV(WDRF);
  734. wdt_disable();
  735. // For boards running at 3.3V and crystal at 16 MHz
  736. #if (F_CPU == 8000000 && F_USB == 16000000)
  737. /* Divide clock by 2 */
  738. clock_prescale_set(clock_div_2);
  739. #else /* Disable clock division */
  740. clock_prescale_set(clock_div_1);
  741. #endif
  742. }
  743. /** \brief Setup USB
  744. *
  745. * FIXME: Needs doc
  746. */
  747. static void setup_usb(void) {
  748. // Leonardo needs. Without this USB device is not recognized.
  749. USB_Disable();
  750. USB_Init();
  751. // for console_flush_task
  752. USB_Device_EnableSOFEvents();
  753. }
  754. void protocol_setup(void) {
  755. #ifdef MIDI_ENABLE
  756. setup_midi();
  757. #endif
  758. setup_mcu();
  759. usb_device_state_init();
  760. }
  761. void protocol_pre_init(void) {
  762. setup_usb();
  763. sei();
  764. /* wait for USB startup & debug output */
  765. #ifdef USB_WAIT_FOR_ENUMERATION
  766. while (USB_DeviceState != DEVICE_STATE_Configured) {
  767. # if defined(INTERRUPT_CONTROL_ENDPOINT)
  768. ;
  769. # else
  770. USB_USBTask();
  771. # endif
  772. }
  773. print("USB configured.\n");
  774. #else
  775. USB_USBTask();
  776. #endif
  777. }
  778. void protocol_post_init(void) {
  779. host_set_driver(&lufa_driver);
  780. }
  781. void protocol_pre_task(void) {
  782. #if !defined(NO_USB_STARTUP_CHECK)
  783. if (USB_DeviceState == DEVICE_STATE_Suspended) {
  784. dprintln("suspending keyboard");
  785. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  786. suspend_power_down();
  787. if (suspend_wakeup_condition() && USB_Device_RemoteWakeupEnabled) {
  788. USB_Device_SendRemoteWakeup();
  789. clear_keyboard();
  790. # if USB_SUSPEND_WAKEUP_DELAY > 0
  791. // Some hubs, kvm switches, and monitors do
  792. // weird things, with USB device state bouncing
  793. // around wildly on wakeup, yielding race
  794. // conditions that can corrupt the keyboard state.
  795. //
  796. // Pause for a while to let things settle...
  797. wait_ms(USB_SUSPEND_WAKEUP_DELAY);
  798. // ...and then update the wakeup matrix again as the waking key
  799. // might have been released during the delay
  800. update_matrix_state_after_wakeup();
  801. # endif
  802. }
  803. }
  804. suspend_wakeup_init();
  805. }
  806. #endif
  807. }
  808. void protocol_post_task(void) {
  809. #ifdef CONSOLE_ENABLE
  810. console_task();
  811. #endif
  812. #ifdef MIDI_ENABLE
  813. MIDI_Device_USBTask(&USB_MIDI_Interface);
  814. #endif
  815. #ifdef VIRTSER_ENABLE
  816. virtser_task();
  817. CDC_Device_USBTask(&cdc_device);
  818. #endif
  819. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  820. USB_USBTask();
  821. #endif
  822. }
  823. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, const uint16_t wIndex, const void **const DescriptorAddress) {
  824. return get_usb_descriptor(wValue, wIndex, USB_ControlRequest.wLength, DescriptorAddress);
  825. }