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 15KB

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