Fixed GenericHIDHost demo report write routine incorrect for control type requests...
[pub/USBasp.git] / Demos / Device / Mouse / Mouse.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 Mouse demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #include "Mouse.h"
38
39 /* Scheduler Task List */
40 TASK_LIST
41 {
42 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
43 { Task: USB_USBTask , TaskStatus: TASK_STOP },
44 #endif
45
46 #if !defined(INTERRUPT_DATA_ENDPOINT)
47 { Task: USB_Mouse_Report , TaskStatus: TASK_STOP },
48 #endif
49 };
50
51 /* Global Variables */
52 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
53 * protocol reporting mode.
54 */
55 bool UsingReportProtocol = true;
56
57 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
58 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
59 */
60 uint8_t IdleCount = 0;
61
62 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
63 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
64 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
65 */
66 uint16_t IdleMSRemaining = 0;
67
68
69 /** Main program entry point. This routine configures the hardware required by the application, then
70 * starts the scheduler to run the application tasks.
71 */
72 int main(void)
73 {
74 /* Disable watchdog if enabled by bootloader/fuses */
75 MCUSR &= ~(1 << WDRF);
76 wdt_disable();
77
78 /* Disable clock division */
79 clock_prescale_set(clock_div_1);
80
81 /* Hardware Initialization */
82 Joystick_Init();
83 LEDs_Init();
84 HWB_Init();
85
86 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
87 OCR0A = 0x7D;
88 TCCR0A = (1 << WGM01);
89 TCCR0B = ((1 << CS01) | (1 << CS00));
90 TIMSK0 = (1 << OCIE0A);
91
92 /* Indicate USB not ready */
93 UpdateStatus(Status_USBNotReady);
94
95 /* Initialize Scheduler so that it can be used */
96 Scheduler_Init();
97
98 /* Initialize USB Subsystem */
99 USB_Init();
100
101 /* Scheduling - routine never returns, so put this last in the main function */
102 Scheduler_Start();
103 }
104
105 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
106 * starts the library USB task to begin the enumeration and USB management process.
107 */
108 EVENT_HANDLER(USB_Connect)
109 {
110 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
111 /* Start USB management task */
112 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
113 #endif
114
115 /* Indicate USB enumerating */
116 UpdateStatus(Status_USBEnumerating);
117
118 /* Default to report protocol on connect */
119 UsingReportProtocol = true;
120 }
121
122 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
123 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
124 * asynchronously when they arrive rather than when the control endpoint is polled manually.
125 */
126 EVENT_HANDLER(USB_Reset)
127 {
128 #if defined(INTERRUPT_CONTROL_ENDPOINT)
129 /* Select the control endpoint */
130 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
131
132 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
133 USB_INT_Enable(ENDPOINT_INT_SETUP);
134 #endif
135 }
136
137 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
138 * the status LEDs and stops the USB management and Mouse reporting tasks.
139 */
140 EVENT_HANDLER(USB_Disconnect)
141 {
142 /* Stop running mouse reporting and USB management tasks */
143 #if !defined(INTERRUPT_DATA_ENDPOINT)
144 Scheduler_SetTaskMode(USB_Mouse_Report, TASK_STOP);
145 #endif
146
147 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
148 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
149 #endif
150
151 /* Indicate USB not ready */
152 UpdateStatus(Status_USBNotReady);
153 }
154
155 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
156 * of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started.
157 */
158 EVENT_HANDLER(USB_ConfigurationChanged)
159 {
160 /* Setup Mouse Report Endpoint */
161 Endpoint_ConfigureEndpoint(MOUSE_EPNUM, EP_TYPE_INTERRUPT,
162 ENDPOINT_DIR_IN, MOUSE_EPSIZE,
163 ENDPOINT_BANK_SINGLE);
164
165 #if defined(INTERRUPT_DATA_ENDPOINT)
166 /* Enable the endpoint IN interrupt ISR for the report endpoint */
167 USB_INT_Enable(ENDPOINT_INT_IN);
168 #endif
169
170 /* Indicate USB connected and ready */
171 UpdateStatus(Status_USBReady);
172
173 #if !defined(INTERRUPT_DATA_ENDPOINT)
174 /* Start running mouse reporting task */
175 Scheduler_SetTaskMode(USB_Mouse_Report, TASK_RUN);
176 #endif
177 }
178
179 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
180 * control requests that are not handled internally by the USB library (including the HID commands, which are
181 * all issued via the control endpoint), so that they can be handled appropriately for the application.
182 */
183 EVENT_HANDLER(USB_UnhandledControlPacket)
184 {
185 /* Handle HID Class specific requests */
186 switch (bRequest)
187 {
188 case REQ_GetReport:
189 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
190 {
191 USB_MouseReport_Data_t MouseReportData;
192
193 /* Create the next mouse report for transmission to the host */
194 CreateMouseReport(&MouseReportData);
195
196 /* Ignore report type and ID number value */
197 Endpoint_Discard_Word();
198
199 /* Ignore unused Interface number value */
200 Endpoint_Discard_Word();
201
202 /* Read in the number of bytes in the report to send to the host */
203 uint16_t wLength = Endpoint_Read_Word_LE();
204
205 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
206 if (wLength > sizeof(MouseReportData))
207 wLength = sizeof(MouseReportData);
208
209 Endpoint_ClearControlSETUP();
210
211 /* Write the report data to the control endpoint */
212 Endpoint_Write_Control_Stream_LE(&MouseReportData, wLength);
213
214 /* Clear the report data afterwards */
215 memset(&MouseReportData, 0, sizeof(MouseReportData));
216
217 /* Finalize the stream transfer to send the last packet or clear the host abort */
218 Endpoint_ClearControlOUT();
219 }
220
221 break;
222 case REQ_GetProtocol:
223 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
224 {
225 Endpoint_ClearControlSETUP();
226
227 /* Write the current protocol flag to the host */
228 Endpoint_Write_Byte(UsingReportProtocol);
229
230 /* Send the flag to the host */
231 Endpoint_ClearControlIN();
232
233 /* Acknowledge status stage */
234 while (!(Endpoint_IsOUTReceived()));
235 Endpoint_ClearControlOUT();
236 }
237
238 break;
239 case REQ_SetProtocol:
240 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
241 {
242 /* Read in the wValue parameter containing the new protocol mode */
243 uint16_t wValue = Endpoint_Read_Word_LE();
244
245 Endpoint_ClearControlSETUP();
246
247 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
248 UsingReportProtocol = (wValue != 0x0000);
249
250 /* Acknowledge status stage */
251 while (!(Endpoint_IsINReady()));
252 Endpoint_ClearControlIN();
253 }
254
255 break;
256 case REQ_SetIdle:
257 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
258 {
259 /* Read in the wValue parameter containing the idle period */
260 uint16_t wValue = Endpoint_Read_Word_LE();
261
262 Endpoint_ClearControlSETUP();
263
264 /* Get idle period in MSB */
265 IdleCount = (wValue >> 8);
266
267 /* Acknowledge status stage */
268 while (!(Endpoint_IsINReady()));
269 Endpoint_ClearControlIN();
270 }
271
272 break;
273 case REQ_GetIdle:
274 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
275 {
276 Endpoint_ClearControlSETUP();
277
278 /* Write the current idle duration to the host */
279 Endpoint_Write_Byte(IdleCount);
280
281 /* Send the flag to the host */
282 Endpoint_ClearControlIN();
283
284 /* Acknowledge status stage */
285 while (!(Endpoint_IsOUTReceived()));
286 Endpoint_ClearControlOUT();
287 }
288
289 break;
290 }
291 }
292
293 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
294 * scheduler elapsed idle period counter when the host has set an idle period.
295 */
296 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
297 {
298 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
299 if (IdleMSRemaining)
300 IdleMSRemaining--;
301 }
302
303 /** Fills the given HID report data structure with the next HID report to send to the host.
304 *
305 * \param ReportData Pointer to a HID report data structure to be filled
306 */
307 void CreateMouseReport(USB_MouseReport_Data_t* ReportData)
308 {
309 uint8_t JoyStatus_LCL = Joystick_GetStatus();
310
311 /* Clear the report contents */
312 memset(ReportData, 0, sizeof(USB_MouseReport_Data_t));
313
314 if (JoyStatus_LCL & JOY_UP)
315 ReportData->Y = -1;
316 else if (JoyStatus_LCL & JOY_DOWN)
317 ReportData->Y = 1;
318
319 if (JoyStatus_LCL & JOY_RIGHT)
320 ReportData->X = 1;
321 else if (JoyStatus_LCL & JOY_LEFT)
322 ReportData->X = -1;
323
324 if (JoyStatus_LCL & JOY_PRESS)
325 ReportData->Button = (1 << 0);
326
327 if (HWB_GetStatus())
328 ReportData->Button |= (1 << 1);
329 }
330
331 /** Sends the next HID report to the host, via the keyboard data endpoint. */
332 static inline void SendNextReport(void)
333 {
334 static USB_MouseReport_Data_t PrevMouseReportData;
335 USB_MouseReport_Data_t MouseReportData;
336 bool SendReport = true;
337
338 /* Create the next mouse report for transmission to the host */
339 CreateMouseReport(&MouseReportData);
340
341 /* Check if the idle period is set*/
342 if (IdleCount)
343 {
344 /* Determine if the idle period has elapsed */
345 if (!(IdleMSRemaining))
346 {
347 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
348 IdleMSRemaining = (IdleCount << 2);
349 }
350 else
351 {
352 /* Idle period not elapsed, indicate that a report must not be sent unless the report has changed */
353 SendReport = (memcmp(&PrevMouseReportData, &MouseReportData, sizeof(USB_MouseReport_Data_t)) != 0);
354 }
355 }
356
357 /* Save the current report data for later comparison to check for changes */
358 PrevMouseReportData = MouseReportData;
359
360 /* Select the Mouse Report Endpoint */
361 Endpoint_SelectEndpoint(MOUSE_EPNUM);
362
363 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
364 if (Endpoint_IsReadWriteAllowed() && SendReport)
365 {
366 /* Write Mouse Report Data */
367 Endpoint_Write_Stream_LE(&MouseReportData, sizeof(MouseReportData));
368
369 /* Finalize the stream transfer to send the last packet */
370 Endpoint_ClearIN();
371 }
372 }
373
374 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
375 * log to a serial port, or anything else that is suitable for status updates.
376 *
377 * \param CurrentStatus Current status of the system, from the Mouse_StatusCodes_t enum
378 */
379 void UpdateStatus(uint8_t CurrentStatus)
380 {
381 uint8_t LEDMask = LEDS_NO_LEDS;
382
383 /* Set the LED mask to the appropriate LED mask based on the given status code */
384 switch (CurrentStatus)
385 {
386 case Status_USBNotReady:
387 LEDMask = (LEDS_LED1);
388 break;
389 case Status_USBEnumerating:
390 LEDMask = (LEDS_LED1 | LEDS_LED2);
391 break;
392 case Status_USBReady:
393 LEDMask = (LEDS_LED2 | LEDS_LED4);
394 break;
395 }
396
397 /* Set the board LEDs to the new LED mask */
398 LEDs_SetAllLEDs(LEDMask);
399 }
400
401 #if !defined(INTERRUPT_DATA_ENDPOINT)
402 /** Task to manage HID report generation and transmission to the host, when in report mode. */
403 TASK(USB_Mouse_Report)
404 {
405 /* Check if the USB system is connected to a host */
406 if (USB_IsConnected)
407 {
408 /* Send the next mouse report to the host */
409 SendNextReport();
410 }
411 }
412 #endif
413
414 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
415 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
416 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
417 * controller. It is also used to respond to standard and class specific requests send to the device on the control
418 * endpoint, by handing them off to the LUFA library when they are received.
419 */
420 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
421 {
422 #if defined(INTERRUPT_CONTROL_ENDPOINT)
423 /* Check if the control endpoint has received a request */
424 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
425 {
426 /* Clear the endpoint interrupt */
427 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP);
428
429 /* Process the control request */
430 USB_USBTask();
431
432 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
433 USB_INT_Clear(ENDPOINT_INT_SETUP);
434 }
435 #endif
436
437 #if defined(INTERRUPT_DATA_ENDPOINT)
438 /* Check if mouse endpoint has interrupted */
439 if (Endpoint_HasEndpointInterrupted(MOUSE_EPNUM))
440 {
441 /* Select the Mouse Report Endpoint */
442 Endpoint_SelectEndpoint(MOUSE_EPNUM);
443
444 /* Clear the endpoint IN interrupt flag */
445 USB_INT_Clear(ENDPOINT_INT_IN);
446
447 /* Clear the Mouse Report endpoint interrupt and select the endpoint */
448 Endpoint_ClearEndpointInterrupt(MOUSE_EPNUM);
449
450 /* Send the next mouse report to the host */
451 SendNextReport();
452 }
453 #endif
454 }