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.

KeyboardHostWithParser.c 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2014.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * Main source file for the KeyboardHostWithParser demo. This file contains the main tasks of
  29. * the demo and is responsible for the initial application hardware configuration.
  30. */
  31. #include "KeyboardHostWithParser.h"
  32. /** Main program entry point. This routine configures the hardware required by the application, then
  33. * enters a loop to run the application tasks in sequence.
  34. */
  35. int main(void)
  36. {
  37. SetupHardware();
  38. puts_P(PSTR(ESC_FG_CYAN "Keyboard HID Parser Host Demo running.\r\n" ESC_FG_WHITE));
  39. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  40. GlobalInterruptEnable();
  41. for (;;)
  42. {
  43. KeyboardHost_Task();
  44. USB_USBTask();
  45. }
  46. }
  47. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  48. void SetupHardware(void)
  49. {
  50. #if (ARCH == ARCH_AVR8)
  51. /* Disable watchdog if enabled by bootloader/fuses */
  52. MCUSR &= ~(1 << WDRF);
  53. wdt_disable();
  54. /* Disable clock division */
  55. clock_prescale_set(clock_div_1);
  56. #endif
  57. /* Hardware Initialization */
  58. Serial_Init(9600, false);
  59. LEDs_Init();
  60. USB_Init();
  61. /* Create a stdio stream for the serial port for stdin and stdout */
  62. Serial_CreateStream(NULL);
  63. }
  64. /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
  65. * starts the library USB task to begin the enumeration and USB management process.
  66. */
  67. void EVENT_USB_Host_DeviceAttached(void)
  68. {
  69. puts_P(PSTR(ESC_FG_GREEN "Device Attached.\r\n" ESC_FG_WHITE));
  70. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  71. }
  72. /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
  73. * stops the library USB task management process.
  74. */
  75. void EVENT_USB_Host_DeviceUnattached(void)
  76. {
  77. puts_P(PSTR(ESC_FG_GREEN "\r\nDevice Unattached.\r\n" ESC_FG_WHITE));
  78. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  79. }
  80. /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
  81. * enumerated by the host and is now ready to be used by the application.
  82. */
  83. void EVENT_USB_Host_DeviceEnumerationComplete(void)
  84. {
  85. puts_P(PSTR("Getting Config Data.\r\n"));
  86. uint8_t ErrorCode;
  87. /* Get and process the configuration descriptor data */
  88. if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
  89. {
  90. if (ErrorCode == ControlError)
  91. puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
  92. else
  93. puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
  94. printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
  95. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  96. return;
  97. }
  98. /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
  99. if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
  100. {
  101. puts_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"));
  102. printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
  103. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  104. return;
  105. }
  106. printf_P(PSTR("Processing HID Report (Size %d Bytes).\r\n"), HIDReportSize);
  107. /* Get and process the device's first HID report descriptor */
  108. if ((ErrorCode = GetHIDReportData()) != ParseSuccessful)
  109. {
  110. puts_P(PSTR(ESC_FG_RED "Report Parse Error.\r\n"));
  111. if (!(HIDReportInfo.TotalReportItems))
  112. puts_P(PSTR("Not a valid Keyboard." ESC_FG_WHITE));
  113. else
  114. printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
  115. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  116. USB_Host_SetDeviceConfiguration(0);
  117. return;
  118. }
  119. puts_P(PSTR("Keyboard Enumerated.\r\n"));
  120. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  121. }
  122. /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
  123. void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
  124. {
  125. USB_Disable();
  126. printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
  127. " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
  128. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  129. for(;;);
  130. }
  131. /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
  132. * enumerating an attached USB device.
  133. */
  134. void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
  135. const uint8_t SubErrorCode)
  136. {
  137. printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
  138. " -- Error Code %d\r\n"
  139. " -- Sub Error Code %d\r\n"
  140. " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
  141. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  142. }
  143. /** Task to read in and processes the next report from the attached device, displaying the report
  144. * contents on the board LEDs and via the serial port.
  145. */
  146. void KeyboardHost_Task(void)
  147. {
  148. if (USB_HostState != HOST_STATE_Configured)
  149. return;
  150. /* Select and unfreeze keyboard data pipe */
  151. Pipe_SelectPipe(KEYBOARD_DATA_IN_PIPE);
  152. Pipe_Unfreeze();
  153. /* Check to see if a packet has been received */
  154. if (Pipe_IsINReceived())
  155. {
  156. /* Check if data has been received from the attached keyboard */
  157. if (Pipe_IsReadWriteAllowed())
  158. {
  159. /* Create buffer big enough for the report */
  160. uint8_t KeyboardReport[Pipe_BytesInPipe()];
  161. /* Load in the keyboard report */
  162. Pipe_Read_Stream_LE(KeyboardReport, Pipe_BytesInPipe(), NULL);
  163. /* Process the read in keyboard report from the device */
  164. ProcessKeyboardReport(KeyboardReport);
  165. }
  166. /* Clear the IN endpoint, ready for next data packet */
  167. Pipe_ClearIN();
  168. }
  169. /* Freeze keyboard data pipe */
  170. Pipe_Freeze();
  171. }
  172. /** Processes a read HID report from an attached keyboard, extracting out elements via the HID parser results
  173. * as required and prints pressed characters to the serial port. Each time a key is typed, a board LED is toggled.
  174. *
  175. * \param[in] KeyboardReport Pointer to a HID report from an attached keyboard device
  176. */
  177. void ProcessKeyboardReport(uint8_t* KeyboardReport)
  178. {
  179. /* Check each HID report item in turn, looking for keyboard scan code reports */
  180. for (uint8_t ReportNumber = 0; ReportNumber < HIDReportInfo.TotalReportItems; ReportNumber++)
  181. {
  182. /* Create a temporary item pointer to the next report item */
  183. HID_ReportItem_t* ReportItem = &HIDReportInfo.ReportItems[ReportNumber];
  184. /* Check if the current report item is a keyboard scan-code */
  185. if ((ReportItem->Attributes.Usage.Page == USAGE_PAGE_KEYBOARD) &&
  186. (ReportItem->Attributes.BitSize == 8) &&
  187. (ReportItem->Attributes.Logical.Maximum > 1) &&
  188. (ReportItem->ItemType == HID_REPORT_ITEM_In))
  189. {
  190. /* Retrieve the keyboard scan-code from the report data retrieved from the device */
  191. bool FoundData = USB_GetHIDReportItemInfo(KeyboardReport, ReportItem);
  192. /* For multi-report devices - if the requested data was not in the issued report, continue */
  193. if (!(FoundData))
  194. continue;
  195. /* Key code is an unsigned char in length, cast to the appropriate type */
  196. uint8_t KeyCode = (uint8_t)ReportItem->Value;
  197. /* If scan-code is non-zero, a key is being pressed */
  198. if (KeyCode)
  199. {
  200. /* Toggle status LED to indicate keypress */
  201. LEDs_ToggleLEDs(LEDS_LED2);
  202. char PressedKey = 0;
  203. /* Retrieve pressed key character if alphanumeric */
  204. if ((KeyCode >= HID_KEYBOARD_SC_A) && (KeyCode <= HID_KEYBOARD_SC_Z))
  205. {
  206. PressedKey = (KeyCode - HID_KEYBOARD_SC_A) + 'A';
  207. }
  208. else if ((KeyCode >= HID_KEYBOARD_SC_1_AND_EXCLAMATION) &
  209. (KeyCode < HID_KEYBOARD_SC_0_AND_CLOSING_PARENTHESIS))
  210. {
  211. PressedKey = (KeyCode - HID_KEYBOARD_SC_1_AND_EXCLAMATION) + '1';
  212. }
  213. else if (KeyCode == HID_KEYBOARD_SC_0_AND_CLOSING_PARENTHESIS)
  214. {
  215. PressedKey = '0';
  216. }
  217. else if (KeyCode == HID_KEYBOARD_SC_SPACE)
  218. {
  219. PressedKey = ' ';
  220. }
  221. else if (KeyCode == HID_KEYBOARD_SC_ENTER)
  222. {
  223. PressedKey = '\n';
  224. }
  225. /* Print the pressed key character out through the serial port if valid */
  226. if (PressedKey)
  227. putchar(PressedKey);
  228. }
  229. /* Once a scan-code is found, stop scanning through the report items */
  230. break;
  231. }
  232. }
  233. }