lufa.c 31 KB

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