lufa.c 29 KB

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