Much faster attribute range lookup - look through short list of attributes and compar...
[pub/USBasp.git] / Demos / Device / LowLevel / Keyboard / Keyboard.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2010.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11 Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
12
13 Permission to use, copy, modify, distribute, and sell this
14 software and its documentation for any purpose is hereby granted
15 without fee, provided that the above copyright notice appear in
16 all 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 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
41 * protocol reporting mode.
42 */
43 bool UsingReportProtocol = true;
44
45 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
46 * for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
47 */
48 uint16_t IdleCount = 500;
49
50 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
51 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
52 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
53 */
54 uint16_t IdleMSRemaining = 0;
55
56
57 /** Main program entry point. This routine configures the hardware required by the application, then
58 * enters a loop to run the application tasks in sequence.
59 */
60 int main(void)
61 {
62 SetupHardware();
63
64 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
65 sei();
66
67 for (;;)
68 {
69 HID_Task();
70 USB_USBTask();
71 }
72 }
73
74 /** Configures the board hardware and chip peripherals for the demo's functionality. */
75 void SetupHardware(void)
76 {
77 /* Disable watchdog if enabled by bootloader/fuses */
78 MCUSR &= ~(1 << WDRF);
79 wdt_disable();
80
81 /* Disable clock division */
82 clock_prescale_set(clock_div_1);
83
84 /* Hardware Initialization */
85 Joystick_Init();
86 LEDs_Init();
87 USB_Init();
88 Buttons_Init();
89 }
90
91 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
92 * starts the library USB task to begin the enumeration and USB management process.
93 */
94 void EVENT_USB_Device_Connect(void)
95 {
96 /* Indicate USB enumerating */
97 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
98
99 /* Default to report protocol on connect */
100 UsingReportProtocol = true;
101 }
102
103 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
104 * the status LEDs.
105 */
106 void EVENT_USB_Device_Disconnect(void)
107 {
108 /* Indicate USB not ready */
109 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
110 }
111
112 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
113 * of the USB device after enumeration, and configures the keyboard device endpoints.
114 */
115 void EVENT_USB_Device_ConfigurationChanged(void)
116 {
117 /* Indicate USB connected and ready */
118 LEDs_SetAllLEDs(LEDMASK_USB_READY);
119
120 /* Setup Keyboard Keycode Report Endpoint */
121 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
122 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
123 ENDPOINT_BANK_SINGLE)))
124 {
125 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
126 }
127
128 /* Setup Keyboard LED Report Endpoint */
129 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
130 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
131 ENDPOINT_BANK_SINGLE)))
132 {
133 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
134 }
135
136 USB_Device_EnableSOFEvents();
137 }
138
139 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific
140 * control requests that are not handled internally by the USB library (including the HID commands, which are
141 * all issued via the control endpoint), so that they can be handled appropriately for the application.
142 */
143 void EVENT_USB_Device_UnhandledControlRequest(void)
144 {
145 /* Handle HID Class specific requests */
146 switch (USB_ControlRequest.bRequest)
147 {
148 case REQ_GetReport:
149 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
150 {
151 USB_KeyboardReport_Data_t KeyboardReportData;
152
153 Endpoint_ClearSETUP();
154
155 /* Create the next keyboard report for transmission to the host */
156 CreateKeyboardReport(&KeyboardReportData);
157
158 /* Write the report data to the control endpoint */
159 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
160
161 /* Finalize the stream transfer to send the last packet or clear the host abort */
162 Endpoint_ClearOUT();
163 }
164
165 break;
166 case REQ_SetReport:
167 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
168 {
169 Endpoint_ClearSETUP();
170
171 /* Wait until the LED report has been sent by the host */
172 while (!(Endpoint_IsOUTReceived()))
173 {
174 if (USB_DeviceState == DEVICE_STATE_Unattached)
175 return;
176 }
177
178 /* Read in the LED report from the host */
179 uint8_t LEDStatus = Endpoint_Read_Byte();
180
181 /* Process the incoming LED report */
182 ProcessLEDReport(LEDStatus);
183
184 /* Clear the endpoint data */
185 Endpoint_ClearOUT();
186
187 Endpoint_ClearStatusStage();
188 }
189
190 break;
191 case REQ_GetProtocol:
192 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
193 {
194 Endpoint_ClearSETUP();
195
196 /* Write the current protocol flag to the host */
197 Endpoint_Write_Byte(UsingReportProtocol);
198
199 /* Send the flag to the host */
200 Endpoint_ClearIN();
201
202 Endpoint_ClearStatusStage();
203 }
204
205 break;
206 case REQ_SetProtocol:
207 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
208 {
209 Endpoint_ClearSETUP();
210
211 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
212 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
213
214 Endpoint_ClearStatusStage();
215 }
216
217 break;
218 case REQ_SetIdle:
219 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
220 {
221 Endpoint_ClearSETUP();
222
223 /* Get idle period in MSB, IdleCount must be multiplied by 4 to get number of milliseconds */
224 IdleCount = ((USB_ControlRequest.wValue & 0xFF00) >> 6);
225
226 Endpoint_ClearStatusStage();
227 }
228
229 break;
230 case REQ_GetIdle:
231 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
232 {
233 Endpoint_ClearSETUP();
234
235 /* Write the current idle duration to the host, must be divided by 4 before sent to host */
236 Endpoint_Write_Byte(IdleCount >> 2);
237
238 /* Send the flag to the host */
239 Endpoint_ClearIN();
240
241 Endpoint_ClearStatusStage();
242 }
243
244 break;
245 }
246 }
247
248 /** Event handler for the USB device Start Of Frame event. */
249 void EVENT_USB_Device_StartOfFrame(void)
250 {
251 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
252 if (IdleMSRemaining)
253 IdleMSRemaining--;
254 }
255
256 /** Fills the given HID report data structure with the next HID report to send to the host.
257 *
258 * \param[out] ReportData Pointer to a HID report data structure to be filled
259 */
260 void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
261 {
262 uint8_t JoyStatus_LCL = Joystick_GetStatus();
263 uint8_t ButtonStatus_LCL = Buttons_GetStatus();
264
265 uint8_t UsedKeyCodes = 0;
266
267 /* Clear the report contents */
268 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
269
270 /* Make sent key uppercase by indicating that the left shift key is pressed */
271 ReportData->Modifier = KEYBOARD_MODIFER_LEFTSHIFT;
272
273 if (JoyStatus_LCL & JOY_UP)
274 ReportData->KeyCode[UsedKeyCodes++] = 0x04; // A
275 else if (JoyStatus_LCL & JOY_DOWN)
276 ReportData->KeyCode[UsedKeyCodes++] = 0x05; // B
277
278 if (JoyStatus_LCL & JOY_LEFT)
279 ReportData->KeyCode[UsedKeyCodes++] = 0x06; // C
280 else if (JoyStatus_LCL & JOY_RIGHT)
281 ReportData->KeyCode[UsedKeyCodes++] = 0x07; // D
282
283 if (JoyStatus_LCL & JOY_PRESS)
284 ReportData->KeyCode[UsedKeyCodes++] = 0x08; // E
285
286 if (ButtonStatus_LCL & BUTTONS_BUTTON1)
287 ReportData->KeyCode[UsedKeyCodes++] = 0x09; // F
288 }
289
290 /** Processes a received LED report, and updates the board LEDs states to match.
291 *
292 * \param[in] LEDReport LED status report from the host
293 */
294 void ProcessLEDReport(uint8_t LEDReport)
295 {
296 uint8_t LEDMask = LEDS_LED2;
297
298 if (LEDReport & KEYBOARD_LED_NUMLOCK)
299 LEDMask |= LEDS_LED1;
300
301 if (LEDReport & KEYBOARD_LED_CAPSLOCK)
302 LEDMask |= LEDS_LED3;
303
304 if (LEDReport & KEYBOARD_LED_SCROLLLOCK)
305 LEDMask |= LEDS_LED4;
306
307 /* Set the status LEDs to the current Keyboard LED status */
308 LEDs_SetAllLEDs(LEDMask);
309 }
310
311 /** Sends the next HID report to the host, via the keyboard data endpoint. */
312 void SendNextReport(void)
313 {
314 static USB_KeyboardReport_Data_t PrevKeyboardReportData;
315 USB_KeyboardReport_Data_t KeyboardReportData;
316 bool SendReport = true;
317
318 /* Create the next keyboard report for transmission to the host */
319 CreateKeyboardReport(&KeyboardReportData);
320
321 /* Check to see if the report data has changed - if so a report MUST be sent */
322 SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
323
324 /* Check if the idle period is set and has elapsed */
325 if ((IdleCount != HID_IDLE_CHANGESONLY) && (!(IdleMSRemaining)))
326 {
327 /* Reset the idle time remaining counter */
328 IdleMSRemaining = IdleCount;
329
330 /* Idle period is set and has elapsed, must send a report to the host */
331 SendReport = true;
332 }
333
334 /* Select the Keyboard Report Endpoint */
335 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
336
337 /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
338 if (Endpoint_IsReadWriteAllowed() && SendReport)
339 {
340 /* Save the current report data for later comparison to check for changes */
341 PrevKeyboardReportData = KeyboardReportData;
342
343 /* Write Keyboard Report Data */
344 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
345
346 /* Finalize the stream transfer to send the last packet */
347 Endpoint_ClearIN();
348 }
349 }
350
351 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
352 void ReceiveNextReport(void)
353 {
354 /* Select the Keyboard LED Report Endpoint */
355 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
356
357 /* Check if Keyboard LED Endpoint contains a packet */
358 if (Endpoint_IsOUTReceived())
359 {
360 /* Check to see if the packet contains data */
361 if (Endpoint_IsReadWriteAllowed())
362 {
363 /* Read in the LED report from the host */
364 uint8_t LEDReport = Endpoint_Read_Byte();
365
366 /* Process the read LED report from the host */
367 ProcessLEDReport(LEDReport);
368 }
369
370 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
371 Endpoint_ClearOUT();
372 }
373 }
374
375 /** Function to manage HID report generation and transmission to the host, when in report mode. */
376 void HID_Task(void)
377 {
378 /* Device must be connected and configured for the task to run */
379 if (USB_DeviceState != DEVICE_STATE_Configured)
380 return;
381
382 /* Send the next keypress report to the host */
383 SendNextReport();
384
385 /* Process the LED report sent from the host */
386 ReceiveNextReport();
387 }