Fixed Mouse and Keyboard device demos not acting in accordance with the HID specifica...
[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 /* Scheduler Task List */
41 TASK_LIST
42 {
43 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
44 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
45 #endif
46
47 #if !defined(INTERRUPT_DATA_ENDPOINT)
48 { .Task = USB_Keyboard_Report , .TaskStatus = TASK_STOP },
49 #endif
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 presses a key).
60 */
61 uint16_t IdleCount = 500;
62
63 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
64 * milliseconds. This is separate 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 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
111 /* Start USB management task */
112 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
113 #endif
114
115 /* Indicate USB enumerating */
116 UpdateStatus(Status_USBEnumerating);
117
118 /* Default to report protocol on connect */
119 UsingReportProtocol = true;
120 }
121
122 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
123 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
124 * asynchronously when they arrive rather than when the control endpoint is polled manually.
125 */
126 EVENT_HANDLER(USB_Reset)
127 {
128 #if defined(INTERRUPT_CONTROL_ENDPOINT)
129 /* Select the control endpoint */
130 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
131
132 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
133 USB_INT_Enable(ENDPOINT_INT_SETUP);
134 #endif
135 }
136
137 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
138 * the status LEDs.
139 */
140 EVENT_HANDLER(USB_Disconnect)
141 {
142 /* Stop running keyboard reporting and USB management tasks */
143 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_STOP);
144
145 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
146 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
147 #endif
148
149 /* Indicate USB not ready */
150 UpdateStatus(Status_USBNotReady);
151 }
152
153 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
154 * of the USB device after enumeration, and configures the keyboard device endpoints.
155 */
156 EVENT_HANDLER(USB_ConfigurationChanged)
157 {
158 /* Setup Keyboard Keycode Report Endpoint */
159 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
160 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
161 ENDPOINT_BANK_SINGLE);
162
163 /* Setup Keyboard LED Report Endpoint */
164 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
165 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
166 ENDPOINT_BANK_SINGLE);
167
168 /* Indicate USB connected and ready */
169 UpdateStatus(Status_USBReady);
170
171 /* Start running keyboard reporting task */
172 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_RUN);
173 }
174
175 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
176 * control requests that are not handled internally by the USB library (including the HID commands, which are
177 * all issued via the control endpoint), so that they can be handled appropriately for the application.
178 */
179 EVENT_HANDLER(USB_UnhandledControlPacket)
180 {
181 /* Handle HID Class specific requests */
182 switch (USB_ControlRequest.bRequest)
183 {
184 case REQ_GetReport:
185 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
186 {
187 USB_KeyboardReport_Data_t KeyboardReportData;
188
189 Endpoint_ClearSETUP();
190
191 /* Create the next keyboard report for transmission to the host */
192 CreateKeyboardReport(&KeyboardReportData);
193
194 /* Write the report data to the control endpoint */
195 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
196
197 /* Finalize the stream transfer to send the last packet or clear the host abort */
198 Endpoint_ClearOUT();
199 }
200
201 break;
202 case REQ_SetReport:
203 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
204 {
205 Endpoint_ClearSETUP();
206
207 /* Wait until the LED report has been sent by the host */
208 while (!(Endpoint_IsOUTReceived()));
209
210 /* Read in the LED report from the host */
211 uint8_t LEDStatus = Endpoint_Read_Byte();
212
213 /* Process the incoming LED report */
214 ProcessLEDReport(LEDStatus);
215
216 /* Clear the endpoint data */
217 Endpoint_ClearOUT();
218
219 /* Acknowledge status stage */
220 while (!(Endpoint_IsINReady()));
221 Endpoint_ClearIN();
222 }
223
224 break;
225 case REQ_GetProtocol:
226 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
227 {
228 Endpoint_ClearSETUP();
229
230 /* Write the current protocol flag to the host */
231 Endpoint_Write_Byte(UsingReportProtocol);
232
233 /* Send the flag to the host */
234 Endpoint_ClearIN();
235
236 /* Acknowledge status stage */
237 while (!(Endpoint_IsOUTReceived()));
238 Endpoint_ClearOUT();
239 }
240
241 break;
242 case REQ_SetProtocol:
243 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
244 {
245 Endpoint_ClearSETUP();
246
247 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
248 UsingReportProtocol = (USB_ControlRequest.wValue != 0x0000);
249
250 /* Acknowledge status stage */
251 while (!(Endpoint_IsINReady()));
252 Endpoint_ClearIN();
253 }
254
255 break;
256 case REQ_SetIdle:
257 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
258 {
259 Endpoint_ClearSETUP();
260
261 /* Get idle period in MSB */
262 IdleCount = (USB_ControlRequest.wValue >> 8);
263
264 /* Acknowledge status stage */
265 while (!(Endpoint_IsINReady()));
266 Endpoint_ClearIN();
267 }
268
269 break;
270 case REQ_GetIdle:
271 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
272 {
273 Endpoint_ClearSETUP();
274
275 /* Write the current idle duration to the host */
276 Endpoint_Write_Byte(IdleCount);
277
278 /* Send the flag to the host */
279 Endpoint_ClearIN();
280
281 /* Acknowledge status stage */
282 while (!(Endpoint_IsOUTReceived()));
283 Endpoint_ClearOUT();
284 }
285
286 break;
287 }
288 }
289
290 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
291 * scheduler elapsed idle period counter when the host has set an idle period.
292 */
293 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
294 {
295 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
296 if (IdleMSRemaining)
297 IdleMSRemaining--;
298 }
299
300 /** Fills the given HID report data structure with the next HID report to send to the host.
301 *
302 * \param ReportData Pointer to a HID report data structure to be filled
303 */
304 void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
305 {
306 uint8_t JoyStatus_LCL = Joystick_GetStatus();
307
308 /* Clear the report contents */
309 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
310
311 if (JoyStatus_LCL & JOY_UP)
312 ReportData->KeyCode[0] = 0x04; // A
313 else if (JoyStatus_LCL & JOY_DOWN)
314 ReportData->KeyCode[0] = 0x05; // B
315
316 if (JoyStatus_LCL & JOY_LEFT)
317 ReportData->KeyCode[0] = 0x06; // C
318 else if (JoyStatus_LCL & JOY_RIGHT)
319 ReportData->KeyCode[0] = 0x07; // D
320
321 if (JoyStatus_LCL & JOY_PRESS)
322 ReportData->KeyCode[0] = 0x08; // E
323 }
324
325 /** Processes a received LED report, and updates the board LEDs states to match.
326 *
327 * \param LEDReport LED status report from the host
328 */
329 void ProcessLEDReport(uint8_t LEDReport)
330 {
331 uint8_t LEDMask = LEDS_LED2;
332
333 if (LEDReport & 0x01) // NUM Lock
334 LEDMask |= LEDS_LED1;
335
336 if (LEDReport & 0x02) // CAPS Lock
337 LEDMask |= LEDS_LED3;
338
339 if (LEDReport & 0x04) // SCROLL Lock
340 LEDMask |= LEDS_LED4;
341
342 /* Set the status LEDs to the current Keyboard LED status */
343 LEDs_SetAllLEDs(LEDMask);
344 }
345
346 /** Sends the next HID report to the host, via the keyboard data endpoint. */
347 void SendNextReport(void)
348 {
349 static USB_KeyboardReport_Data_t PrevKeyboardReportData;
350 USB_KeyboardReport_Data_t KeyboardReportData;
351 bool SendReport = true;
352
353 /* Create the next keyboard report for transmission to the host */
354 CreateKeyboardReport(&KeyboardReportData);
355
356 /* Check to see if the report data has changed - if so a report MUST be sent */
357 SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
358
359 /* Save the current report data for later comparison to check for changes */
360 PrevKeyboardReportData = KeyboardReportData;
361
362 /* Check if the idle period is set and has elapsed */
363 if ((IdleCount != HID_IDLE_CHANGESONLY) && (!(IdleMSRemaining)))
364 {
365 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
366 IdleMSRemaining = (IdleCount << 2);
367
368 /* Idle period is set and has elapsed, must send a report to the host */
369 SendReport = true;
370 }
371
372 /* Select the Keyboard Report Endpoint */
373 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
374
375 /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
376 if (Endpoint_IsReadWriteAllowed() && SendReport)
377 {
378 /* Write Keyboard Report Data */
379 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
380
381 /* Finalize the stream transfer to send the last packet */
382 Endpoint_ClearIN();
383 }
384 }
385
386 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
387 void ReceiveNextReport(void)
388 {
389 /* Select the Keyboard LED Report Endpoint */
390 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
391
392 /* Check if Keyboard LED Endpoint contains a packet */
393 if (Endpoint_IsOUTReceived())
394 {
395 /* Check to see if the packet contains data */
396 if (Endpoint_IsReadWriteAllowed())
397 {
398 /* Read in the LED report from the host */
399 uint8_t LEDReport = Endpoint_Read_Byte();
400
401 /* Process the read LED report from the host */
402 ProcessLEDReport(LEDReport);
403 }
404
405 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
406 Endpoint_ClearOUT();
407 }
408 }
409
410 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
411 * log to a serial port, or anything else that is suitable for status updates.
412 *
413 * \param CurrentStatus Current status of the system, from the Keyboard_StatusCodes_t enum
414 */
415 void UpdateStatus(uint8_t CurrentStatus)
416 {
417 uint8_t LEDMask = LEDS_NO_LEDS;
418
419 /* Set the LED mask to the appropriate LED mask based on the given status code */
420 switch (CurrentStatus)
421 {
422 case Status_USBNotReady:
423 LEDMask = (LEDS_LED1);
424 break;
425 case Status_USBEnumerating:
426 LEDMask = (LEDS_LED1 | LEDS_LED2);
427 break;
428 case Status_USBReady:
429 LEDMask = (LEDS_LED2 | LEDS_LED4);
430 break;
431 }
432
433 /* Set the board LEDs to the new LED mask */
434 LEDs_SetAllLEDs(LEDMask);
435 }
436
437 /** Function to manage HID report generation and transmission to the host, when in report mode. */
438 TASK(USB_Keyboard_Report)
439 {
440 /* Check if the USB system is connected to a host */
441 if (USB_IsConnected)
442 {
443 /* Send the next keypress report to the host */
444 SendNextReport();
445
446 /* Process the LED report sent from the host */
447 ReceiveNextReport();
448 }
449 }
450
451 #if defined(INTERRUPT_CONTROL_ENDPOINT)
452 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
453 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
454 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
455 * controller. It is also used to respond to standard and class specific requests send to the device on the control
456 * endpoint, by handing them off to the LUFA library when they are received.
457 */
458 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
459 {
460 /* Save previously selected endpoint before selecting a new endpoint */
461 uint8_t PrevSelectedEndpoint = Endpoint_GetCurrentEndpoint();
462
463 /* Check if the control endpoint has received a request */
464 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
465 {
466 /* Process the control request */
467 USB_USBTask();
468
469 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
470 USB_INT_Clear(ENDPOINT_INT_SETUP);
471 }
472
473 /* Restore previously selected endpoint */
474 Endpoint_SelectEndpoint(PrevSelectedEndpoint);
475 }
476 #endif