lufa.c 30 KB

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