lufa.c 31 KB

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