lufa.c 30 KB

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