Fixed incorrect HID interface class and subclass values in the Mouse and KeyboardMous...
[pub/USBasp.git] / Demos / Host / MouseHostWithParser / MouseHostWithParser.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 MouseHostWithParser demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
35 */
36
37 #include "MouseHostWithParser.h"
38
39 /* Scheduler Task List */
40 TASK_LIST
41 {
42 { Task: USB_USBTask , TaskStatus: TASK_STOP },
43 { Task: USB_Mouse_Host , TaskStatus: TASK_STOP },
44 };
45
46
47 /** Main program entry point. This routine configures the hardware required by the application, then
48 * starts the scheduler to run the application tasks.
49 */
50 int main(void)
51 {
52 /* Disable watchdog if enabled by bootloader/fuses */
53 MCUSR &= ~(1 << WDRF);
54 wdt_disable();
55
56 /* Disable clock division */
57 clock_prescale_set(clock_div_1);
58
59 /* Hardware Initialization */
60 SerialStream_Init(9600, false);
61 LEDs_Init();
62
63 /* Indicate USB not ready */
64 UpdateStatus(Status_USBNotReady);
65
66 /* Initialize Scheduler so that it can be used */
67 Scheduler_Init();
68
69 /* Initialize USB Subsystem */
70 USB_Init();
71
72 /* Start-up message */
73 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
74 "Mouse Host Demo running.\r\n" ESC_INVERSE_OFF));
75
76 /* Scheduling - routine never returns, so put this last in the main function */
77 Scheduler_Start();
78 }
79
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.
82 */
83 EVENT_HANDLER(USB_DeviceAttached)
84 {
85 puts_P(PSTR("Device Attached.\r\n"));
86 UpdateStatus(Status_USBEnumerating);
87
88 /* Start USB management task to enumerate the device */
89 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
90 }
91
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.
94 */
95 EVENT_HANDLER(USB_DeviceUnattached)
96 {
97 /* Stop mouse and USB management task */
98 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
99 Scheduler_SetTaskMode(USB_Mouse_Host, TASK_STOP);
100
101 puts_P(PSTR("Device Unattached.\r\n"));
102 UpdateStatus(Status_USBNotReady);
103 }
104
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.
107 */
108 EVENT_HANDLER(USB_DeviceEnumerationComplete)
109 {
110 /* Start Mouse Host task */
111 Scheduler_SetTaskMode(USB_Mouse_Host, TASK_RUN);
112
113 /* Indicate device enumeration complete */
114 UpdateStatus(Status_USBReady);
115 }
116
117 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
118 EVENT_HANDLER(USB_HostError)
119 {
120 USB_ShutDown();
121
122 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
123 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
124
125 UpdateStatus(Status_HardwareError);
126 for(;;);
127 }
128
129 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
130 * enumerating an attached USB device.
131 */
132 EVENT_HANDLER(USB_DeviceEnumerationFailed)
133 {
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);
138
139 UpdateStatus(Status_EnumerationError);
140 }
141
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.
144 *
145 * \param CurrentStatus Current status of the system, from the MouseHostWithParser_StatusCodes_t enum
146 */
147 void UpdateStatus(uint8_t CurrentStatus)
148 {
149 uint8_t LEDMask = LEDS_NO_LEDS;
150
151 /* Set the LED mask to the appropriate LED mask based on the given status code */
152 switch (CurrentStatus)
153 {
154 case Status_USBNotReady:
155 LEDMask = (LEDS_LED1);
156 break;
157 case Status_USBEnumerating:
158 LEDMask = (LEDS_LED1 | LEDS_LED2);
159 break;
160 case Status_USBReady:
161 LEDMask = (LEDS_LED2);
162 break;
163 case Status_EnumerationError:
164 case Status_HardwareError:
165 LEDMask = (LEDS_LED1 | LEDS_LED3);
166 break;
167 case Status_Busy:
168 LEDMask = (LEDS_LED1 | LEDS_LED4);
169 break;
170 }
171
172 /* Set the board LEDs to the new LED mask */
173 LEDs_SetAllLEDs(LEDMask);
174 }
175
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.
178 */
179 TASK(USB_Mouse_Host)
180 {
181 uint8_t ErrorCode;
182
183 /* Switch to determine what user-application handled host state the host state machine is in */
184 switch (USB_HostState)
185 {
186 case HOST_STATE_Addressed:
187 /* Standard request to set the device configuration to configuration 1 */
188 USB_HostRequest = (USB_Host_Request_Header_t)
189 {
190 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
191 bRequest: REQ_SetConfiguration,
192 wValue: 1,
193 wIndex: 0,
194 wLength: 0,
195 };
196
197 /* Select the control pipe for the request transfer */
198 Pipe_SelectPipe(PIPE_CONTROLPIPE);
199
200 /* Send the request, display error and wait for device detach if request fails */
201 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
202 {
203 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
204 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
205
206 /* Indicate error via status LEDs */
207 UpdateStatus(Status_EnumerationError);
208
209 /* Wait until USB device disconnected */
210 while (USB_IsConnected);
211 break;
212 }
213
214 USB_HostState = HOST_STATE_Configured;
215 break;
216 case HOST_STATE_Configured:
217 puts_P(PSTR("Getting Config Data.\r\n"));
218
219 /* Get and process the configuration descriptor data */
220 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
221 {
222 if (ErrorCode == ControlError)
223 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
224 else
225 puts_P(PSTR("Invalid Device.\r\n"));
226
227 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
228
229 /* Indicate error via status LEDs */
230 UpdateStatus(Status_EnumerationError);
231
232 /* Wait until USB device disconnected */
233 while (USB_IsConnected);
234 break;
235 }
236
237 puts_P(PSTR("Processing HID Report.\r\n"));
238
239 /* LEDs one and two on to indicate busy processing */
240 UpdateStatus(Status_Busy);
241
242 /* Get and process the device's first HID report descriptor */
243 if ((ErrorCode = GetHIDReportData()) != ParseSuccessful)
244 {
245 puts_P(PSTR("Report Parse Error.\r\n"));
246 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
247
248 /* Indicate error via status LEDs */
249 UpdateStatus(Status_EnumerationError);
250
251 /* Wait until USB device disconnected */
252 while (USB_IsConnected);
253 break;
254 }
255
256 /* All LEDs off - ready to indicate key presses */
257 UpdateStatus(Status_USBReady);
258
259 puts_P(PSTR("Mouse Enumerated.\r\n"));
260
261 USB_HostState = HOST_STATE_Ready;
262 break;
263 case HOST_STATE_Ready:
264 /* Select and unfreeze mouse data pipe */
265 Pipe_SelectPipe(MOUSE_DATAPIPE);
266 Pipe_Unfreeze();
267
268 /* Check to see if a packet has been received */
269 if (Pipe_IsINReceived())
270 {
271 /* Check if data has been received from the attached mouse */
272 if (Pipe_IsReadWriteAllowed())
273 {
274 /* Create buffer big enough for the report */
275 uint8_t MouseReport[Pipe_BytesInPipe()];
276
277 /* Load in the mouse report */
278 Pipe_Read_Stream_LE(MouseReport, Pipe_BytesInPipe());
279
280 /* Process the read in mouse report from the device */
281 ProcessMouseReport(MouseReport);
282 }
283
284 /* Clear the IN endpoint, ready for next data packet */
285 Pipe_ClearIN();
286 }
287
288 /* Freeze mouse data pipe */
289 Pipe_Freeze();
290 break;
291 }
292 }
293
294 /** Processes a read HID report from an attached mouse, extracting out elements via the HID parser results
295 * as required and displays movement and button presses on the board LEDs.
296 *
297 * \param MouseReport Pointer to a HID report from an attached mouse device
298 */
299 void ProcessMouseReport(uint8_t* MouseReport)
300 {
301 uint8_t LEDMask = LEDS_NO_LEDS;
302
303 /* Check each HID report item in turn, looking for mouse X/Y/button reports */
304 for (uint8_t ReportNumber = 0; ReportNumber < HIDReportInfo.TotalReportItems; ReportNumber++)
305 {
306 /* Create a temporary item pointer to the next report item */
307 HID_ReportItem_t* ReportItem = &HIDReportInfo.ReportItems[ReportNumber];
308
309 bool FoundData;
310
311 if ((ReportItem->Attributes.Usage.Page == USAGE_PAGE_BUTTON) &&
312 (ReportItem->ItemType == REPORT_ITEM_TYPE_In))
313 {
314 /* Get the mouse button value */
315 FoundData = USB_GetHIDReportItemInfo(MouseReport, ReportItem);
316
317 /* For multi-report devices - if the requested data was not in the issued report, continue */
318 if (!(FoundData))
319 continue;
320
321 /* If button is pressed, all LEDs are turned on */
322 if (ReportItem->Value)
323 LEDMask = LEDS_ALL_LEDS;
324 }
325 else if ((ReportItem->Attributes.Usage.Page == USAGE_PAGE_GENERIC_DCTRL) &&
326 ((ReportItem->Attributes.Usage.Usage == USAGE_X) ||
327 (ReportItem->Attributes.Usage.Usage == USAGE_Y)) &&
328 (ReportItem->ItemType == REPORT_ITEM_TYPE_In))
329 {
330 /* Get the mouse relative position value */
331 FoundData = USB_GetHIDReportItemInfo(MouseReport, ReportItem);
332
333 /* For multi-report devices - if the requested data was not in the issued report, continue */
334 if (!(FoundData))
335 continue;
336
337 int16_t DeltaMovement;
338
339 if (ReportItem->Attributes.BitSize > 8)
340 DeltaMovement = (int16_t)ReportItem->Value;
341 else
342 DeltaMovement = (int8_t)ReportItem->Value;
343
344 /* Determine if the report is for the X or Y delta movement */
345 if (ReportItem->Attributes.Usage.Usage == USAGE_X)
346 {
347 /* Turn on the appropriate LED according to direction if the delta is non-zero */
348 if (DeltaMovement)
349 LEDMask |= ((DeltaMovement > 0) ? LEDS_LED1 : LEDS_LED2);
350 }
351 else
352 {
353 /* Turn on the appropriate LED according to direction if the delta is non-zero */
354 if (DeltaMovement)
355 LEDMask |= ((DeltaMovement > 0) ? LEDS_LED3 : LEDS_LED4);
356 }
357 }
358 }
359
360 /* Display the button information on the board LEDs */
361 LEDs_SetAllLEDs(LEDMask);
362 }