Keyboard firmwares for Atmel AVR and Cortex-M
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.

lufa.c 18KB

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