Changed stream wait timeout counter to be 16-bit, so that very long timeout periods...
[pub/USBasp.git] / Demos / KeyboardHostWithParser / KeyboardHostWithParser.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
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
28 this software.
29 */
30
31 /** \file
32 *
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.
35 */
36
37 #include "KeyboardHostWithParser.h"
38
39 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName, "LUFA KBD Host App");
41 BUTTLOADTAG(BuildTime, __TIME__);
42 BUTTLOADTAG(BuildDate, __DATE__);
43 BUTTLOADTAG(LUFAVersion, "LUFA V" LUFA_VERSION_STRING);
44
45 /* Scheduler Task List */
46 TASK_LIST
47 {
48 { Task: USB_USBTask , TaskStatus: TASK_STOP },
49 { Task: USB_Keyboard_Host , TaskStatus: TASK_STOP },
50 };
51
52
53 /** Main program entry point. This routine configures the hardware required by the application, then
54 * starts the scheduler to run the application tasks.
55 */
56 int main(void)
57 {
58 /* Disable watchdog if enabled by bootloader/fuses */
59 MCUSR &= ~(1 << WDRF);
60 wdt_disable();
61
62 /* Disable Clock Division */
63 SetSystemClockPrescaler(0);
64
65 /* Hardware Initialization */
66 SerialStream_Init(9600, false);
67 LEDs_Init();
68
69 /* Indicate USB not ready */
70 UpdateStatus(Status_USBNotReady);
71
72 /* Initialize Scheduler so that it can be used */
73 Scheduler_Init();
74
75 /* Initialize USB Subsystem */
76 USB_Init();
77
78 /* Startup message */
79 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
80 "Keyboard Host Demo running.\r\n" ESC_INVERSE_OFF));
81
82 /* Scheduling - routine never returns, so put this last in the main function */
83 Scheduler_Start();
84 }
85
86 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
87 * starts the library USB task to begin the enumeration and USB management process.
88 */
89 EVENT_HANDLER(USB_DeviceAttached)
90 {
91 puts_P(PSTR("Device Attached.\r\n"));
92 UpdateStatus(Status_USBEnumerating);
93
94 /* Start USB management task to enumerate the device */
95 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
96 }
97
98 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
99 * stops the library USB task management process.
100 */
101 EVENT_HANDLER(USB_DeviceUnattached)
102 {
103 /* Stop keyboard and USB management task */
104 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
105 Scheduler_SetTaskMode(USB_Keyboard_Host, TASK_STOP);
106
107 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
108 UpdateStatus(Status_USBNotReady);
109 }
110
111 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
112 * enumerated by the host and is now ready to be used by the application.
113 */
114 EVENT_HANDLER(USB_DeviceEnumerationComplete)
115 {
116 /* Start Keyboard Host task */
117 Scheduler_SetTaskMode(USB_Keyboard_Host, TASK_RUN);
118
119 /* Indicate device enumeration complete */
120 UpdateStatus(Status_USBReady);
121 }
122
123 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
124 EVENT_HANDLER(USB_HostError)
125 {
126 USB_ShutDown();
127
128 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
129 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
130
131 UpdateStatus(Status_HardwareError);
132 for(;;);
133 }
134
135 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occured while
136 * enumerating an attached USB device.
137 */
138 EVENT_HANDLER(USB_DeviceEnumerationFailed)
139 {
140 puts_P(PSTR(ESC_BG_RED "Dev Enum Error\r\n"));
141 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
142 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode);
143 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState);
144
145 UpdateStatus(Status_EnumerationError);
146 }
147
148 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
149 * log to a serial port, or anything else that is suitable for status updates.
150 *
151 * \param CurrentStatus Current status of the system, from the KeyboardHostWithParser_StatusCodes_t enum
152 */
153 void UpdateStatus(uint8_t CurrentStatus)
154 {
155 uint8_t LEDMask = LEDS_NO_LEDS;
156
157 /* Set the LED mask to the appropriate LED mask based on the given status code */
158 switch (CurrentStatus)
159 {
160 case Status_USBNotReady:
161 LEDMask = (LEDS_LED1);
162 break;
163 case Status_USBEnumerating:
164 LEDMask = (LEDS_LED1 | LEDS_LED2);
165 break;
166 case Status_USBReady:
167 LEDMask = (LEDS_LED2);
168 break;
169 case Status_EnumerationError:
170 case Status_HardwareError:
171 LEDMask = (LEDS_LED1 | LEDS_LED3);
172 break;
173 case Status_Busy:
174 LEDMask = (LEDS_LED1 | LEDS_LED4);
175 break;
176 }
177
178 /* Set the board LEDs to the new LED mask */
179 LEDs_SetAllLEDs(LEDMask);
180 }
181
182 /** Task to set the configuration of the attached device after it has been enumerated, and to read and process
183 * the HID report descriptor and HID reports from the device and display the results onto the board LEDs.
184 */
185 TASK(USB_Keyboard_Host)
186 {
187 uint8_t ErrorCode;
188
189 switch (USB_HostState)
190 {
191 case HOST_STATE_Addressed:
192 /* Standard request to set the device configuration to configuration 1 */
193 USB_HostRequest = (USB_Host_Request_Header_t)
194 {
195 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
196 bRequest: REQ_SetConfiguration,
197 wValue: 1,
198 wIndex: 0,
199 wLength: 0,
200 };
201
202 /* Send the request, display error and wait for device detatch if request fails */
203 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
204 {
205 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
206 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
207
208 /* Indicate error via status LEDs */
209 UpdateStatus(Status_EnumerationError);
210
211 /* Wait until USB device disconnected */
212 while (USB_IsConnected);
213 break;
214 }
215
216 USB_HostState = HOST_STATE_Configured;
217 break;
218 case HOST_STATE_Configured:
219 puts_P(PSTR("Getting Config Data.\r\n"));
220
221 /* Get and process the configuration descriptor data */
222 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
223 {
224 if (ErrorCode == ControlError)
225 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
226 else
227 puts_P(PSTR("Invalid Device.\r\n"));
228
229 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
230
231 /* Indicate error via status LEDs */
232 UpdateStatus(Status_EnumerationError);
233
234 /* Wait until USB device disconnected */
235 while (USB_IsConnected);
236 break;
237 }
238
239 puts_P(PSTR("Processing HID Report.\r\n"));
240
241 /* LEDs one and two on to indicate busy processing */
242 UpdateStatus(Status_Busy);
243
244 /* Get and process the device's first HID report descriptor */
245 if ((ErrorCode = GetHIDReportData()) != ParseSuccessful)
246 {
247 puts_P(PSTR("Report Parse Error.\r\n"));
248 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
249
250 /* Indicate error via status LEDs */
251 UpdateStatus(Status_EnumerationError);
252
253 /* Wait until USB device disconnected */
254 while (USB_IsConnected);
255 break;
256 }
257
258 /* All LEDs off - ready to indicate keypresses */
259 UpdateStatus(Status_USBReady);
260
261 puts_P(PSTR("Keyboard Enumerated.\r\n"));
262
263 USB_HostState = HOST_STATE_Ready;
264 break;
265 case HOST_STATE_Ready:
266 /* Select and unfreeze keyboard data pipe */
267 Pipe_SelectPipe(KEYBOARD_DATAPIPE);
268 Pipe_Unfreeze();
269
270 /* Check if data has been received from the attached keyboard */
271 if (Pipe_ReadWriteAllowed())
272 {
273 /* Create buffer big enough for the report */
274 uint8_t KeyboardReport[Pipe_BytesInPipe()];
275
276 /* Load in the keyboard report */
277 Pipe_Read_Stream_LE(KeyboardReport, Pipe_BytesInPipe());
278
279 /* Clear the IN endpoint, ready for next data packet */
280 Pipe_ClearCurrentBank();
281
282 /* Check each HID report item in turn, looking for keyboard scan code reports */
283 for (uint8_t ReportNumber = 0; ReportNumber < HIDReportInfo.TotalReportItems; ReportNumber++)
284 {
285 /* Create a tempoary item pointer to the next report item */
286 HID_ReportItem_t* ReportItem = &HIDReportInfo.ReportItems[ReportNumber];
287
288 /* Check if the current report item is a keyboard scancode */
289 if ((ReportItem->Attributes.Usage.Page == USAGE_PAGE_KEYBOARD) &&
290 (ReportItem->Attributes.BitSize == 8) &&
291 (ReportItem->Attributes.Logical.Maximum > 1) &&
292 (ReportItem->ItemType == REPORT_ITEM_TYPE_In))
293 {
294 /* Retrieve the keyboard scancode from the report data retrieved from the device */
295 bool FoundData = GetReportItemInfo(KeyboardReport, ReportItem);
296
297 /* For multi-report devices - if the requested data was not in the issued report, continue */
298 if (!(FoundData))
299 continue;
300
301 /* Key code is an unsigned char in length, cast to the appropriate type */
302 uint8_t KeyCode = (uint8_t)ReportItem->Value;
303
304 /* If scancode is non-zero, a key is being pressed */
305 if (KeyCode)
306 {
307 /* Toggle status LED to indicate keypress */
308 if (LEDs_GetLEDs() & LEDS_LED2)
309 LEDs_TurnOffLEDs(LEDS_LED2);
310 else
311 LEDs_TurnOnLEDs(LEDS_LED2);
312
313 char PressedKey = 0;
314
315 /* Convert scancode to printable character if alphanumeric */
316 if ((KeyCode >= 0x04) && (KeyCode <= 0x1D))
317 PressedKey = (KeyCode - 0x04) + 'A';
318 else if ((KeyCode >= 0x1E) && (KeyCode <= 0x27))
319 PressedKey = (KeyCode - 0x1E) + '0';
320 else if (KeyCode == 0x2C)
321 PressedKey = ' ';
322 else if (KeyCode == 0x28)
323 PressedKey = '\n';
324
325 /* Print the pressed key character out through the serial port if valid */
326 if (PressedKey)
327 putchar(PressedKey);
328 }
329
330 /* Once a scancode is found, stop scanning through the report items */
331 break;
332 }
333 }
334 }
335
336 /* Freeze keyboard data pipe */
337 Pipe_Freeze();
338 break;
339 }
340 }