lufa.c 35 KB

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