Deleted StdDescriptors.c, renamed USB_GetDescriptor() to CALLBACK_USB_GetDescriptor...
[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 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
44 { .Task = USB_Keyboard_Report , .TaskStatus = TASK_STOP },
45 };
46
47 /* Global Variables */
48 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
49 * protocol reporting mode.
50 */
51 bool UsingReportProtocol = true;
52
53 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
54 * for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
55 */
56 uint16_t IdleCount = 500;
57
58 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
59 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
60 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
61 */
62 uint16_t IdleMSRemaining = 0;
63
64
65 /** Main program entry point. This routine configures the hardware required by the application, then
66 * starts the scheduler to run the USB management task.
67 */
68 int main(void)
69 {
70 /* Disable watchdog if enabled by bootloader/fuses */
71 MCUSR &= ~(1 << WDRF);
72 wdt_disable();
73
74 /* Disable clock division */
75 clock_prescale_set(clock_div_1);
76
77 /* Hardware Initialization */
78 Joystick_Init();
79 LEDs_Init();
80
81 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
82 OCR0A = 0x7D;
83 TCCR0A = (1 << WGM01);
84 TCCR0B = ((1 << CS01) | (1 << CS00));
85 TIMSK0 = (1 << OCIE0A);
86
87 /* Indicate USB not ready */
88 UpdateStatus(Status_USBNotReady);
89
90 /* Initialize Scheduler so that it can be used */
91 Scheduler_Init();
92
93 /* Initialize USB Subsystem */
94 USB_Init();
95
96 /* Scheduling - routine never returns, so put this last in the main function */
97 Scheduler_Start();
98 }
99
100 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
101 * starts the library USB task to begin the enumeration and USB management process.
102 */
103 void EVENT_USB_Connect(void)
104 {
105 /* Start USB management task */
106 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
107
108 /* Indicate USB enumerating */
109 UpdateStatus(Status_USBEnumerating);
110
111 /* Default to report protocol on connect */
112 UsingReportProtocol = true;
113 }
114
115 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
116 * the status LEDs.
117 */
118 void EVENT_USB_Disconnect(void)
119 {
120 /* Stop running keyboard reporting and USB management tasks */
121 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_STOP);
122 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
123
124 /* Indicate USB not ready */
125 UpdateStatus(Status_USBNotReady);
126 }
127
128 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
129 * of the USB device after enumeration, and configures the keyboard device endpoints.
130 */
131 void EVENT_USB_ConfigurationChanged(void)
132 {
133 /* Setup Keyboard Keycode Report Endpoint */
134 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
135 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
136 ENDPOINT_BANK_SINGLE);
137
138 /* Setup Keyboard LED Report Endpoint */
139 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
140 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
141 ENDPOINT_BANK_SINGLE);
142
143 /* Indicate USB connected and ready */
144 UpdateStatus(Status_USBReady);
145
146 /* Start running keyboard reporting task */
147 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_RUN);
148 }
149
150 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
151 * control requests that are not handled internally by the USB library (including the HID commands, which are
152 * all issued via the control endpoint), so that they can be handled appropriately for the application.
153 */
154 void EVENT_USB_UnhandledControlPacket(void)
155 {
156 /* Handle HID Class specific requests */
157 switch (USB_ControlRequest.bRequest)
158 {
159 case REQ_GetReport:
160 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
161 {
162 USB_KeyboardReport_Data_t KeyboardReportData;
163
164 Endpoint_ClearSETUP();
165
166 /* Create the next keyboard report for transmission to the host */
167 CreateKeyboardReport(&KeyboardReportData);
168
169 /* Write the report data to the control endpoint */
170 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
171
172 /* Finalize the stream transfer to send the last packet or clear the host abort */
173 Endpoint_ClearOUT();
174 }
175
176 break;
177 case REQ_SetReport:
178 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
179 {
180 Endpoint_ClearSETUP();
181
182 /* Wait until the LED report has been sent by the host */
183 while (!(Endpoint_IsOUTReceived()));
184
185 /* Read in the LED report from the host */
186 uint8_t LEDStatus = Endpoint_Read_Byte();
187
188 /* Process the incoming LED report */
189 ProcessLEDReport(LEDStatus);
190
191 /* Clear the endpoint data */
192 Endpoint_ClearOUT();
193
194 /* Acknowledge status stage */
195 while (!(Endpoint_IsINReady()));
196 Endpoint_ClearIN();
197 }
198
199 break;
200 case REQ_GetProtocol:
201 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
202 {
203 Endpoint_ClearSETUP();
204
205 /* Write the current protocol flag to the host */
206 Endpoint_Write_Byte(UsingReportProtocol);
207
208 /* Send the flag to the host */
209 Endpoint_ClearIN();
210
211 /* Acknowledge status stage */
212 while (!(Endpoint_IsOUTReceived()));
213 Endpoint_ClearOUT();
214 }
215
216 break;
217 case REQ_SetProtocol:
218 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
219 {
220 Endpoint_ClearSETUP();
221
222 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
223 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
224
225 /* Acknowledge status stage */
226 while (!(Endpoint_IsINReady()));
227 Endpoint_ClearIN();
228 }
229
230 break;
231 case REQ_SetIdle:
232 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
233 {
234 Endpoint_ClearSETUP();
235
236 /* Get idle period in MSB */
237 IdleCount = (USB_ControlRequest.wValue >> 8);
238
239 /* Acknowledge status stage */
240 while (!(Endpoint_IsINReady()));
241 Endpoint_ClearIN();
242 }
243
244 break;
245 case REQ_GetIdle:
246 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
247 {
248 Endpoint_ClearSETUP();
249
250 /* Write the current idle duration to the host */
251 Endpoint_Write_Byte(IdleCount);
252
253 /* Send the flag to the host */
254 Endpoint_ClearIN();
255
256 /* Acknowledge status stage */
257 while (!(Endpoint_IsOUTReceived()));
258 Endpoint_ClearOUT();
259 }
260
261 break;
262 }
263 }
264
265 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
266 * scheduler elapsed idle period counter when the host has set an idle period.
267 */
268 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
269 {
270 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
271 if (IdleMSRemaining)
272 IdleMSRemaining--;
273 }
274
275 /** Fills the given HID report data structure with the next HID report to send to the host.
276 *
277 * \param ReportData Pointer to a HID report data structure to be filled
278 */
279 void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
280 {
281 uint8_t JoyStatus_LCL = Joystick_GetStatus();
282
283 /* Clear the report contents */
284 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
285
286 if (JoyStatus_LCL & JOY_UP)
287 ReportData->KeyCode[0] = 0x04; // A
288 else if (JoyStatus_LCL & JOY_DOWN)
289 ReportData->KeyCode[0] = 0x05; // B
290
291 if (JoyStatus_LCL & JOY_LEFT)
292 ReportData->KeyCode[0] = 0x06; // C
293 else if (JoyStatus_LCL & JOY_RIGHT)
294 ReportData->KeyCode[0] = 0x07; // D
295
296 if (JoyStatus_LCL & JOY_PRESS)
297 ReportData->KeyCode[0] = 0x08; // E
298 }
299
300 /** Processes a received LED report, and updates the board LEDs states to match.
301 *
302 * \param LEDReport LED status report from the host
303 */
304 void ProcessLEDReport(uint8_t LEDReport)
305 {
306 uint8_t LEDMask = LEDS_LED2;
307
308 if (LEDReport & 0x01) // NUM Lock
309 LEDMask |= LEDS_LED1;
310
311 if (LEDReport & 0x02) // CAPS Lock
312 LEDMask |= LEDS_LED3;
313
314 if (LEDReport & 0x04) // SCROLL Lock
315 LEDMask |= LEDS_LED4;
316
317 /* Set the status LEDs to the current Keyboard LED status */
318 LEDs_SetAllLEDs(LEDMask);
319 }
320
321 /** Sends the next HID report to the host, via the keyboard data endpoint. */
322 void SendNextReport(void)
323 {
324 static USB_KeyboardReport_Data_t PrevKeyboardReportData;
325 USB_KeyboardReport_Data_t KeyboardReportData;
326 bool SendReport = true;
327
328 /* Create the next keyboard report for transmission to the host */
329 CreateKeyboardReport(&KeyboardReportData);
330
331 /* Check to see if the report data has changed - if so a report MUST be sent */
332 SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
333
334 /* Save the current report data for later comparison to check for changes */
335 PrevKeyboardReportData = KeyboardReportData;
336
337 /* Check if the idle period is set and has elapsed */
338 if ((IdleCount != HID_IDLE_CHANGESONLY) && (!(IdleMSRemaining)))
339 {
340 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
341 IdleMSRemaining = (IdleCount << 2);
342
343 /* Idle period is set and has elapsed, must send a report to the host */
344 SendReport = true;
345 }
346
347 /* Select the Keyboard Report Endpoint */
348 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
349
350 /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
351 if (Endpoint_IsReadWriteAllowed() && SendReport)
352 {
353 /* Write Keyboard Report Data */
354 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
355
356 /* Finalize the stream transfer to send the last packet */
357 Endpoint_ClearIN();
358 }
359 }
360
361 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
362 void ReceiveNextReport(void)
363 {
364 /* Select the Keyboard LED Report Endpoint */
365 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
366
367 /* Check if Keyboard LED Endpoint contains a packet */
368 if (Endpoint_IsOUTReceived())
369 {
370 /* Check to see if the packet contains data */
371 if (Endpoint_IsReadWriteAllowed())
372 {
373 /* Read in the LED report from the host */
374 uint8_t LEDReport = Endpoint_Read_Byte();
375
376 /* Process the read LED report from the host */
377 ProcessLEDReport(LEDReport);
378 }
379
380 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
381 Endpoint_ClearOUT();
382 }
383 }
384
385 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
386 * log to a serial port, or anything else that is suitable for status updates.
387 *
388 * \param CurrentStatus Current status of the system, from the Keyboard_StatusCodes_t enum
389 */
390 void UpdateStatus(uint8_t CurrentStatus)
391 {
392 uint8_t LEDMask = LEDS_NO_LEDS;
393
394 /* Set the LED mask to the appropriate LED mask based on the given status code */
395 switch (CurrentStatus)
396 {
397 case Status_USBNotReady:
398 LEDMask = (LEDS_LED1);
399 break;
400 case Status_USBEnumerating:
401 LEDMask = (LEDS_LED1 | LEDS_LED2);
402 break;
403 case Status_USBReady:
404 LEDMask = (LEDS_LED2 | LEDS_LED4);
405 break;
406 }
407
408 /* Set the board LEDs to the new LED mask */
409 LEDs_SetAllLEDs(LEDMask);
410 }
411
412 /** Function to manage HID report generation and transmission to the host, when in report mode. */
413 TASK(USB_Keyboard_Report)
414 {
415 /* Check if the USB system is connected to a host */
416 if (USB_IsConnected)
417 {
418 /* Send the next keypress report to the host */
419 SendNextReport();
420
421 /* Process the LED report sent from the host */
422 ReceiveNextReport();
423 }
424 }