Fixed incorrect/missing control status stage transfers on demos, bootloaders and...
[pub/USBasp.git] / Demos / KeyboardFullInt / KeyboardFullInt.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 Denver Gingerich (denver [at] ossguy [dot] com)
11 Based on code by Dean Camera (dean [at] fourwalledcubicle [dot] com)
12
13 Permission to use, copy, modify, and distribute this software
14 and its documentation for any purpose and without fee is hereby
15 granted, provided that the above copyright notice appear in all
16 copies and that both that the copyright notice and this
17 permission notice and warranty disclaimer appear in supporting
18 documentation, and that the name of the author not be used in
19 advertising or publicity pertaining to distribution of the
20 software without specific, written prior permission.
21
22 The author disclaim all warranties with regard to this
23 software, including all implied warranties of merchantability
24 and fitness. In no event shall the author be liable for any
25 special, indirect or consequential damages or any damages
26 whatsoever resulting from loss of use, data or profits, whether
27 in an action of contract, negligence or other tortious action,
28 arising out of or in connection with the use or performance of
29 this software.
30 */
31
32 /** \file
33 *
34 * Main source file for the KeyboardFullInt demo. This file contains the main tasks of the demo and
35 * is responsible for the initial application hardware configuration.
36 */
37
38 #include "KeyboardFullInt.h"
39
40 /* Project Tags, for reading out using the ButtLoad project */
41 BUTTLOADTAG(ProjName, "LUFA KeyboardFI App");
42 BUTTLOADTAG(BuildTime, __TIME__);
43 BUTTLOADTAG(BuildDate, __DATE__);
44 BUTTLOADTAG(LUFAVersion, "LUFA V" LUFA_VERSION_STRING);
45
46 /* Global Variables */
47 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
48 * protocol reporting mode.
49 */
50 bool UsingReportProtocol = true;
51
52 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
53 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
54 */
55 uint8_t IdleCount = 0;
56
57 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
58 * milliseconds. This is seperate to the IdleCount timer and is incremented and compared as the host may request
59 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
60 */
61 uint16_t IdleMSRemaining = 0;
62
63
64 /** Main program entry point. This routine configures the hardware required by the application, then
65 * starts the scheduler to run the USB management task.
66 */
67 int main(void)
68 {
69 /* Disable watchdog if enabled by bootloader/fuses */
70 MCUSR &= ~(1 << WDRF);
71 wdt_disable();
72
73 /* Disable clock division */
74 clock_prescale_set(clock_div_1);
75
76 /* Hardware Initialization */
77 Joystick_Init();
78 LEDs_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 keyboard device endpoints.
135 */
136 EVENT_HANDLER(USB_ConfigurationChanged)
137 {
138 /* Setup Keyboard Keycode Report Endpoint */
139 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
140 ENDPOINT_DIR_IN, KEYBOARD_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 /* Setup Keyboard LED Report Endpoint */
147 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
148 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
149 ENDPOINT_BANK_SINGLE);
150
151 /* Enable the endpoint OUT interrupt ISR for the LED report endpoint */
152 USB_INT_Enable(ENDPOINT_INT_OUT);
153
154 /* Indicate USB connected and ready */
155 UpdateStatus(Status_USBReady);
156 }
157
158 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
159 * control requests that are not handled internally by the USB library (including the HID commands, which are
160 * all issued via the control endpoint), so that they can be handled appropriately for the application.
161 */
162 EVENT_HANDLER(USB_UnhandledControlPacket)
163 {
164 /* Handle HID Class specific requests */
165 switch (bRequest)
166 {
167 case REQ_GetReport:
168 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
169 {
170 USB_KeyboardReport_Data_t KeyboardReportData;
171
172 /* Create the next keyboard report for transmission to the host */
173 GetNextReport(&KeyboardReportData);
174
175 /* Ignore report type and ID number value */
176 Endpoint_Discard_Word();
177
178 /* Ignore unused Interface number value */
179 Endpoint_Discard_Word();
180
181 /* Read in the number of bytes in the report to send to the host */
182 uint16_t wLength = Endpoint_Read_Word_LE();
183
184 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
185 if (wLength > sizeof(KeyboardReportData))
186 wLength = sizeof(KeyboardReportData);
187
188 Endpoint_ClearSetupReceived();
189
190 /* Write the report data to the control endpoint */
191 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, wLength);
192
193 /* Finalize the stream transfer to send the last packet or clear the host abort */
194 Endpoint_ClearSetupOUT();
195 }
196
197 break;
198 case REQ_SetReport:
199 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
200 {
201 Endpoint_ClearSetupReceived();
202
203 /* Wait until the LED report has been sent by the host */
204 while (!(Endpoint_IsSetupOUTReceived()));
205
206 /* Read in the LED report from the host */
207 uint8_t LEDStatus = Endpoint_Read_Byte();
208
209 /* Process the incomming LED report */
210 ProcessLEDReport(LEDStatus);
211
212 /* Clear the endpoint data */
213 Endpoint_ClearSetupOUT();
214
215 /* Acknowledge status stage */
216 while (!(Endpoint_IsSetupINReady()));
217 Endpoint_ClearSetupIN();
218 }
219
220 break;
221 case REQ_GetProtocol:
222 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
223 {
224 Endpoint_ClearSetupReceived();
225
226 /* Write the current protocol flag to the host */
227 Endpoint_Write_Byte(UsingReportProtocol);
228
229 /* Send the flag to the host */
230 Endpoint_ClearSetupIN();
231
232 /* Acknowledge status stage */
233 while (!(Endpoint_IsSetupOUTReceived()));
234 Endpoint_ClearSetupOUT();
235 }
236
237 break;
238 case REQ_SetProtocol:
239 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
240 {
241 /* Read in the wValue parameter containing the new protocol mode */
242 uint16_t wValue = Endpoint_Read_Word_LE();
243
244 Endpoint_ClearSetupReceived();
245
246 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
247 UsingReportProtocol = (wValue != 0x0000);
248
249 /* Acknowledge status stage */
250 while (!(Endpoint_IsSetupINReady()));
251 Endpoint_ClearSetupIN();
252 }
253
254 break;
255 case REQ_SetIdle:
256 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
257 {
258 /* Read in the wValue parameter containing the idle period */
259 uint16_t wValue = Endpoint_Read_Word_LE();
260
261 Endpoint_ClearSetupReceived();
262
263 /* Get idle period in MSB */
264 IdleCount = (wValue >> 8);
265
266 /* Acknowledge status stage */
267 while (!(Endpoint_IsSetupINReady()));
268 Endpoint_ClearSetupIN();
269 }
270
271 break;
272 case REQ_GetIdle:
273 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
274 {
275 Endpoint_ClearSetupReceived();
276
277 /* Write the current idle duration to the host */
278 Endpoint_Write_Byte(IdleCount);
279
280 /* Send the flag to the host */
281 Endpoint_ClearSetupIN();
282
283 /* Acknowledge status stage */
284 while (!(Endpoint_IsSetupOUTReceived()));
285 Endpoint_ClearSetupOUT();
286 }
287
288 break;
289 }
290 }
291
292 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
293 * scheduler elapsed idle period counter when the host has set an idle period.
294 */
295 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
296 {
297 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
298 if (IdleMSRemaining)
299 IdleMSRemaining--;
300 }
301
302 /** Fills the given HID report data structure with the next HID report to send to the host.
303 *
304 * \param ReportData Pointer to a HID report data structure to be filled
305 *
306 * \return Boolean true if the new report differs from the last report, false otherwise
307 */
308 bool GetNextReport(USB_KeyboardReport_Data_t* ReportData)
309 {
310 static uint8_t PrevJoyStatus = 0;
311 uint8_t JoyStatus_LCL = Joystick_GetStatus();
312 bool InputChanged = false;
313
314 /* Clear the report contents */
315 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
316
317 if (JoyStatus_LCL & JOY_UP)
318 ReportData->KeyCode[0] = 0x04; // A
319 else if (JoyStatus_LCL & JOY_DOWN)
320 ReportData->KeyCode[0] = 0x05; // B
321
322 if (JoyStatus_LCL & JOY_LEFT)
323 ReportData->KeyCode[0] = 0x06; // C
324 else if (JoyStatus_LCL & JOY_RIGHT)
325 ReportData->KeyCode[0] = 0x07; // D
326
327 if (JoyStatus_LCL & JOY_PRESS)
328 ReportData->KeyCode[0] = 0x08; // E
329
330 /* Check if the new report is different to the previous report */
331 InputChanged = (uint8_t)(PrevJoyStatus ^ JoyStatus_LCL);
332
333 /* Save the current joystick status for later comparison */
334 PrevJoyStatus = JoyStatus_LCL;
335
336 /* Return whether the new report is different to the previous report or not */
337 return InputChanged;
338 }
339
340 /** Processes a given LED report mask from the host and sets the board LEDs to match.
341 *
342 * \param LEDReport LED mask from the host, containing a mask of what LEDs are set
343 */
344 void ProcessLEDReport(uint8_t LEDReport)
345 {
346 uint8_t LEDMask = LEDS_LED2;
347
348 if (LEDReport & 0x01) // NUM Lock
349 LEDMask |= LEDS_LED1;
350
351 if (LEDReport & 0x02) // CAPS Lock
352 LEDMask |= LEDS_LED3;
353
354 if (LEDReport & 0x04) // SCROLL Lock
355 LEDMask |= LEDS_LED4;
356
357 /* Set the status LEDs to the current Keyboard LED status */
358 LEDs_SetAllLEDs(LEDMask);
359 }
360
361 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
362 * log to a serial port, or anything else that is suitable for status updates.
363 *
364 * \param CurrentStatus Current status of the system, from the KeyboardFullInt_StatusCodes_t enum
365 */
366 void UpdateStatus(uint8_t CurrentStatus)
367 {
368 uint8_t LEDMask = LEDS_NO_LEDS;
369
370 /* Set the LED mask to the appropriate LED mask based on the given status code */
371 switch (CurrentStatus)
372 {
373 case Status_USBNotReady:
374 LEDMask = (LEDS_LED1);
375 break;
376 case Status_USBEnumerating:
377 LEDMask = (LEDS_LED1 | LEDS_LED2);
378 break;
379 case Status_USBReady:
380 LEDMask = (LEDS_LED2 | LEDS_LED4);
381 break;
382 }
383
384 /* Set the board LEDs to the new LED mask */
385 LEDs_SetAllLEDs(LEDMask);
386 }
387
388 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
389 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
390 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
391 * controller. It is also used to respond to standard and class specific requests send to the device on the control
392 * endpoint, by handing them off to the LUFA library when they are received.
393 */
394 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
395 {
396 /* Check if the control endpoint has received a request */
397 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
398 {
399 /* Clear the endpoint interrupt */
400 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP);
401
402 /* Process the control request */
403 USB_USBTask();
404
405 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
406 USB_INT_Clear(ENDPOINT_INT_SETUP);
407 }
408
409 /* Check if keyboard endpoint has interrupted */
410 if (Endpoint_HasEndpointInterrupted(KEYBOARD_EPNUM))
411 {
412 USB_KeyboardReport_Data_t KeyboardReportData;
413 bool SendReport;
414
415 /* Select the Keyboard Report Endpoint */
416 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
417
418 /* Clear the endpoint IN interrupt flag */
419 USB_INT_Clear(ENDPOINT_INT_IN);
420
421 /* Clear the Keyboard Report endpoint interrupt */
422 Endpoint_ClearEndpointInterrupt(KEYBOARD_EPNUM);
423
424 /* Create the next keyboard report for transmission to the host */
425 SendReport = GetNextReport(&KeyboardReportData);
426
427 /* Check if the idle period is set and has elapsed */
428 if (IdleCount && !(IdleMSRemaining))
429 {
430 /* Idle period elapsed, indicate that a report must be sent */
431 SendReport = true;
432
433 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
434 IdleMSRemaining = (IdleCount << 2);
435 }
436
437 /* Check to see if a report should be issued */
438 if (SendReport)
439 {
440 /* Write Keyboard Report Data */
441 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
442 }
443
444 /* Finalize the stream transfer to send the last packet */
445 Endpoint_ClearCurrentBank();
446 }
447
448 /* Check if Keyboard LED status Endpoint has interrupted */
449 if (Endpoint_HasEndpointInterrupted(KEYBOARD_LEDS_EPNUM))
450 {
451 /* Select the Keyboard LED Report Endpoint */
452 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
453
454 /* Clear the endpoint OUT interrupt flag */
455 USB_INT_Clear(ENDPOINT_INT_OUT);
456
457 /* Clear the Keyboard LED Report endpoint interrupt */
458 Endpoint_ClearEndpointInterrupt(KEYBOARD_LEDS_EPNUM);
459
460 /* Read in the LED report from the host */
461 uint8_t LEDStatus = Endpoint_Read_Byte();
462
463 /* Process the incomming LED report */
464 ProcessLEDReport(LEDStatus);
465
466 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
467 Endpoint_ClearCurrentBank();
468 }
469 }
470