Changed GenericHID device demo to use the LUFA scheduler, added INTERRUPT_DATA_ENDPOI...
[pub/USBasp.git] / Demos / Device / Keyboard / Keyboard.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 Keyboard demo. This file contains the main tasks of the demo and
35 * is responsible for the initial application hardware configuration.
36 */
37
38 #include "Keyboard.h"
39
40 /* Project Tags, for reading out using the ButtLoad project */
41 BUTTLOADTAG(ProjName, "LUFA Keyboard 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 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
50 { Task: USB_USBTask , TaskStatus: TASK_STOP },
51 #endif
52
53 #if !defined(INTERRUPT_DATA_ENDPOINT)
54 { Task: USB_Keyboard_Report , TaskStatus: TASK_STOP },
55 #endif
56 };
57
58 /* Global Variables */
59 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
60 * protocol reporting mode.
61 */
62 bool UsingReportProtocol = true;
63
64 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
65 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
66 */
67 uint8_t IdleCount = 0;
68
69 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
70 * milliseconds. This is seperate to the IdleCount timer and is incremented and compared as the host may request
71 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
72 */
73 uint16_t IdleMSRemaining = 0;
74
75
76 /** Main program entry point. This routine configures the hardware required by the application, then
77 * starts the scheduler to run the USB management task.
78 */
79 int main(void)
80 {
81 /* Disable watchdog if enabled by bootloader/fuses */
82 MCUSR &= ~(1 << WDRF);
83 wdt_disable();
84
85 /* Disable clock division */
86 clock_prescale_set(clock_div_1);
87
88 /* Hardware Initialization */
89 Joystick_Init();
90 LEDs_Init();
91
92 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
93 OCR0A = 0x7D;
94 TCCR0A = (1 << WGM01);
95 TCCR0B = ((1 << CS01) | (1 << CS00));
96 TIMSK0 = (1 << OCIE0A);
97
98 /* Indicate USB not ready */
99 UpdateStatus(Status_USBNotReady);
100
101 /* Initialize Scheduler so that it can be used */
102 Scheduler_Init();
103
104 /* Initialize USB Subsystem */
105 USB_Init();
106
107 /* Scheduling - routine never returns, so put this last in the main function */
108 Scheduler_Start();
109 }
110
111 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
112 * starts the library USB task to begin the enumeration and USB management process.
113 */
114 EVENT_HANDLER(USB_Connect)
115 {
116 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
117 /* Start USB management task */
118 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
119 #endif
120
121 /* Indicate USB enumerating */
122 UpdateStatus(Status_USBEnumerating);
123
124 /* Default to report protocol on connect */
125 UsingReportProtocol = true;
126 }
127
128 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
129 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
130 * asynchronously when they arrive rather than when the control endpoint is polled manually.
131 */
132 EVENT_HANDLER(USB_Reset)
133 {
134 #if defined(INTERRUPT_CONTROL_ENDPOINT)
135 /* Select the control endpoint */
136 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
137
138 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
139 USB_INT_Enable(ENDPOINT_INT_SETUP);
140 #endif
141 }
142
143 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
144 * the status LEDs.
145 */
146 EVENT_HANDLER(USB_Disconnect)
147 {
148 /* Stop running keyboard reporting and USB management tasks */
149 #if !defined(INTERRUPT_DATA_ENDPOINT)
150 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_STOP);
151 #endif
152
153 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
154 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
155 #endif
156
157 /* Indicate USB not ready */
158 UpdateStatus(Status_USBNotReady);
159 }
160
161 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
162 * of the USB device after enumeration, and configures the keyboard device endpoints.
163 */
164 EVENT_HANDLER(USB_ConfigurationChanged)
165 {
166 /* Setup Keyboard Keycode Report Endpoint */
167 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
168 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
169 ENDPOINT_BANK_SINGLE);
170
171 #if defined(INTERRUPT_DATA_ENDPOINT)
172 /* Enable the endpoint IN interrupt ISR for the report endpoint */
173 USB_INT_Enable(ENDPOINT_INT_IN);
174 #endif
175
176 /* Setup Keyboard LED Report Endpoint */
177 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
178 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
179 ENDPOINT_BANK_SINGLE);
180
181 #if defined(INTERRUPT_DATA_ENDPOINT)
182 /* Enable the endpoint OUT interrupt ISR for the LED report endpoint */
183 USB_INT_Enable(ENDPOINT_INT_OUT);
184 #endif
185
186 /* Indicate USB connected and ready */
187 UpdateStatus(Status_USBReady);
188
189 #if !defined(INTERRUPT_DATA_ENDPOINT)
190 /* Start running keyboard reporting task */
191 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_RUN);
192 #endif
193 }
194
195 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
196 * control requests that are not handled internally by the USB library (including the HID commands, which are
197 * all issued via the control endpoint), so that they can be handled appropriately for the application.
198 */
199 EVENT_HANDLER(USB_UnhandledControlPacket)
200 {
201 /* Handle HID Class specific requests */
202 switch (bRequest)
203 {
204 case REQ_GetReport:
205 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
206 {
207 USB_KeyboardReport_Data_t KeyboardReportData;
208
209 /* Create the next keyboard report for transmission to the host */
210 CreateKeyboardReport(&KeyboardReportData);
211
212 /* Ignore report type and ID number value */
213 Endpoint_Discard_Word();
214
215 /* Ignore unused Interface number value */
216 Endpoint_Discard_Word();
217
218 /* Read in the number of bytes in the report to send to the host */
219 uint16_t wLength = Endpoint_Read_Word_LE();
220
221 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
222 if (wLength > sizeof(KeyboardReportData))
223 wLength = sizeof(KeyboardReportData);
224
225 Endpoint_ClearSetupReceived();
226
227 /* Write the report data to the control endpoint */
228 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, wLength);
229
230 /* Finalize the stream transfer to send the last packet or clear the host abort */
231 Endpoint_ClearSetupOUT();
232 }
233
234 break;
235 case REQ_SetReport:
236 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
237 {
238 Endpoint_ClearSetupReceived();
239
240 /* Wait until the LED report has been sent by the host */
241 while (!(Endpoint_IsSetupOUTReceived()));
242
243 /* Read in the LED report from the host */
244 uint8_t LEDStatus = Endpoint_Read_Byte();
245
246 /* Process the incomming LED report */
247 ProcessLEDReport(LEDStatus);
248
249 /* Clear the endpoint data */
250 Endpoint_ClearSetupOUT();
251
252 /* Acknowledge status stage */
253 while (!(Endpoint_IsSetupINReady()));
254 Endpoint_ClearSetupIN();
255 }
256
257 break;
258 case REQ_GetProtocol:
259 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
260 {
261 Endpoint_ClearSetupReceived();
262
263 /* Write the current protocol flag to the host */
264 Endpoint_Write_Byte(UsingReportProtocol);
265
266 /* Send the flag to the host */
267 Endpoint_ClearSetupIN();
268
269 /* Acknowledge status stage */
270 while (!(Endpoint_IsSetupOUTReceived()));
271 Endpoint_ClearSetupOUT();
272 }
273
274 break;
275 case REQ_SetProtocol:
276 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
277 {
278 /* Read in the wValue parameter containing the new protocol mode */
279 uint16_t wValue = Endpoint_Read_Word_LE();
280
281 Endpoint_ClearSetupReceived();
282
283 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
284 UsingReportProtocol = (wValue != 0x0000);
285
286 /* Acknowledge status stage */
287 while (!(Endpoint_IsSetupINReady()));
288 Endpoint_ClearSetupIN();
289 }
290
291 break;
292 case REQ_SetIdle:
293 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
294 {
295 /* Read in the wValue parameter containing the idle period */
296 uint16_t wValue = Endpoint_Read_Word_LE();
297
298 Endpoint_ClearSetupReceived();
299
300 /* Get idle period in MSB */
301 IdleCount = (wValue >> 8);
302
303 /* Acknowledge status stage */
304 while (!(Endpoint_IsSetupINReady()));
305 Endpoint_ClearSetupIN();
306 }
307
308 break;
309 case REQ_GetIdle:
310 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
311 {
312 Endpoint_ClearSetupReceived();
313
314 /* Write the current idle duration to the host */
315 Endpoint_Write_Byte(IdleCount);
316
317 /* Send the flag to the host */
318 Endpoint_ClearSetupIN();
319
320 /* Acknowledge status stage */
321 while (!(Endpoint_IsSetupOUTReceived()));
322 Endpoint_ClearSetupOUT();
323 }
324
325 break;
326 }
327 }
328
329 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
330 * scheduler elapsed idle period counter when the host has set an idle period.
331 */
332 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
333 {
334 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
335 if (IdleMSRemaining)
336 IdleMSRemaining--;
337 }
338
339 /** Fills the given HID report data structure with the next HID report to send to the host.
340 *
341 * \param ReportData Pointer to a HID report data structure to be filled
342 */
343 void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
344 {
345 uint8_t JoyStatus_LCL = Joystick_GetStatus();
346
347 /* Clear the report contents */
348 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
349
350 if (JoyStatus_LCL & JOY_UP)
351 ReportData->KeyCode[0] = 0x04; // A
352 else if (JoyStatus_LCL & JOY_DOWN)
353 ReportData->KeyCode[0] = 0x05; // B
354
355 if (JoyStatus_LCL & JOY_LEFT)
356 ReportData->KeyCode[0] = 0x06; // C
357 else if (JoyStatus_LCL & JOY_RIGHT)
358 ReportData->KeyCode[0] = 0x07; // D
359
360 if (JoyStatus_LCL & JOY_PRESS)
361 ReportData->KeyCode[0] = 0x08; // E
362 }
363
364 /** Processes a received LED report, and updates the board LEDs states to match.
365 *
366 * \param LEDReport LED status report from the host
367 */
368 void ProcessLEDReport(uint8_t LEDReport)
369 {
370 uint8_t LEDMask = LEDS_LED2;
371
372 if (LEDReport & 0x01) // NUM Lock
373 LEDMask |= LEDS_LED1;
374
375 if (LEDReport & 0x02) // CAPS Lock
376 LEDMask |= LEDS_LED3;
377
378 if (LEDReport & 0x04) // SCROLL Lock
379 LEDMask |= LEDS_LED4;
380
381 /* Set the status LEDs to the current Keyboard LED status */
382 LEDs_SetAllLEDs(LEDMask);
383 }
384
385 /** Sends the next HID report to the host, via the keyboard data endpoint. */
386 static inline void SendNextReport(void)
387 {
388 static USB_KeyboardReport_Data_t PrevKeyboardReportData;
389 USB_KeyboardReport_Data_t KeyboardReportData;
390 bool SendReport = true;
391
392 /* Create the next keyboard report for transmission to the host */
393 CreateKeyboardReport(&KeyboardReportData);
394
395 /* Check if the idle period is set */
396 if (IdleCount)
397 {
398 /* Check if idle period has elapsed */
399 if (!(IdleMSRemaining))
400 {
401 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
402 IdleMSRemaining = (IdleCount << 2);
403 }
404 else
405 {
406 /* Idle period not elapsed, indicate that a report must not be sent unless the report has changed */
407 SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
408 }
409 }
410
411 /* Save the current report data for later comparison to check for changes */
412 PrevKeyboardReportData = KeyboardReportData;
413
414 /* Select the Keyboard Report Endpoint */
415 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
416
417 /* Check if Keyboard Endpoint Ready for Read/Write, and if we should send a report */
418 if (Endpoint_ReadWriteAllowed() && SendReport)
419 {
420 /* Write Keyboard Report Data */
421 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
422
423 /* Finalize the stream transfer to send the last packet */
424 Endpoint_ClearCurrentBank();
425 }
426 }
427
428 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
429 static inline void ReceiveNextReport(void)
430 {
431 /* Select the Keyboard LED Report Endpoint */
432 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
433
434 /* Check if Keyboard LED Endpoint Ready for Read/Write */
435 if (!(Endpoint_ReadWriteAllowed()))
436 return;
437
438 /* Read in the LED report from the host */
439 uint8_t LEDReport = Endpoint_Read_Byte();
440
441 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
442 Endpoint_ClearCurrentBank();
443
444 /* Process the read LED report from the host */
445 ProcessLEDReport(LEDReport);
446 }
447
448 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
449 * log to a serial port, or anything else that is suitable for status updates.
450 *
451 * \param CurrentStatus Current status of the system, from the Keyboard_StatusCodes_t enum
452 */
453 void UpdateStatus(uint8_t CurrentStatus)
454 {
455 uint8_t LEDMask = LEDS_NO_LEDS;
456
457 /* Set the LED mask to the appropriate LED mask based on the given status code */
458 switch (CurrentStatus)
459 {
460 case Status_USBNotReady:
461 LEDMask = (LEDS_LED1);
462 break;
463 case Status_USBEnumerating:
464 LEDMask = (LEDS_LED1 | LEDS_LED2);
465 break;
466 case Status_USBReady:
467 LEDMask = (LEDS_LED2 | LEDS_LED4);
468 break;
469 }
470
471 /* Set the board LEDs to the new LED mask */
472 LEDs_SetAllLEDs(LEDMask);
473 }
474
475 #if !defined(INTERRUPT_DATA_ENDPOINT)
476 /** Function to manage HID report generation and transmission to the host, when in report mode. */
477 TASK(USB_Keyboard_Report)
478 {
479 /* Check if the USB system is connected to a host */
480 if (USB_IsConnected)
481 {
482 /* Send the next keypress report to the host */
483 SendNextReport();
484
485 /* Process the LED report sent from the host */
486 ReceiveNextReport();
487 }
488 }
489 #endif
490
491 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
492 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
493 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
494 * controller. It is also used to respond to standard and class specific requests send to the device on the control
495 * endpoint, by handing them off to the LUFA library when they are received.
496 */
497 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
498 {
499 #if defined(INTERRUPT_CONTROL_ENDPOINT)
500 /* Check if the control endpoint has received a request */
501 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
502 {
503 /* Clear the endpoint interrupt */
504 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP);
505
506 /* Process the control request */
507 USB_USBTask();
508
509 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
510 USB_INT_Clear(ENDPOINT_INT_SETUP);
511 }
512 #endif
513
514 #if defined(INTERRUPT_DATA_ENDPOINT)
515 /* Check if keyboard endpoint has interrupted */
516 if (Endpoint_HasEndpointInterrupted(KEYBOARD_EPNUM))
517 {
518 /* Select the Keyboard Report Endpoint */
519 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
520
521 /* Clear the endpoint IN interrupt flag */
522 USB_INT_Clear(ENDPOINT_INT_IN);
523
524 /* Clear the Keyboard Report endpoint interrupt */
525 Endpoint_ClearEndpointInterrupt(KEYBOARD_EPNUM);
526
527 /* Send the next keypress report to the host */
528 SendNextReport();
529 }
530
531 /* Check if Keyboard LED status Endpoint has interrupted */
532 if (Endpoint_HasEndpointInterrupted(KEYBOARD_LEDS_EPNUM))
533 {
534 /* Select the Keyboard LED Report Endpoint */
535 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
536
537 /* Clear the endpoint OUT interrupt flag */
538 USB_INT_Clear(ENDPOINT_INT_OUT);
539
540 /* Clear the Keyboard LED Report endpoint interrupt */
541 Endpoint_ClearEndpointInterrupt(KEYBOARD_LEDS_EPNUM);
542
543 /* Process the LED report sent from the host */
544 ReceiveNextReport();
545 }
546 #endif
547 }