Fixed minor issue with the RNDISEthernet demo DHCP protocol decoder routine using...
[pub/USBasp.git] / Demos / Host / GenericHIDHost / GenericHIDHost.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 GenericHIDHost demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
35 */
36
37 #include "GenericHIDHost.h"
38
39 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName, "LUFA GenHid 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_HID_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 clock_prescale_set(clock_div_1);
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 /* Start-up message */
79 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
80 "Generic HID 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 HID and USB management task */
104 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
105 Scheduler_SetTaskMode(USB_HID_Host, TASK_STOP);
106
107 puts_P(PSTR("Device 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 HID Host task */
117 Scheduler_SetTaskMode(USB_HID_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 occurred 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 GenericHIDHost_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 }
174
175 /* Set the board LEDs to the new LED mask */
176 LEDs_SetAllLEDs(LEDMask);
177 }
178
179 /** Reads in and processes the next report from the attached device, displaying the report
180 * contents on the board LEDs and via the serial port.
181 */
182 void ReadNextReport(void)
183 {
184 /* Select and unfreeze HID data IN pipe */
185 Pipe_SelectPipe(HID_DATA_IN_PIPE);
186 Pipe_Unfreeze();
187
188 /* Ensure pipe contains data and is ready to be read before continuing */
189 if (!(Pipe_ReadWriteAllowed()))
190 {
191 #if !defined(INTERRUPT_DATA_PIPE)
192 /* Refreeze HID data IN pipe */
193 Pipe_Freeze();
194 #endif
195
196 return;
197 }
198
199 uint8_t ReportINData[Pipe_BytesInPipe()];
200
201 /* Read in HID report data */
202 Pipe_Read_Stream_LE(&ReportINData, sizeof(ReportINData));
203
204 /* Clear the IN endpoint, ready for next data packet */
205 Pipe_ClearCurrentBank();
206
207 /* Print report data through the serial port */
208 for (uint16_t CurrByte = 0; CurrByte < sizeof(ReportINData); CurrByte++)
209 printf_P(PSTR("0x%02X "), ReportINData[CurrByte]);
210
211 puts_P(PSTR("\r\n"));
212
213 #if !defined(INTERRUPT_DATA_PIPE)
214 /* Refreeze HID data IN pipe */
215 Pipe_Freeze();
216 #endif
217 }
218
219 /** Writes a report to the attached device.
220 *
221 * \param ReportOUTData Buffer containing the report to send to the device
222 * \param ReportIndex Index of the report in the device (zero if the device does not use multiple reports)
223 * \param ReportType Type of report to send, either HID_REPORTTYPE_OUTPUT or HID_REPORTTYPE_FEATURE
224 * \param ReportLength Length of the report to send
225 */
226 void WriteNextReport(uint8_t* ReportOUTData, uint8_t ReportIndex, uint8_t ReportType, uint16_t ReportLength)
227 {
228 /* Select and unfreeze HID data OUT pipe */
229 Pipe_SelectPipe(HID_DATA_OUT_PIPE);
230
231 /* Not all HID devices have an OUT endpoint (some require OUT reports to be sent over the
232 * control endpoint instead) - check to see if the OUT endpoint has been initialized */
233 if (Pipe_IsConfigured())
234 {
235 Pipe_Unfreeze();
236
237 /* Ensure pipe is ready to be written to before continuing */
238 if (!(Pipe_ReadWriteAllowed()))
239 {
240 /* Refreeze the data OUT pipe */
241 Pipe_Freeze();
242
243 return;
244 }
245
246 /* If the report index is used, send it before the report data */
247 if (ReportIndex)
248 Pipe_Write_Byte(ReportIndex);
249
250 /* Write out HID report data */
251 Pipe_Write_Stream_LE(ReportOUTData, ReportLength);
252
253 /* Clear the OUT endpoint, send last data packet */
254 Pipe_ClearCurrentBank();
255
256 /* Refreeze the data OUT pipe */
257 Pipe_Freeze();
258 }
259 else
260 {
261 /* Class specific request to send a HID report to the device */
262 USB_HostRequest = (USB_Host_Request_Header_t)
263 {
264 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
265 bRequest: REQ_SetReport,
266 wValue: ((ReportType << 8) | ReportIndex),
267 wIndex: 0,
268 wLength: ReportLength,
269 };
270
271 /* Select the control pipe for the request transfer */
272 Pipe_SelectPipe(PIPE_CONTROLPIPE);
273
274 /* Send the request to the device */
275 USB_Host_SendControlRequest(ReportOUTData);
276 }
277 }
278
279 /** Task to set the configuration of the attached device after it has been enumerated, and to read and process
280 * HID reports from the device and to send reports if desired.
281 */
282 TASK(USB_HID_Host)
283 {
284 uint8_t ErrorCode;
285
286 /* Switch to determine what user-application handled host state the host state machine is in */
287 switch (USB_HostState)
288 {
289 case HOST_STATE_Addressed:
290 /* Standard request to set the device configuration to configuration 1 */
291 USB_HostRequest = (USB_Host_Request_Header_t)
292 {
293 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
294 bRequest: REQ_SetConfiguration,
295 wValue: 1,
296 wIndex: 0,
297 wLength: 0,
298 };
299
300 /* Select the control pipe for the request transfer */
301 Pipe_SelectPipe(PIPE_CONTROLPIPE);
302
303 /* Send the request, display error and wait for device detach if request fails */
304 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
305 {
306 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
307 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
308
309 /* Indicate error status */
310 UpdateStatus(Status_EnumerationError);
311
312 /* Wait until USB device disconnected */
313 while (USB_IsConnected);
314 break;
315 }
316
317 USB_HostState = HOST_STATE_Configured;
318 break;
319 case HOST_STATE_Configured:
320 puts_P(PSTR("Getting Config Data.\r\n"));
321
322 /* Get and process the configuration descriptor data */
323 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
324 {
325 if (ErrorCode == ControlError)
326 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
327 else
328 puts_P(PSTR("Invalid Device.\r\n"));
329
330 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
331
332 /* Indicate error status */
333 UpdateStatus(Status_EnumerationError);
334
335 /* Wait until USB device disconnected */
336 while (USB_IsConnected);
337 break;
338 }
339
340 #if defined(INTERRUPT_DATA_PIPE)
341 /* Select and unfreeze HID data IN pipe */
342 Pipe_SelectPipe(HID_DATA_IN_PIPE);
343 Pipe_Unfreeze();
344 #endif
345
346 puts_P(PSTR("HID Device Enumerated.\r\n"));
347
348 USB_HostState = HOST_STATE_Ready;
349 break;
350 #if !defined(INTERRUPT_DATA_PIPE)
351 case HOST_STATE_Ready:
352 ReadNextReport();
353
354 break;
355 #endif
356 }
357 }
358
359 #if defined(INTERRUPT_DATA_PIPE)
360 /** Interrupt handler for the Endpoint/Pipe interrupt vector. This interrupt fires each time an enabled
361 * pipe interrupt occurs on a pipe which has had that interrupt enabled.
362 */
363 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
364 {
365 /* Save previously selected pipe before selecting a new pipe */
366 uint8_t PrevSelectedPipe = Pipe_GetCurrentPipe();
367
368 /* Check to see if the HID data IN pipe has caused the interrupt */
369 if (Pipe_HasPipeInterrupted(HID_DATA_IN_PIPE))
370 {
371 /* Clear the pipe interrupt, and select the data IN pipe */
372 Pipe_ClearPipeInterrupt(HID_DATA_IN_PIPE);
373 Pipe_SelectPipe(HID_DATA_IN_PIPE);
374
375 /* Check to see if the pipe IN interrupt has fired */
376 if (USB_INT_HasOccurred(PIPE_INT_IN) && USB_INT_IsEnabled(PIPE_INT_IN))
377 {
378 /* Clear interrupt flag */
379 USB_INT_Clear(PIPE_INT_IN);
380
381 /* Read and process the next report from the device */
382 ReadNextReport();
383 }
384 }
385
386 /* Restore previously selected pipe */
387 Pipe_SelectPipe(PrevSelectedPipe);
388 }
389 #endif