lufa.c 29 KB

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