You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

lufa.c 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /*
  2. * Copyright 2012 Jun Wako <[email protected]>
  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. #ifdef SERIAL_MOUSE_ENABLE
  46. #include "serial_mouse.h"
  47. #endif
  48. #include "descriptor.h"
  49. #include "lufa.h"
  50. uint8_t keyboard_idle = 0;
  51. uint8_t keyboard_protocol = 1;
  52. static uint8_t keyboard_led_stats = 0;
  53. static report_keyboard_t keyboard_report_sent;
  54. /* Host driver */
  55. static uint8_t keyboard_leds(void);
  56. static void send_keyboard(report_keyboard_t *report);
  57. static void send_mouse(report_mouse_t *report);
  58. static void send_system(uint16_t data);
  59. static void send_consumer(uint16_t data);
  60. host_driver_t lufa_driver = {
  61. keyboard_leds,
  62. send_keyboard,
  63. send_mouse,
  64. send_system,
  65. send_consumer
  66. };
  67. /*******************************************************************************
  68. * Console
  69. ******************************************************************************/
  70. #ifdef CONSOLE_ENABLE
  71. static void Console_Task(void)
  72. {
  73. /* Device must be connected and configured for the task to run */
  74. if (USB_DeviceState != DEVICE_STATE_Configured)
  75. return;
  76. uint8_t ep = Endpoint_GetCurrentEndpoint();
  77. #if 0
  78. // TODO: impl receivechar()/recvchar()
  79. Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
  80. /* Check to see if a packet has been sent from the host */
  81. if (Endpoint_IsOUTReceived())
  82. {
  83. /* Check to see if the packet contains data */
  84. if (Endpoint_IsReadWriteAllowed())
  85. {
  86. /* Create a temporary buffer to hold the read in report from the host */
  87. uint8_t ConsoleData[CONSOLE_EPSIZE];
  88. /* Read Console Report Data */
  89. Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
  90. /* Process Console Report Data */
  91. //ProcessConsoleHIDReport(ConsoleData);
  92. }
  93. /* Finalize the stream transfer to send the last packet */
  94. Endpoint_ClearOUT();
  95. }
  96. #endif
  97. /* IN packet */
  98. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  99. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  100. Endpoint_SelectEndpoint(ep);
  101. return;
  102. }
  103. // fill empty bank
  104. while (Endpoint_IsReadWriteAllowed())
  105. Endpoint_Write_8(0);
  106. // flash senchar packet
  107. if (Endpoint_IsINReady()) {
  108. Endpoint_ClearIN();
  109. }
  110. Endpoint_SelectEndpoint(ep);
  111. }
  112. #else
  113. static void Console_Task(void)
  114. {
  115. }
  116. #endif
  117. /*******************************************************************************
  118. * USB Events
  119. ******************************************************************************/
  120. /*
  121. * Event Order of Plug in:
  122. * 0) EVENT_USB_Device_Connect
  123. * 1) EVENT_USB_Device_Suspend
  124. * 2) EVENT_USB_Device_Reset
  125. * 3) EVENT_USB_Device_Wake
  126. */
  127. void EVENT_USB_Device_Connect(void)
  128. {
  129. }
  130. void EVENT_USB_Device_Disconnect(void)
  131. {
  132. }
  133. void EVENT_USB_Device_Reset(void)
  134. {
  135. }
  136. void EVENT_USB_Device_Suspend()
  137. {
  138. #ifdef SLEEP_LED_ENABLE
  139. sleep_led_enable();
  140. #endif
  141. }
  142. void EVENT_USB_Device_WakeUp()
  143. {
  144. suspend_wakeup_init();
  145. #ifdef SLEEP_LED_ENABLE
  146. sleep_led_disable();
  147. // NOTE: converters may not accept this
  148. led_set(host_keyboard_leds());
  149. #endif
  150. }
  151. void EVENT_USB_Device_StartOfFrame(void)
  152. {
  153. Console_Task();
  154. }
  155. /** Event handler for the USB_ConfigurationChanged event.
  156. * This is fired when the host sets the current configuration of the USB device after enumeration.
  157. */
  158. void EVENT_USB_Device_ConfigurationChanged(void)
  159. {
  160. bool ConfigSuccess = true;
  161. /* Setup Keyboard HID Report Endpoints */
  162. ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  163. KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
  164. #ifdef MOUSE_ENABLE
  165. /* Setup Mouse HID Report Endpoint */
  166. ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  167. MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
  168. #endif
  169. #ifdef EXTRAKEY_ENABLE
  170. /* Setup Extra HID Report Endpoint */
  171. ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  172. EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
  173. #endif
  174. #ifdef CONSOLE_ENABLE
  175. /* Setup Console HID Report Endpoints */
  176. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  177. CONSOLE_EPSIZE, ENDPOINT_BANK_DOUBLE);
  178. #if 0
  179. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
  180. CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
  181. #endif
  182. #endif
  183. #ifdef NKRO_ENABLE
  184. /* Setup NKRO HID Report Endpoints */
  185. ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  186. NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
  187. #endif
  188. }
  189. /*
  190. Appendix G: HID Request Support Requirements
  191. The following table enumerates the requests that need to be supported by various types of HID class devices.
  192. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  193. ------------------------------------------------------------------------------------------
  194. Boot Mouse Required Optional Optional Optional Required Required
  195. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  196. Boot Keyboard Required Optional Required Required Required Required
  197. Non-Boot Keybrd Required Optional Required Required Optional Optional
  198. Other Device Required Optional Optional Optional Optional Optional
  199. */
  200. /** Event handler for the USB_ControlRequest event.
  201. * This is fired before passing along unhandled control requests to the library for processing internally.
  202. */
  203. void EVENT_USB_Device_ControlRequest(void)
  204. {
  205. uint8_t* ReportData = NULL;
  206. uint8_t ReportSize = 0;
  207. /* Handle HID Class specific requests */
  208. switch (USB_ControlRequest.bRequest)
  209. {
  210. case HID_REQ_GetReport:
  211. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  212. {
  213. Endpoint_ClearSETUP();
  214. // Interface
  215. switch (USB_ControlRequest.wIndex) {
  216. case KEYBOARD_INTERFACE:
  217. // TODO: test/check
  218. ReportData = (uint8_t*)&keyboard_report_sent;
  219. ReportSize = sizeof(keyboard_report_sent);
  220. break;
  221. }
  222. /* Write the report data to the control endpoint */
  223. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  224. Endpoint_ClearOUT();
  225. }
  226. break;
  227. case HID_REQ_SetReport:
  228. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  229. {
  230. // Interface
  231. switch (USB_ControlRequest.wIndex) {
  232. case KEYBOARD_INTERFACE:
  233. #ifdef NKRO_ENABLE
  234. case NKRO_INTERFACE:
  235. #endif
  236. Endpoint_ClearSETUP();
  237. while (!(Endpoint_IsOUTReceived())) {
  238. if (USB_DeviceState == DEVICE_STATE_Unattached)
  239. return;
  240. }
  241. keyboard_led_stats = Endpoint_Read_8();
  242. Endpoint_ClearOUT();
  243. Endpoint_ClearStatusStage();
  244. break;
  245. }
  246. }
  247. break;
  248. case HID_REQ_GetProtocol:
  249. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  250. {
  251. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  252. Endpoint_ClearSETUP();
  253. while (!(Endpoint_IsINReady()));
  254. Endpoint_Write_8(keyboard_protocol);
  255. Endpoint_ClearIN();
  256. Endpoint_ClearStatusStage();
  257. }
  258. }
  259. break;
  260. case HID_REQ_SetProtocol:
  261. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  262. {
  263. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  264. Endpoint_ClearSETUP();
  265. Endpoint_ClearStatusStage();
  266. keyboard_protocol = ((USB_ControlRequest.wValue & 0xFF) != 0x00);
  267. #ifdef NKRO_ENABLE
  268. keyboard_nkro = !!keyboard_protocol;
  269. #endif
  270. clear_keyboard();
  271. }
  272. }
  273. break;
  274. case HID_REQ_SetIdle:
  275. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  276. {
  277. Endpoint_ClearSETUP();
  278. Endpoint_ClearStatusStage();
  279. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  280. }
  281. break;
  282. case HID_REQ_GetIdle:
  283. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  284. {
  285. Endpoint_ClearSETUP();
  286. while (!(Endpoint_IsINReady()));
  287. Endpoint_Write_8(keyboard_idle);
  288. Endpoint_ClearIN();
  289. Endpoint_ClearStatusStage();
  290. }
  291. break;
  292. }
  293. }
  294. /*******************************************************************************
  295. * Host driver
  296. ******************************************************************************/
  297. static uint8_t keyboard_leds(void)
  298. {
  299. return keyboard_led_stats;
  300. }
  301. static void send_keyboard(report_keyboard_t *report)
  302. {
  303. uint8_t timeout = 255;
  304. if (USB_DeviceState != DEVICE_STATE_Configured)
  305. return;
  306. /* Select the Keyboard Report Endpoint */
  307. #ifdef NKRO_ENABLE
  308. if (keyboard_nkro) {
  309. /* Report protocol - NKRO */
  310. Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
  311. /* Check if write ready for a polling interval around 1ms */
  312. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
  313. if (!Endpoint_IsReadWriteAllowed()) return;
  314. /* Write Keyboard Report Data */
  315. Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
  316. }
  317. else
  318. #endif
  319. {
  320. /* Boot protocol */
  321. Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
  322. /* Check if write ready for a polling interval around 10ms */
  323. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  324. if (!Endpoint_IsReadWriteAllowed()) return;
  325. /* Write Keyboard Report Data */
  326. Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
  327. }
  328. /* Finalize the stream transfer to send the last packet */
  329. Endpoint_ClearIN();
  330. keyboard_report_sent = *report;
  331. }
  332. static void send_mouse(report_mouse_t *report)
  333. {
  334. #ifdef MOUSE_ENABLE
  335. uint8_t timeout = 255;
  336. if (USB_DeviceState != DEVICE_STATE_Configured)
  337. return;
  338. /* Select the Mouse Report Endpoint */
  339. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  340. /* Check if write ready for a polling interval around 10ms */
  341. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  342. if (!Endpoint_IsReadWriteAllowed()) return;
  343. /* Write Mouse Report Data */
  344. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  345. /* Finalize the stream transfer to send the last packet */
  346. Endpoint_ClearIN();
  347. #endif
  348. }
  349. static void send_system(uint16_t data)
  350. {
  351. uint8_t timeout = 255;
  352. if (USB_DeviceState != DEVICE_STATE_Configured)
  353. return;
  354. report_extra_t r = {
  355. .report_id = REPORT_ID_SYSTEM,
  356. .usage = data
  357. };
  358. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  359. /* Check if write ready for a polling interval around 10ms */
  360. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  361. if (!Endpoint_IsReadWriteAllowed()) return;
  362. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  363. Endpoint_ClearIN();
  364. }
  365. static void send_consumer(uint16_t data)
  366. {
  367. uint8_t timeout = 255;
  368. if (USB_DeviceState != DEVICE_STATE_Configured)
  369. return;
  370. report_extra_t r = {
  371. .report_id = REPORT_ID_CONSUMER,
  372. .usage = data
  373. };
  374. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  375. /* Check if write ready for a polling interval around 10ms */
  376. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  377. if (!Endpoint_IsReadWriteAllowed()) return;
  378. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  379. Endpoint_ClearIN();
  380. }
  381. /*******************************************************************************
  382. * sendchar
  383. ******************************************************************************/
  384. #ifdef CONSOLE_ENABLE
  385. #define SEND_TIMEOUT 5
  386. int8_t sendchar(uint8_t c)
  387. {
  388. // Not wait once timeouted.
  389. // Because sendchar() is called so many times, waiting each call causes big lag.
  390. static bool timeouted = false;
  391. if (USB_DeviceState != DEVICE_STATE_Configured)
  392. return -1;
  393. uint8_t ep = Endpoint_GetCurrentEndpoint();
  394. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  395. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  396. Endpoint_SelectEndpoint(ep);
  397. return -1;
  398. }
  399. if (timeouted && !Endpoint_IsReadWriteAllowed()) {
  400. Endpoint_SelectEndpoint(ep);
  401. return - 1;
  402. }
  403. timeouted = false;
  404. uint8_t timeout = SEND_TIMEOUT;
  405. uint16_t prevFN = USB_Device_GetFrameNumber();
  406. while (!Endpoint_IsReadWriteAllowed()) {
  407. switch (USB_DeviceState) {
  408. case DEVICE_STATE_Unattached:
  409. case DEVICE_STATE_Suspended:
  410. return -1;
  411. }
  412. if (Endpoint_IsStalled()) {
  413. Endpoint_SelectEndpoint(ep);
  414. return -1;
  415. }
  416. if (prevFN != USB_Device_GetFrameNumber()) {
  417. if (!(timeout--)) {
  418. timeouted = true;
  419. Endpoint_SelectEndpoint(ep);
  420. return -1;
  421. }
  422. prevFN = USB_Device_GetFrameNumber();
  423. }
  424. }
  425. Endpoint_Write_8(c);
  426. // send when bank is full
  427. if (!Endpoint_IsReadWriteAllowed())
  428. Endpoint_ClearIN();
  429. Endpoint_SelectEndpoint(ep);
  430. return 0;
  431. }
  432. #else
  433. int8_t sendchar(uint8_t c)
  434. {
  435. return 0;
  436. }
  437. #endif
  438. /*******************************************************************************
  439. * main
  440. ******************************************************************************/
  441. static void SetupHardware(void)
  442. {
  443. /* Disable watchdog if enabled by bootloader/fuses */
  444. MCUSR &= ~(1 << WDRF);
  445. wdt_disable();
  446. /* Disable clock division */
  447. clock_prescale_set(clock_div_1);
  448. // Leonardo needs. Without this USB device is not recognized.
  449. USB_Disable();
  450. USB_Init();
  451. // for Console_Task
  452. USB_Device_EnableSOFEvents();
  453. print_set_sendchar(sendchar);
  454. }
  455. int main(void) __attribute__ ((weak));
  456. int main(void)
  457. {
  458. SetupHardware();
  459. sei();
  460. /* wait for USB startup & debug output */
  461. while (USB_DeviceState != DEVICE_STATE_Configured) {
  462. #if defined(INTERRUPT_CONTROL_ENDPOINT)
  463. ;
  464. #else
  465. USB_USBTask();
  466. #endif
  467. }
  468. print("USB configured.\n");
  469. /* init modules */
  470. keyboard_init();
  471. host_set_driver(&lufa_driver);
  472. #ifdef SLEEP_LED_ENABLE
  473. sleep_led_init();
  474. #endif
  475. #ifdef SERIAL_MOUSE_ENABLE
  476. serial_mouse_init();
  477. #endif
  478. print("Keyboard start.\n");
  479. while (1) {
  480. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  481. suspend_power_down();
  482. if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
  483. USB_Device_SendRemoteWakeup();
  484. }
  485. }
  486. keyboard_task();
  487. #ifdef SERIAL_MOUSE_ENABLE
  488. serial_mouse_task();
  489. #endif
  490. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  491. USB_USBTask();
  492. #endif
  493. }
  494. }