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

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