Endpoint configuration is now refined to give better output when all configurations...
[pub/USBasp.git] / Demos / Host / MouseHost / MouseHost.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 MouseHost demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
35 */
36
37 #include "MouseHost.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 MouseHost_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 }
168
169 /* Set the board LEDs to the new LED mask */
170 LEDs_SetAllLEDs(LEDMask);
171 }
172
173 /** Reads in and processes the next report from the attached device, displaying the report
174 * contents on the board LEDs and via the serial port.
175 */
176 void ReadNextReport(void)
177 {
178 USB_MouseReport_Data_t MouseReport;
179 uint8_t LEDMask = LEDS_NO_LEDS;
180
181 /* Select mouse data pipe */
182 Pipe_SelectPipe(MOUSE_DATAPIPE);
183
184 #if !defined(INTERRUPT_DATA_PIPE)
185 /* Unfreeze keyboard data pipe */
186 Pipe_Unfreeze();
187 #endif
188
189 /* Check to see if a packet has been received */
190 if (!(Pipe_IsINReceived()))
191 {
192 #if !defined(INTERRUPT_DATA_PIPE)
193 /* Refreeze HID data IN pipe */
194 Pipe_Freeze();
195 #endif
196
197 return;
198 }
199
200 /* Ensure pipe contains data before trying to read from it */
201 if (Pipe_IsReadWriteAllowed())
202 {
203 /* Read in mouse report data */
204 Pipe_Read_Stream_LE(&MouseReport, sizeof(MouseReport));
205
206 /* Alter status LEDs according to mouse X movement */
207 if (MouseReport.X > 0)
208 LEDMask |= LEDS_LED1;
209 else if (MouseReport.X < 0)
210 LEDMask |= LEDS_LED2;
211
212 /* Alter status LEDs according to mouse Y movement */
213 if (MouseReport.Y > 0)
214 LEDMask |= LEDS_LED3;
215 else if (MouseReport.Y < 0)
216 LEDMask |= LEDS_LED4;
217
218 /* Alter status LEDs according to mouse button position */
219 if (MouseReport.Button)
220 LEDMask = LEDS_ALL_LEDS;
221
222 LEDs_SetAllLEDs(LEDMask);
223
224 /* Print mouse report data through the serial port */
225 printf_P(PSTR("dX:%2d dY:%2d Button:%d\r\n"), MouseReport.X,
226 MouseReport.Y,
227 MouseReport.Button);
228 }
229
230 /* Clear the IN endpoint, ready for next data packet */
231 Pipe_ClearIN();
232
233 #if !defined(INTERRUPT_DATA_PIPE)
234 /* Refreeze mouse data pipe */
235 Pipe_Freeze();
236 #endif
237 }
238
239 /** Task to set the configuration of the attached device after it has been enumerated, and to read and process
240 * HID reports from the device and display the results onto the board LEDs.
241 */
242 TASK(USB_Mouse_Host)
243 {
244 uint8_t ErrorCode;
245
246 /* Switch to determine what user-application handled host state the host state machine is in */
247 switch (USB_HostState)
248 {
249 case HOST_STATE_Addressed:
250 /* Standard request to set the device configuration to configuration 1 */
251 USB_ControlRequest = (USB_Request_Header_t)
252 {
253 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
254 .bRequest = REQ_SetConfiguration,
255 .wValue = 1,
256 .wIndex = 0,
257 .wLength = 0,
258 };
259
260 /* Select the control pipe for the request transfer */
261 Pipe_SelectPipe(PIPE_CONTROLPIPE);
262
263 /* Send the request, display error and wait for device detach if request fails */
264 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
265 {
266 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
267 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
268
269 /* Indicate error status */
270 UpdateStatus(Status_EnumerationError);
271
272 /* Wait until USB device disconnected */
273 while (USB_IsConnected);
274 break;
275 }
276
277 USB_HostState = HOST_STATE_Configured;
278 break;
279 case HOST_STATE_Configured:
280 puts_P(PSTR("Getting Config Data.\r\n"));
281
282 /* Get and process the configuration descriptor data */
283 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
284 {
285 if (ErrorCode == ControlError)
286 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
287 else
288 puts_P(PSTR("Invalid Device.\r\n"));
289
290 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
291
292 /* Indicate error status */
293 UpdateStatus(Status_EnumerationError);
294
295 /* Wait until USB device disconnected */
296 while (USB_IsConnected);
297 break;
298 }
299
300 /* HID class request to set the mouse protocol to the Boot Protocol */
301 USB_ControlRequest = (USB_Request_Header_t)
302 {
303 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
304 .bRequest = REQ_SetProtocol,
305 .wValue = 0,
306 .wIndex = 0,
307 .wLength = 0,
308 };
309
310 /* Select the control pipe for the request transfer */
311 Pipe_SelectPipe(PIPE_CONTROLPIPE);
312
313 /* Send the request, display error and wait for device detach if request fails */
314 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
315 {
316 puts_P(PSTR("Control Error (Set Protocol).\r\n"));
317 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
318
319 /* Indicate error status */
320 UpdateStatus(Status_EnumerationError);
321
322 /* Wait until USB device disconnected */
323 while (USB_IsConnected);
324 break;
325 }
326
327 #if defined(INTERRUPT_DATA_PIPE)
328 /* Select and unfreeze mouse data pipe */
329 Pipe_SelectPipe(MOUSE_DATAPIPE);
330 Pipe_Unfreeze();
331 #endif
332
333 puts_P(PSTR("Mouse Enumerated.\r\n"));
334
335 USB_HostState = HOST_STATE_Ready;
336 break;
337 #if !defined(INTERRUPT_DATA_PIPE)
338 case HOST_STATE_Ready:
339 /* If a report has been received, read and process it */
340 ReadNextReport();
341
342 break;
343 #endif
344 }
345 }
346
347 #if defined(INTERRUPT_DATA_PIPE)
348 /** Interrupt handler for the Endpoint/Pipe interrupt vector. This interrupt fires each time an enabled
349 * pipe interrupt occurs on a pipe which has had that interrupt enabled.
350 */
351 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
352 {
353 /* Save previously selected pipe before selecting a new pipe */
354 uint8_t PrevSelectedPipe = Pipe_GetCurrentPipe();
355
356 /* Check to see if the mouse data pipe has caused the interrupt */
357 if (Pipe_HasPipeInterrupted(MOUSE_DATAPIPE))
358 {
359 /* Clear the pipe interrupt, and select the mouse pipe */
360 Pipe_ClearPipeInterrupt(MOUSE_DATAPIPE);
361 Pipe_SelectPipe(MOUSE_DATAPIPE);
362
363 /* Check to see if the pipe IN interrupt has fired */
364 if (USB_INT_HasOccurred(PIPE_INT_IN) && USB_INT_IsEnabled(PIPE_INT_IN))
365 {
366 /* Clear interrupt flag */
367 USB_INT_Clear(PIPE_INT_IN);
368
369 /* Read and process the next report from the device */
370 ReadNextReport();
371 }
372 }
373
374 /* Restore previously selected pipe */
375 Pipe_SelectPipe(PrevSelectedPipe);
376 }
377 #endif