lufa.c 32 KB

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