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