lufa.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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 CONSOLE_ENABLE
  380. /* Setup console endpoint */
  381. ConfigSuccess &= Endpoint_ConfigureEndpoint((CONSOLE_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CONSOLE_EPSIZE, 1);
  382. #endif
  383. #ifdef MIDI_ENABLE
  384. /* Setup MIDI stream endpoints */
  385. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  386. ConfigSuccess &= Endpoint_ConfigureEndpoint((MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, MIDI_STREAM_EPSIZE, 1);
  387. #endif
  388. #ifdef VIRTSER_ENABLE
  389. /* Setup virtual serial endpoints */
  390. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_NOTIFICATION_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
  391. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_BULK, CDC_EPSIZE, 1);
  392. ConfigSuccess &= Endpoint_ConfigureEndpoint((CDC_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_BULK, CDC_EPSIZE, 1);
  393. #endif
  394. #if defined(JOYSTICK_ENABLE) && !defined(JOYSTICK_SHARED_EP)
  395. /* Setup joystick endpoint */
  396. ConfigSuccess &= Endpoint_ConfigureEndpoint((JOYSTICK_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
  397. #endif
  398. #if defined(DIGITIZER_ENABLE) && !defined(DIGITIZER_SHARED_EP)
  399. /* Setup digitizer endpoint */
  400. ConfigSuccess &= Endpoint_ConfigureEndpoint((DIGITIZER_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, DIGITIZER_EPSIZE, 1);
  401. #endif
  402. #ifdef XAP_ENABLE
  403. /* Setup XAP endpoints */
  404. ConfigSuccess &= Endpoint_ConfigureEndpoint((XAP_IN_EPNUM | ENDPOINT_DIR_IN), EP_TYPE_INTERRUPT, XAP_EPSIZE, 1);
  405. ConfigSuccess &= Endpoint_ConfigureEndpoint((XAP_OUT_EPNUM | ENDPOINT_DIR_OUT), EP_TYPE_INTERRUPT, XAP_EPSIZE, 1);
  406. #endif // XAP_ENABLE
  407. usb_device_state_set_configuration(USB_DeviceState == DEVICE_STATE_Configured, USB_Device_ConfigurationNumber);
  408. }
  409. /* FIXME: Expose this table in the docs somehow
  410. Appendix G: HID Request Support Requirements
  411. The following table enumerates the requests that need to be supported by various types of HID class devices.
  412. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  413. ------------------------------------------------------------------------------------------
  414. Boot Mouse Required Optional Optional Optional Required Required
  415. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  416. Boot Keyboard Required Optional Required Required Required Required
  417. Non-Boot Keybrd Required Optional Required Required Optional Optional
  418. Other Device Required Optional Optional Optional Optional Optional
  419. */
  420. /** \brief Event handler for the USB_ControlRequest event.
  421. *
  422. * This is fired before passing along unhandled control requests to the library for processing internally.
  423. */
  424. void EVENT_USB_Device_ControlRequest(void) {
  425. uint8_t *ReportData = NULL;
  426. uint8_t ReportSize = 0;
  427. /* Handle HID Class specific requests */
  428. switch (USB_ControlRequest.bRequest) {
  429. case HID_REQ_GetReport:
  430. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  431. Endpoint_ClearSETUP();
  432. // Interface
  433. switch (USB_ControlRequest.wIndex) {
  434. case KEYBOARD_INTERFACE:
  435. // TODO: test/check
  436. ReportData = (uint8_t *)&keyboard_report_sent;
  437. ReportSize = sizeof(keyboard_report_sent);
  438. break;
  439. }
  440. /* Write the report data to the control endpoint */
  441. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  442. Endpoint_ClearOUT();
  443. }
  444. break;
  445. case HID_REQ_SetReport:
  446. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  447. // Interface
  448. switch (USB_ControlRequest.wIndex) {
  449. case KEYBOARD_INTERFACE:
  450. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  451. case SHARED_INTERFACE:
  452. #endif
  453. Endpoint_ClearSETUP();
  454. while (!(Endpoint_IsOUTReceived())) {
  455. if (USB_DeviceState == DEVICE_STATE_Unattached) return;
  456. }
  457. if (Endpoint_BytesInEndpoint() == 2) {
  458. uint8_t report_id = Endpoint_Read_8();
  459. if (report_id == REPORT_ID_KEYBOARD || report_id == REPORT_ID_NKRO) {
  460. usb_device_state_set_leds(Endpoint_Read_8());
  461. }
  462. } else {
  463. usb_device_state_set_leds(Endpoint_Read_8());
  464. }
  465. Endpoint_ClearOUT();
  466. Endpoint_ClearStatusStage();
  467. break;
  468. }
  469. }
  470. break;
  471. case HID_REQ_GetProtocol:
  472. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  473. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  474. Endpoint_ClearSETUP();
  475. while (!(Endpoint_IsINReady()))
  476. ;
  477. Endpoint_Write_8(usb_device_state_get_protocol());
  478. Endpoint_ClearIN();
  479. Endpoint_ClearStatusStage();
  480. }
  481. }
  482. break;
  483. case HID_REQ_SetProtocol:
  484. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  485. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  486. Endpoint_ClearSETUP();
  487. Endpoint_ClearStatusStage();
  488. usb_device_state_set_protocol(USB_ControlRequest.wValue & 0xFF);
  489. clear_keyboard();
  490. }
  491. }
  492. break;
  493. case HID_REQ_SetIdle:
  494. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) {
  495. Endpoint_ClearSETUP();
  496. Endpoint_ClearStatusStage();
  497. usb_device_state_set_idle_rate(USB_ControlRequest.wValue >> 8);
  498. }
  499. break;
  500. case HID_REQ_GetIdle:
  501. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) {
  502. Endpoint_ClearSETUP();
  503. while (!(Endpoint_IsINReady()))
  504. ;
  505. Endpoint_Write_8(usb_device_state_get_idle_rate());
  506. Endpoint_ClearIN();
  507. Endpoint_ClearStatusStage();
  508. }
  509. break;
  510. }
  511. #ifdef VIRTSER_ENABLE
  512. CDC_Device_ProcessControlRequest(&cdc_device);
  513. #endif
  514. }
  515. /*******************************************************************************
  516. * Host driver
  517. ******************************************************************************/
  518. /** \brief Send Keyboard
  519. *
  520. * FIXME: Needs doc
  521. */
  522. static void send_keyboard(report_keyboard_t *report) {
  523. /* If we're in Boot Protocol, don't send any report ID or other funky fields */
  524. if (usb_device_state_get_protocol() == USB_PROTOCOL_BOOT) {
  525. send_report(KEYBOARD_IN_EPNUM, &report->mods, 8);
  526. } else {
  527. send_report(KEYBOARD_IN_EPNUM, report, KEYBOARD_REPORT_SIZE);
  528. }
  529. keyboard_report_sent = *report;
  530. }
  531. /** \brief Send NKRO
  532. *
  533. * FIXME: Needs doc
  534. */
  535. static void send_nkro(report_nkro_t *report) {
  536. #ifdef NKRO_ENABLE
  537. send_report(SHARED_IN_EPNUM, report, sizeof(report_nkro_t));
  538. #endif
  539. }
  540. /** \brief Send Mouse
  541. *
  542. * FIXME: Needs doc
  543. */
  544. static void send_mouse(report_mouse_t *report) {
  545. #ifdef MOUSE_ENABLE
  546. send_report(MOUSE_IN_EPNUM, report, sizeof(report_mouse_t));
  547. #endif
  548. }
  549. /** \brief Send Extra
  550. *
  551. * FIXME: Needs doc
  552. */
  553. static void send_extra(report_extra_t *report) {
  554. #ifdef EXTRAKEY_ENABLE
  555. send_report(SHARED_IN_EPNUM, report, sizeof(report_extra_t));
  556. #endif
  557. }
  558. void send_joystick(report_joystick_t *report) {
  559. #ifdef JOYSTICK_ENABLE
  560. send_report(JOYSTICK_IN_EPNUM, report, sizeof(report_joystick_t));
  561. #endif
  562. }
  563. void send_programmable_button(report_programmable_button_t *report) {
  564. #ifdef PROGRAMMABLE_BUTTON_ENABLE
  565. send_report(SHARED_IN_EPNUM, report, sizeof(report_programmable_button_t));
  566. #endif
  567. }
  568. void send_digitizer(report_digitizer_t *report) {
  569. #ifdef DIGITIZER_ENABLE
  570. send_report(DIGITIZER_IN_EPNUM, report, sizeof(report_digitizer_t));
  571. #endif
  572. }
  573. /*******************************************************************************
  574. * sendchar
  575. ******************************************************************************/
  576. #ifdef CONSOLE_ENABLE
  577. # define SEND_TIMEOUT 5
  578. /** \brief Send Char
  579. *
  580. * FIXME: Needs doc
  581. */
  582. int8_t sendchar(uint8_t c) {
  583. // Do not wait if the previous write has timed_out.
  584. // Because sendchar() is called so many times, waiting each call causes big lag.
  585. // The `timed_out` state is an approximation of the ideal `is_listener_disconnected?` state.
  586. static bool timed_out = false;
  587. // prevents console_flush_task() from running during sendchar() runs.
  588. // or char will be lost. These two function is mutually exclusive.
  589. CONSOLE_FLUSH_SET(false);
  590. if (USB_DeviceState != DEVICE_STATE_Configured) return -1;
  591. uint8_t ep = Endpoint_GetCurrentEndpoint();
  592. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  593. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  594. goto ERROR_EXIT;
  595. }
  596. if (timed_out && !Endpoint_IsReadWriteAllowed()) {
  597. goto ERROR_EXIT;
  598. }
  599. timed_out = false;
  600. uint8_t timeout = SEND_TIMEOUT;
  601. while (!Endpoint_IsReadWriteAllowed()) {
  602. if (USB_DeviceState != DEVICE_STATE_Configured) {
  603. goto ERROR_EXIT;
  604. }
  605. if (Endpoint_IsStalled()) {
  606. goto ERROR_EXIT;
  607. }
  608. if (!(timeout--)) {
  609. timed_out = true;
  610. goto ERROR_EXIT;
  611. }
  612. _delay_ms(1);
  613. }
  614. Endpoint_Write_8(c);
  615. // send when bank is full
  616. if (!Endpoint_IsReadWriteAllowed()) {
  617. while (!(Endpoint_IsINReady()))
  618. ;
  619. Endpoint_ClearIN();
  620. } else {
  621. CONSOLE_FLUSH_SET(true);
  622. }
  623. Endpoint_SelectEndpoint(ep);
  624. return 0;
  625. ERROR_EXIT:
  626. Endpoint_SelectEndpoint(ep);
  627. return -1;
  628. }
  629. #endif
  630. /*******************************************************************************
  631. * MIDI
  632. ******************************************************************************/
  633. #ifdef MIDI_ENABLE
  634. // clang-format off
  635. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface = {
  636. .Config = {
  637. .StreamingInterfaceNumber = AS_INTERFACE,
  638. .DataINEndpoint = {
  639. .Address = (MIDI_STREAM_IN_EPNUM | ENDPOINT_DIR_IN),
  640. .Size = MIDI_STREAM_EPSIZE,
  641. .Banks = 1
  642. },
  643. .DataOUTEndpoint = {
  644. .Address = (MIDI_STREAM_OUT_EPNUM | ENDPOINT_DIR_OUT),
  645. .Size = MIDI_STREAM_EPSIZE,
  646. .Banks = 1
  647. }
  648. }
  649. };
  650. // clang-format on
  651. void send_midi_packet(MIDI_EventPacket_t *event) {
  652. MIDI_Device_SendEventPacket(&USB_MIDI_Interface, event);
  653. }
  654. bool recv_midi_packet(MIDI_EventPacket_t *const event) {
  655. return MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, event);
  656. }
  657. #endif
  658. /*******************************************************************************
  659. * VIRTUAL SERIAL
  660. ******************************************************************************/
  661. #ifdef VIRTSER_ENABLE
  662. /** \brief Virtual Serial Init
  663. *
  664. * FIXME: Needs doc
  665. */
  666. void virtser_init(void) {
  667. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR;
  668. CDC_Device_SendControlLineStateChange(&cdc_device);
  669. }
  670. /** \brief Virtual Serial Receive
  671. *
  672. * FIXME: Needs doc
  673. */
  674. void virtser_recv(uint8_t c) __attribute__((weak));
  675. void virtser_recv(uint8_t c) {
  676. // Ignore by default
  677. }
  678. /** \brief Virtual Serial Task
  679. *
  680. * FIXME: Needs doc
  681. */
  682. void virtser_task(void) {
  683. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  684. uint8_t ch;
  685. for (; count; --count) {
  686. ch = CDC_Device_ReceiveByte(&cdc_device);
  687. virtser_recv(ch);
  688. }
  689. }
  690. /** \brief Virtual Serial Send
  691. *
  692. * FIXME: Needs doc
  693. */
  694. void virtser_send(const uint8_t byte) {
  695. uint8_t timeout = 255;
  696. uint8_t ep = Endpoint_GetCurrentEndpoint();
  697. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) {
  698. /* IN packet */
  699. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  700. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  701. Endpoint_SelectEndpoint(ep);
  702. return;
  703. }
  704. while (timeout-- && !Endpoint_IsReadWriteAllowed())
  705. _delay_us(40);
  706. Endpoint_Write_8(byte);
  707. CDC_Device_Flush(&cdc_device);
  708. if (Endpoint_IsINReady()) {
  709. Endpoint_ClearIN();
  710. }
  711. Endpoint_SelectEndpoint(ep);
  712. }
  713. }
  714. #endif
  715. /*******************************************************************************
  716. * main
  717. ******************************************************************************/
  718. /** \brief Setup MCU
  719. *
  720. * FIXME: Needs doc
  721. */
  722. static void setup_mcu(void) {
  723. /* Disable watchdog if enabled by bootloader/fuses */
  724. MCUSR &= ~_BV(WDRF);
  725. wdt_disable();
  726. // For boards running at 3.3V and crystal at 16 MHz
  727. #if (F_CPU == 8000000 && F_USB == 16000000)
  728. /* Divide clock by 2 */
  729. clock_prescale_set(clock_div_2);
  730. #else /* Disable clock division */
  731. clock_prescale_set(clock_div_1);
  732. #endif
  733. }
  734. /** \brief Setup USB
  735. *
  736. * FIXME: Needs doc
  737. */
  738. static void setup_usb(void) {
  739. // Leonardo needs. Without this USB device is not recognized.
  740. USB_Disable();
  741. USB_Init();
  742. // for console_flush_task
  743. USB_Device_EnableSOFEvents();
  744. }
  745. void protocol_setup(void) {
  746. #ifdef MIDI_ENABLE
  747. setup_midi();
  748. #endif
  749. setup_mcu();
  750. usb_device_state_init();
  751. }
  752. void protocol_pre_init(void) {
  753. setup_usb();
  754. sei();
  755. /* wait for USB startup & debug output */
  756. #ifdef USB_WAIT_FOR_ENUMERATION
  757. while (USB_DeviceState != DEVICE_STATE_Configured) {
  758. # if defined(INTERRUPT_CONTROL_ENDPOINT)
  759. ;
  760. # else
  761. USB_USBTask();
  762. # endif
  763. }
  764. print("USB configured.\n");
  765. #else
  766. USB_USBTask();
  767. #endif
  768. }
  769. void protocol_post_init(void) {
  770. host_set_driver(&lufa_driver);
  771. }
  772. void protocol_pre_task(void) {
  773. #if !defined(NO_USB_STARTUP_CHECK)
  774. if (USB_DeviceState == DEVICE_STATE_Suspended) {
  775. dprintln("suspending keyboard");
  776. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  777. suspend_power_down();
  778. if (suspend_wakeup_condition() && USB_Device_RemoteWakeupEnabled) {
  779. USB_Device_SendRemoteWakeup();
  780. clear_keyboard();
  781. # if USB_SUSPEND_WAKEUP_DELAY > 0
  782. // Some hubs, kvm switches, and monitors do
  783. // weird things, with USB device state bouncing
  784. // around wildly on wakeup, yielding race
  785. // conditions that can corrupt the keyboard state.
  786. //
  787. // Pause for a while to let things settle...
  788. wait_ms(USB_SUSPEND_WAKEUP_DELAY);
  789. # endif
  790. }
  791. }
  792. suspend_wakeup_init();
  793. }
  794. #endif
  795. }
  796. void protocol_post_task(void) {
  797. #ifdef CONSOLE_ENABLE
  798. console_task();
  799. #endif
  800. #ifdef MIDI_ENABLE
  801. MIDI_Device_USBTask(&USB_MIDI_Interface);
  802. #endif
  803. #ifdef VIRTSER_ENABLE
  804. virtser_task();
  805. CDC_Device_USBTask(&cdc_device);
  806. #endif
  807. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  808. USB_USBTask();
  809. #endif
  810. }
  811. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, const uint16_t wIndex, const void **const DescriptorAddress) {
  812. return get_usb_descriptor(wValue, wIndex, USB_ControlRequest.wLength, DescriptorAddress);
  813. }