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