lufa.c 29 KB

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