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