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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. /** Processed HID report descriptor items structure, containing information on each HID report element */
  33. static HID_ReportInfo_t HIDReportInfo;
  34. /** LUFA HID Class driver interface configuration and state information. This structure is
  35. * passed to all HID Class driver functions, so that multiple instances of the same class
  36. * within a device can be differentiated from one another.
  37. */
  38. USB_ClassInfo_HID_Host_t Keyboard_HID_Interface =
  39. {
  40. .Config =
  41. {
  42. .DataINPipe =
  43. {
  44. .Address = (PIPE_DIR_IN | 1),
  45. .Banks = 1,
  46. },
  47. .DataOUTPipe =
  48. {
  49. .Address = (PIPE_DIR_OUT | 2),
  50. .Banks = 1,
  51. },
  52. .HIDInterfaceProtocol = HID_CSCP_NonBootProtocol,
  53. .HIDParserData = &HIDReportInfo
  54. },
  55. };
  56. /** Main program entry point. This routine configures the hardware required by the application, then
  57. * enters a loop to run the application tasks in sequence.
  58. */
  59. int main(void)
  60. {
  61. SetupHardware();
  62. puts_P(PSTR(ESC_FG_CYAN "Keyboard Host Demo running.\r\n" ESC_FG_WHITE));
  63. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  64. GlobalInterruptEnable();
  65. for (;;)
  66. {
  67. KeyboardHost_Task();
  68. HID_Host_USBTask(&Keyboard_HID_Interface);
  69. USB_USBTask();
  70. }
  71. }
  72. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  73. void SetupHardware(void)
  74. {
  75. #if (ARCH == ARCH_AVR8)
  76. /* Disable watchdog if enabled by bootloader/fuses */
  77. MCUSR &= ~(1 << WDRF);
  78. wdt_disable();
  79. /* Disable clock division */
  80. clock_prescale_set(clock_div_1);
  81. #endif
  82. /* Hardware Initialization */
  83. Serial_Init(9600, false);
  84. LEDs_Init();
  85. USB_Init();
  86. /* Create a stdio stream for the serial port for stdin and stdout */
  87. Serial_CreateStream(NULL);
  88. }
  89. /** Task to manage an enumerated USB keyboard once connected, to display key state
  90. * data as it is received.
  91. */
  92. void KeyboardHost_Task(void)
  93. {
  94. if (USB_HostState != HOST_STATE_Configured)
  95. return;
  96. if (HID_Host_IsReportReceived(&Keyboard_HID_Interface))
  97. {
  98. uint8_t KeyboardReport[Keyboard_HID_Interface.State.LargestReportSize];
  99. HID_Host_ReceiveReport(&Keyboard_HID_Interface, &KeyboardReport);
  100. for (uint8_t ReportNumber = 0; ReportNumber < HIDReportInfo.TotalReportItems; ReportNumber++)
  101. {
  102. HID_ReportItem_t* ReportItem = &HIDReportInfo.ReportItems[ReportNumber];
  103. /* Update the report item value if it is contained within the current report */
  104. if (!(USB_GetHIDReportItemInfo(KeyboardReport, ReportItem)))
  105. continue;
  106. /* Determine what report item is being tested, process updated value as needed */
  107. if ((ReportItem->Attributes.Usage.Page == USAGE_PAGE_KEYBOARD) &&
  108. (ReportItem->Attributes.BitSize == 8) &&
  109. (ReportItem->Attributes.Logical.Maximum > 1) &&
  110. (ReportItem->ItemType == HID_REPORT_ITEM_In))
  111. {
  112. /* Key code is an unsigned char in length, cast to the appropriate type */
  113. uint8_t KeyCode = (uint8_t)ReportItem->Value;
  114. /* If scan-code is non-zero, a key is being pressed */
  115. if (KeyCode)
  116. {
  117. /* Toggle status LED to indicate keypress */
  118. LEDs_ToggleLEDs(LEDS_LED2);
  119. char PressedKey = 0;
  120. /* Convert scan-code to printable character if alphanumeric */
  121. if ((KeyCode >= HID_KEYBOARD_SC_A) && (KeyCode <= HID_KEYBOARD_SC_Z))
  122. {
  123. PressedKey = (KeyCode - HID_KEYBOARD_SC_A) + 'A';
  124. }
  125. else if ((KeyCode >= HID_KEYBOARD_SC_1_AND_EXCLAMATION) &
  126. (KeyCode < HID_KEYBOARD_SC_0_AND_CLOSING_PARENTHESIS))
  127. {
  128. PressedKey = (KeyCode - HID_KEYBOARD_SC_1_AND_EXCLAMATION) + '1';
  129. }
  130. else if (KeyCode == HID_KEYBOARD_SC_0_AND_CLOSING_PARENTHESIS)
  131. {
  132. PressedKey = '0';
  133. }
  134. else if (KeyCode == HID_KEYBOARD_SC_SPACE)
  135. {
  136. PressedKey = ' ';
  137. }
  138. else if (KeyCode == HID_KEYBOARD_SC_ENTER)
  139. {
  140. PressedKey = '\n';
  141. }
  142. /* Print the pressed key character out through the serial port if valid */
  143. if (PressedKey)
  144. putchar(PressedKey);
  145. }
  146. /* Once a scan-code is found, stop scanning through the report items */
  147. break;
  148. }
  149. }
  150. }
  151. }
  152. /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
  153. * starts the library USB task to begin the enumeration and USB management process.
  154. */
  155. void EVENT_USB_Host_DeviceAttached(void)
  156. {
  157. puts_P(PSTR("Device Attached.\r\n"));
  158. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  159. }
  160. /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
  161. * stops the library USB task management process.
  162. */
  163. void EVENT_USB_Host_DeviceUnattached(void)
  164. {
  165. puts_P(PSTR("\r\nDevice Unattached.\r\n"));
  166. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  167. }
  168. /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
  169. * enumerated by the host and is now ready to be used by the application.
  170. */
  171. void EVENT_USB_Host_DeviceEnumerationComplete(void)
  172. {
  173. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  174. uint16_t ConfigDescriptorSize;
  175. uint8_t ConfigDescriptorData[512];
  176. if (USB_Host_GetDeviceConfigDescriptor(1, &ConfigDescriptorSize, ConfigDescriptorData,
  177. sizeof(ConfigDescriptorData)) != HOST_GETCONFIG_Successful)
  178. {
  179. puts_P(PSTR("Error Retrieving Configuration Descriptor.\r\n"));
  180. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  181. return;
  182. }
  183. if (HID_Host_ConfigurePipes(&Keyboard_HID_Interface,
  184. ConfigDescriptorSize, ConfigDescriptorData) != HID_ENUMERROR_NoError)
  185. {
  186. puts_P(PSTR("Attached Device Not a Valid Keyboard.\r\n"));
  187. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  188. return;
  189. }
  190. if (USB_Host_SetDeviceConfiguration(1) != HOST_SENDCONTROL_Successful)
  191. {
  192. puts_P(PSTR("Error Setting Device Configuration.\r\n"));
  193. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  194. return;
  195. }
  196. if (HID_Host_SetReportProtocol(&Keyboard_HID_Interface) != 0)
  197. {
  198. puts_P(PSTR("Error Setting Report Protocol Mode or Not a Valid Keyboard.\r\n"));
  199. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  200. USB_Host_SetDeviceConfiguration(0);
  201. return;
  202. }
  203. puts_P(PSTR("Keyboard Enumerated.\r\n"));
  204. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  205. }
  206. /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
  207. void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
  208. {
  209. USB_Disable();
  210. printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
  211. " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
  212. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  213. for(;;);
  214. }
  215. /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
  216. * enumerating an attached USB device.
  217. */
  218. void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
  219. const uint8_t SubErrorCode)
  220. {
  221. printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
  222. " -- Error Code %d\r\n"
  223. " -- Sub Error Code %d\r\n"
  224. " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
  225. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  226. }
  227. /** Callback for the HID Report Parser. This function is called each time the HID report parser is about to store
  228. * an IN, OUT or FEATURE item into the HIDReportInfo structure. To save on RAM, we are able to filter out items
  229. * we aren't interested in (preventing us from being able to extract them later on, but saving on the RAM they would
  230. * have occupied).
  231. *
  232. * \param[in] CurrentItem Pointer to the item the HID report parser is currently working with
  233. *
  234. * \return Boolean \c true if the item should be stored into the HID report structure, \c false if it should be discarded
  235. */
  236. bool CALLBACK_HIDParser_FilterHIDReportItem(HID_ReportItem_t* const CurrentItem)
  237. {
  238. /* Check the attributes of the current item - see if we are interested in it or not;
  239. * only store KEYBOARD usage page items into the Processed HID Report structure to
  240. * save RAM and ignore the rest
  241. */
  242. return (CurrentItem->Attributes.Usage.Page == USAGE_PAGE_KEYBOARD);
  243. }