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