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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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 <avr/sleep.h>
  34. #include <avr/wdt.h>
  35. #include "report.h"
  36. #include "host.h"
  37. #include "host_driver.h"
  38. #include "keyboard.h"
  39. #include "action.h"
  40. #include "matrix.h"
  41. #include "led.h"
  42. #include "sendchar.h"
  43. #include "debug.h"
  44. #ifdef SLEEP_LED_ENABLE
  45. #include "sleep_led.h"
  46. #endif
  47. #include "descriptor.h"
  48. #include "lufa.h"
  49. static uint8_t idle_duration = 0;
  50. static uint8_t protocol_report = 1;
  51. static uint8_t keyboard_led_stats = 0;
  52. static report_keyboard_t keyboard_report_sent;
  53. /* Host driver */
  54. static uint8_t keyboard_leds(void);
  55. static void send_keyboard(report_keyboard_t *report);
  56. static void send_mouse(report_mouse_t *report);
  57. static void send_system(uint16_t data);
  58. static void send_consumer(uint16_t data);
  59. host_driver_t lufa_driver = {
  60. keyboard_leds,
  61. send_keyboard,
  62. send_mouse,
  63. send_system,
  64. send_consumer
  65. };
  66. /*******************************************************************************
  67. * Console
  68. ******************************************************************************/
  69. #ifdef CONSOLE_ENABLE
  70. static void Console_Task(void)
  71. {
  72. /* Device must be connected and configured for the task to run */
  73. if (USB_DeviceState != DEVICE_STATE_Configured)
  74. return;
  75. uint8_t ep = Endpoint_GetCurrentEndpoint();
  76. #if 0
  77. // TODO: impl receivechar()/recvchar()
  78. Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
  79. /* Check to see if a packet has been sent from the host */
  80. if (Endpoint_IsOUTReceived())
  81. {
  82. /* Check to see if the packet contains data */
  83. if (Endpoint_IsReadWriteAllowed())
  84. {
  85. /* Create a temporary buffer to hold the read in report from the host */
  86. uint8_t ConsoleData[CONSOLE_EPSIZE];
  87. /* Read Console Report Data */
  88. Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
  89. /* Process Console Report Data */
  90. //ProcessConsoleHIDReport(ConsoleData);
  91. }
  92. /* Finalize the stream transfer to send the last packet */
  93. Endpoint_ClearOUT();
  94. }
  95. #endif
  96. /* IN packet */
  97. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  98. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  99. Endpoint_SelectEndpoint(ep);
  100. return;
  101. }
  102. // fill empty bank
  103. while (Endpoint_IsReadWriteAllowed())
  104. Endpoint_Write_8(0);
  105. // flash senchar packet
  106. if (Endpoint_IsINReady()) {
  107. Endpoint_ClearIN();
  108. }
  109. Endpoint_SelectEndpoint(ep);
  110. }
  111. #else
  112. static void Console_Task(void)
  113. {
  114. }
  115. #endif
  116. /*******************************************************************************
  117. * USB Events
  118. ******************************************************************************/
  119. /*
  120. * Event Order of Plug in:
  121. * 0) EVENT_USB_Device_Connect
  122. * 1) EVENT_USB_Device_Suspend
  123. * 2) EVENT_USB_Device_Reset
  124. * 3) EVENT_USB_Device_Wake
  125. */
  126. void EVENT_USB_Device_Connect(void)
  127. {
  128. led_set(0x1f); // all on
  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. // initialize
  145. matrix_init();
  146. clear_keyboard();
  147. #ifdef SLEEP_LED_ENABLE
  148. sleep_led_disable();
  149. #endif
  150. led_set(host_keyboard_leds());
  151. }
  152. void EVENT_USB_Device_StartOfFrame(void)
  153. {
  154. Console_Task();
  155. }
  156. /** Event handler for the USB_ConfigurationChanged event.
  157. * This is fired when the host sets the current configuration of the USB device after enumeration.
  158. */
  159. #if LUFA_VERSION_INTEGER < 0x120730
  160. /* old API 120219 */
  161. #define ENDPOINT_CONFIG(epnum, eptype, epdir, epsize, epbank) Endpoint_ConfigureEndpoint(epnum, eptype, epdir, epsize, epbank)
  162. #else
  163. /* new API >= 120730 */
  164. #define ENDPOINT_BANK_SINGLE 1
  165. #define ENDPOINT_BANK_DOUBLE 2
  166. #define ENDPOINT_CONFIG(epnum, eptype, epdir, epsize, epbank) Endpoint_ConfigureEndpoint((epdir) | (epnum) , eptype, epsize, epbank)
  167. #endif
  168. void EVENT_USB_Device_ConfigurationChanged(void)
  169. {
  170. bool ConfigSuccess = true;
  171. /* Setup Keyboard HID Report Endpoints */
  172. ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  173. KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
  174. #ifdef MOUSE_ENABLE
  175. /* Setup Mouse HID Report Endpoint */
  176. ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  177. MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
  178. #endif
  179. #ifdef EXTRAKEY_ENABLE
  180. /* Setup Extra HID Report Endpoint */
  181. ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  182. EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
  183. #endif
  184. #ifdef CONSOLE_ENABLE
  185. /* Setup Console HID Report Endpoints */
  186. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  187. CONSOLE_EPSIZE, ENDPOINT_BANK_DOUBLE);
  188. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
  189. CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
  190. #endif
  191. }
  192. /*
  193. Appendix G: HID Request Support Requirements
  194. The following table enumerates the requests that need to be supported by various types of HID class devices.
  195. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  196. ------------------------------------------------------------------------------------------
  197. Boot Mouse Required Optional Optional Optional Required Required
  198. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  199. Boot Keyboard Required Optional Required Required Required Required
  200. Non-Boot Keybrd Required Optional Required Required Optional Optional
  201. Other Device Required Optional Optional Optional Optional Optional
  202. */
  203. /** Event handler for the USB_ControlRequest event.
  204. * This is fired before passing along unhandled control requests to the library for processing internally.
  205. */
  206. void EVENT_USB_Device_ControlRequest(void)
  207. {
  208. uint8_t* ReportData = NULL;
  209. uint8_t ReportSize = 0;
  210. /* Handle HID Class specific requests */
  211. switch (USB_ControlRequest.bRequest)
  212. {
  213. case HID_REQ_GetReport:
  214. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  215. {
  216. Endpoint_ClearSETUP();
  217. // Interface
  218. switch (USB_ControlRequest.wIndex) {
  219. case KEYBOARD_INTERFACE:
  220. // TODO: test/check
  221. ReportData = (uint8_t*)&keyboard_report_sent;
  222. ReportSize = sizeof(keyboard_report_sent);
  223. break;
  224. }
  225. /* Write the report data to the control endpoint */
  226. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  227. Endpoint_ClearOUT();
  228. }
  229. break;
  230. case HID_REQ_SetReport:
  231. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  232. {
  233. // Interface
  234. switch (USB_ControlRequest.wIndex) {
  235. case KEYBOARD_INTERFACE:
  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. Endpoint_ClearSETUP();
  252. while (!(Endpoint_IsINReady()));
  253. Endpoint_Write_8(protocol_report);
  254. Endpoint_ClearIN();
  255. Endpoint_ClearStatusStage();
  256. }
  257. break;
  258. case HID_REQ_SetProtocol:
  259. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  260. {
  261. Endpoint_ClearSETUP();
  262. Endpoint_ClearStatusStage();
  263. protocol_report = ((USB_ControlRequest.wValue & 0xFF) != 0x00);
  264. }
  265. break;
  266. case HID_REQ_SetIdle:
  267. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  268. {
  269. Endpoint_ClearSETUP();
  270. Endpoint_ClearStatusStage();
  271. idle_duration = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  272. }
  273. break;
  274. case HID_REQ_GetIdle:
  275. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  276. {
  277. Endpoint_ClearSETUP();
  278. while (!(Endpoint_IsINReady()));
  279. Endpoint_Write_8(idle_duration);
  280. Endpoint_ClearIN();
  281. Endpoint_ClearStatusStage();
  282. }
  283. break;
  284. }
  285. }
  286. /*******************************************************************************
  287. * Host driver
  288. ******************************************************************************/
  289. static uint8_t keyboard_leds(void)
  290. {
  291. return keyboard_led_stats;
  292. }
  293. static void send_keyboard(report_keyboard_t *report)
  294. {
  295. uint8_t timeout = 0;
  296. // TODO: handle NKRO report
  297. /* Select the Keyboard Report Endpoint */
  298. Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
  299. /* Check if Keyboard Endpoint Ready for Read/Write */
  300. while (--timeout && !Endpoint_IsReadWriteAllowed()) ;
  301. /* Write Keyboard Report Data */
  302. Endpoint_Write_Stream_LE(report, sizeof(report_keyboard_t), NULL);
  303. /* Finalize the stream transfer to send the last packet */
  304. Endpoint_ClearIN();
  305. keyboard_report_sent = *report;
  306. }
  307. static void send_mouse(report_mouse_t *report)
  308. {
  309. #ifdef MOUSE_ENABLE
  310. uint8_t timeout = 0;
  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. report_extra_t r = {
  325. .report_id = REPORT_ID_SYSTEM,
  326. .usage = data
  327. };
  328. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  329. while (--timeout && !Endpoint_IsReadWriteAllowed()) ;
  330. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  331. Endpoint_ClearIN();
  332. }
  333. static void send_consumer(uint16_t data)
  334. {
  335. uint8_t timeout = 0;
  336. report_extra_t r = {
  337. .report_id = REPORT_ID_CONSUMER,
  338. .usage = data
  339. };
  340. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  341. while (--timeout && !Endpoint_IsReadWriteAllowed()) ;
  342. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  343. Endpoint_ClearIN();
  344. }
  345. /*******************************************************************************
  346. * sendchar
  347. ******************************************************************************/
  348. #ifdef CONSOLE_ENABLE
  349. #define SEND_TIMEOUT 5
  350. int8_t sendchar(uint8_t c)
  351. {
  352. // Not wait once timeouted.
  353. // Because sendchar() is called so many times, waiting each call causes big lag.
  354. static bool timeouted = false;
  355. if (USB_DeviceState != DEVICE_STATE_Configured)
  356. return -1;
  357. uint8_t ep = Endpoint_GetCurrentEndpoint();
  358. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  359. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  360. Endpoint_SelectEndpoint(ep);
  361. return -1;
  362. }
  363. if (timeouted && !Endpoint_IsReadWriteAllowed()) {
  364. Endpoint_SelectEndpoint(ep);
  365. return - 1;
  366. }
  367. timeouted = false;
  368. uint8_t timeout = SEND_TIMEOUT;
  369. uint16_t prevFN = USB_Device_GetFrameNumber();
  370. while (!Endpoint_IsReadWriteAllowed()) {
  371. switch (USB_DeviceState) {
  372. case DEVICE_STATE_Unattached:
  373. case DEVICE_STATE_Suspended:
  374. return -1;
  375. }
  376. if (Endpoint_IsStalled()) {
  377. Endpoint_SelectEndpoint(ep);
  378. return -1;
  379. }
  380. if (prevFN != USB_Device_GetFrameNumber()) {
  381. if (!(timeout--)) {
  382. timeouted = true;
  383. Endpoint_SelectEndpoint(ep);
  384. return -1;
  385. }
  386. prevFN = USB_Device_GetFrameNumber();
  387. }
  388. }
  389. Endpoint_Write_8(c);
  390. // send when bank is full
  391. if (!Endpoint_IsReadWriteAllowed())
  392. Endpoint_ClearIN();
  393. Endpoint_SelectEndpoint(ep);
  394. return 0;
  395. }
  396. #else
  397. int8_t sendchar(uint8_t c)
  398. {
  399. return 0;
  400. }
  401. #endif
  402. /*******************************************************************************
  403. * main
  404. ******************************************************************************/
  405. static void SetupHardware(void)
  406. {
  407. /* Disable watchdog if enabled by bootloader/fuses */
  408. MCUSR &= ~(1 << WDRF);
  409. wdt_disable();
  410. /* Disable clock division */
  411. clock_prescale_set(clock_div_1);
  412. // Leonardo needs. Without this USB device is not recognized.
  413. USB_Disable();
  414. USB_Init();
  415. // for Console_Task
  416. USB_Device_EnableSOFEvents();
  417. }
  418. static bool wakeup_condition(void)
  419. {
  420. matrix_scan();
  421. for (uint8_t r = 0; r < MATRIX_ROWS; r++) {
  422. if (matrix_get_row(r)) return true;
  423. }
  424. return false;
  425. }
  426. #define wdt_intr_enable(value) \
  427. __asm__ __volatile__ ( \
  428. "in __tmp_reg__,__SREG__" "\n\t" \
  429. "cli" "\n\t" \
  430. "wdr" "\n\t" \
  431. "sts %0,%1" "\n\t" \
  432. "out __SREG__,__tmp_reg__" "\n\t" \
  433. "sts %0,%2" "\n\t" \
  434. : /* no outputs */ \
  435. : "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \
  436. "r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \
  437. "r" ((uint8_t) ((value & 0x08 ? _WD_PS3_MASK : 0x00) | \
  438. _BV(WDIE) | (value & 0x07)) ) \
  439. : "r0" \
  440. )
  441. int main(void) __attribute__ ((weak));
  442. int main(void)
  443. {
  444. SetupHardware();
  445. keyboard_init();
  446. host_set_driver(&lufa_driver);
  447. #ifdef SLEEP_LED_ENABLE
  448. sleep_led_init();
  449. #endif
  450. sei();
  451. while (1) {
  452. // while suspend
  453. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  454. #ifndef NO_SUSPEND_POWER_DOWN
  455. // Enable watchdog to wake from MCU sleep
  456. cli();
  457. wdt_reset();
  458. // Watchdog Interrupt and System Reset Mode
  459. //wdt_enable(WDTO_1S);
  460. //WDTCSR |= _BV(WDIE);
  461. // Watchdog Interrupt Mode
  462. wdt_intr_enable(WDTO_120MS);
  463. // TODO: more power saving
  464. // See PicoPower application note
  465. // - I/O port input with pullup
  466. // - prescale clock
  467. // - BOD disable
  468. // - Power Reduction Register PRR
  469. // sleep in power down mode
  470. set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  471. sleep_enable();
  472. sei();
  473. sleep_cpu();
  474. sleep_disable();
  475. // Disable watchdog after sleep
  476. wdt_disable();
  477. #endif
  478. // Send request of USB Wakeup from Suspend to host
  479. if (USB_Device_RemoteWakeupEnabled) {
  480. if (wakeup_condition()) {
  481. USB_Device_SendRemoteWakeup();
  482. }
  483. }
  484. }
  485. keyboard_task();
  486. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  487. USB_USBTask();
  488. #endif
  489. }
  490. }
  491. #ifndef NO_SUSPEND_POWER_DOWN
  492. /* watchdog timeout */
  493. ISR(WDT_vect)
  494. {
  495. /* wakeup from MCU sleep mode */
  496. /*
  497. // blink LED
  498. static uint8_t led_state = 0;
  499. static uint8_t led_count = 0;
  500. led_count++;
  501. if ((led_count & 0x07) == 0) {
  502. led_set((led_state ^= (1<<USB_LED_CAPS_LOCK)));
  503. }
  504. */
  505. }
  506. #endif