3 Copyright (C) Dean Camera, 2009.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
33 * Main source file for the KeyboardHostWithParser demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
37 #include "KeyboardHostWithParser.h"
39 /* Scheduler Task List */
42 { .Task
= USB_USBTask
, .TaskStatus
= TASK_STOP
},
43 { .Task
= USB_Keyboard_Host
, .TaskStatus
= TASK_STOP
},
47 /** Main program entry point. This routine configures the hardware required by the application, then
48 * starts the scheduler to run the application tasks.
52 /* Disable watchdog if enabled by bootloader/fuses */
53 MCUSR
&= ~(1 << WDRF
);
56 /* Disable clock division */
57 clock_prescale_set(clock_div_1
);
59 /* Hardware Initialization */
60 SerialStream_Init(9600, false);
63 /* Indicate USB not ready */
64 UpdateStatus(Status_USBNotReady
);
66 /* Initialize Scheduler so that it can be used */
69 /* Initialize USB Subsystem */
72 /* Start-up message */
73 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
74 "Keyboard Host Demo running.\r\n" ESC_INVERSE_OFF
));
76 /* Scheduling - routine never returns, so put this last in the main function */
80 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
81 * starts the library USB task to begin the enumeration and USB management process.
83 EVENT_HANDLER(USB_DeviceAttached
)
85 puts_P(PSTR("Device Attached.\r\n"));
86 UpdateStatus(Status_USBEnumerating
);
88 /* Start USB management task to enumerate the device */
89 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
92 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
93 * stops the library USB task management process.
95 EVENT_HANDLER(USB_DeviceUnattached
)
97 /* Stop keyboard and USB management task */
98 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
99 Scheduler_SetTaskMode(USB_Keyboard_Host
, TASK_STOP
);
101 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
102 UpdateStatus(Status_USBNotReady
);
105 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
106 * enumerated by the host and is now ready to be used by the application.
108 EVENT_HANDLER(USB_DeviceEnumerationComplete
)
110 /* Start Keyboard Host task */
111 Scheduler_SetTaskMode(USB_Keyboard_Host
, TASK_RUN
);
113 /* Indicate device enumeration complete */
114 UpdateStatus(Status_USBReady
);
117 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
118 EVENT_HANDLER(USB_HostError
)
122 puts_P(PSTR(ESC_BG_RED
"Host Mode Error\r\n"));
123 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
125 UpdateStatus(Status_HardwareError
);
129 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
130 * enumerating an attached USB device.
132 EVENT_HANDLER(USB_DeviceEnumerationFailed
)
134 puts_P(PSTR(ESC_BG_RED
"Dev Enum Error\r\n"));
135 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
136 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode
);
137 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState
);
139 UpdateStatus(Status_EnumerationError
);
142 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
143 * log to a serial port, or anything else that is suitable for status updates.
145 * \param CurrentStatus Current status of the system, from the KeyboardHostWithParser_StatusCodes_t enum
147 void UpdateStatus(uint8_t CurrentStatus
)
149 uint8_t LEDMask
= LEDS_NO_LEDS
;
151 /* Set the LED mask to the appropriate LED mask based on the given status code */
152 switch (CurrentStatus
)
154 case Status_USBNotReady
:
155 LEDMask
= (LEDS_LED1
);
157 case Status_USBEnumerating
:
158 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
160 case Status_USBReady
:
161 LEDMask
= (LEDS_LED2
);
163 case Status_EnumerationError
:
164 case Status_HardwareError
:
165 LEDMask
= (LEDS_LED1
| LEDS_LED3
);
168 LEDMask
= (LEDS_LED1
| LEDS_LED4
);
172 /* Set the board LEDs to the new LED mask */
173 LEDs_SetAllLEDs(LEDMask
);
176 /** Task to set the configuration of the attached device after it has been enumerated, and to read and process
177 * the HID report descriptor and HID reports from the device and display the results onto the board LEDs.
179 TASK(USB_Keyboard_Host
)
183 switch (USB_HostState
)
185 case HOST_STATE_Addressed
:
186 /* Standard request to set the device configuration to configuration 1 */
187 USB_HostRequest
= (USB_Host_Request_Header_t
)
189 .bmRequestType
= (REQDIR_HOSTTODEVICE
| REQTYPE_STANDARD
| REQREC_DEVICE
),
190 .bRequest
= REQ_SetConfiguration
,
196 /* Select the control pipe for the request transfer */
197 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
199 /* Send the request, display error and wait for device detach if request fails */
200 if ((ErrorCode
= USB_Host_SendControlRequest(NULL
)) != HOST_SENDCONTROL_Successful
)
202 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
203 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
205 /* Indicate error via status LEDs */
206 UpdateStatus(Status_EnumerationError
);
208 /* Wait until USB device disconnected */
209 while (USB_IsConnected
);
213 USB_HostState
= HOST_STATE_Configured
;
215 case HOST_STATE_Configured
:
216 puts_P(PSTR("Getting Config Data.\r\n"));
218 /* Get and process the configuration descriptor data */
219 if ((ErrorCode
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
)
221 if (ErrorCode
== ControlError
)
222 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
224 puts_P(PSTR("Invalid Device.\r\n"));
226 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
228 /* Indicate error via status LEDs */
229 UpdateStatus(Status_EnumerationError
);
231 /* Wait until USB device disconnected */
232 while (USB_IsConnected
);
236 puts_P(PSTR("Processing HID Report.\r\n"));
238 /* LEDs one and two on to indicate busy processing */
239 UpdateStatus(Status_Busy
);
241 /* Get and process the device's first HID report descriptor */
242 if ((ErrorCode
= GetHIDReportData()) != ParseSuccessful
)
244 puts_P(PSTR("Report Parse Error.\r\n"));
245 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
247 /* Indicate error via status LEDs */
248 UpdateStatus(Status_EnumerationError
);
250 /* Wait until USB device disconnected */
251 while (USB_IsConnected
);
255 /* All LEDs off - ready to indicate key presses */
256 UpdateStatus(Status_USBReady
);
258 puts_P(PSTR("Keyboard Enumerated.\r\n"));
260 USB_HostState
= HOST_STATE_Ready
;
262 case HOST_STATE_Ready
:
263 /* Select and unfreeze keyboard data pipe */
264 Pipe_SelectPipe(KEYBOARD_DATAPIPE
);
267 /* Check to see if a packet has been received */
268 if (Pipe_IsINReceived())
270 /* Check if data has been received from the attached keyboard */
271 if (Pipe_IsReadWriteAllowed())
273 /* Create buffer big enough for the report */
274 uint8_t KeyboardReport
[Pipe_BytesInPipe()];
276 /* Load in the keyboard report */
277 Pipe_Read_Stream_LE(KeyboardReport
, Pipe_BytesInPipe());
279 /* Process the read in keyboard report from the device */
280 ProcessKeyboardReport(KeyboardReport
);
283 /* Clear the IN endpoint, ready for next data packet */
287 /* Freeze keyboard data pipe */
293 /** Processes a read HID report from an attached keyboard, extracting out elements via the HID parser results
294 * as required and prints pressed characters to the serial port. Each time a key is typed, a board LED is toggled.
296 * \param KeyboardReport Pointer to a HID report from an attached keyboard device
298 void ProcessKeyboardReport(uint8_t* KeyboardReport
)
300 /* Check each HID report item in turn, looking for keyboard scan code reports */
301 for (uint8_t ReportNumber
= 0; ReportNumber
< HIDReportInfo
.TotalReportItems
; ReportNumber
++)
303 /* Create a temporary item pointer to the next report item */
304 HID_ReportItem_t
* ReportItem
= &HIDReportInfo
.ReportItems
[ReportNumber
];
306 /* Check if the current report item is a keyboard scancode */
307 if ((ReportItem
->Attributes
.Usage
.Page
== USAGE_PAGE_KEYBOARD
) &&
308 (ReportItem
->Attributes
.BitSize
== 8) &&
309 (ReportItem
->Attributes
.Logical
.Maximum
> 1) &&
310 (ReportItem
->ItemType
== REPORT_ITEM_TYPE_In
))
312 /* Retrieve the keyboard scancode from the report data retrieved from the device */
313 bool FoundData
= USB_GetHIDReportItemInfo(KeyboardReport
, ReportItem
);
315 /* For multi-report devices - if the requested data was not in the issued report, continue */
319 /* Key code is an unsigned char in length, cast to the appropriate type */
320 uint8_t KeyCode
= (uint8_t)ReportItem
->Value
;
322 /* If scancode is non-zero, a key is being pressed */
325 /* Toggle status LED to indicate keypress */
326 if (LEDs_GetLEDs() & LEDS_LED2
)
327 LEDs_TurnOffLEDs(LEDS_LED2
);
329 LEDs_TurnOnLEDs(LEDS_LED2
);
333 /* Convert scancode to printable character if alphanumeric */
334 if ((KeyCode
>= 0x04) && (KeyCode
<= 0x1D))
335 PressedKey
= (KeyCode
- 0x04) + 'A';
336 else if ((KeyCode
>= 0x1E) && (KeyCode
<= 0x27))
337 PressedKey
= (KeyCode
- 0x1E) + '0';
338 else if (KeyCode
== 0x2C)
340 else if (KeyCode
== 0x28)
343 /* Print the pressed key character out through the serial port if valid */
348 /* Once a scancode is found, stop scanning through the report items */