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