lufa.c 29 KB

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