Keyboard firmwares for Atmel AVR and Cortex-M
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

lufa.c 17KB

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