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

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