lufa.c 34 KB

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