Fixed Endpoint_Write_Control_Stream_* functions not sending a terminating IN when...
[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 /** 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
66 for (;;)
67 {
68 HID_Task();
69 USB_USBTask();
70 }
71 }
72
73 /** Configures the board hardware and chip peripherals for the demo's functionality. */
74 void SetupHardware(void)
75 {
76 /* Disable watchdog if enabled by bootloader/fuses */
77 MCUSR &= ~(1 << WDRF);
78 wdt_disable();
79
80 /* Disable clock division */
81 clock_prescale_set(clock_div_1);
82
83 /* Hardware Initialization */
84 Joystick_Init();
85 LEDs_Init();
86 USB_Init();
87 Buttons_Init();
88 }
89
90 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
91 * starts the library USB task to begin the enumeration and USB management process.
92 */
93 void EVENT_USB_Device_Connect(void)
94 {
95 /* Indicate USB enumerating */
96 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
97
98 /* Default to report protocol on connect */
99 UsingReportProtocol = true;
100 }
101
102 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
103 * the status LEDs.
104 */
105 void EVENT_USB_Device_Disconnect(void)
106 {
107 /* Indicate USB not ready */
108 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
109 }
110
111 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
112 * of the USB device after enumeration, and configures the keyboard device endpoints.
113 */
114 void EVENT_USB_Device_ConfigurationChanged(void)
115 {
116 /* Indicate USB connected and ready */
117 LEDs_SetAllLEDs(LEDMASK_USB_READY);
118
119 /* Setup Keyboard Keycode Report Endpoint */
120 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
121 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
122 ENDPOINT_BANK_SINGLE)))
123 {
124 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
125 }
126
127 /* Setup Keyboard LED Report Endpoint */
128 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
129 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
130 ENDPOINT_BANK_SINGLE)))
131 {
132 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
133 }
134
135 USB_Device_EnableSOFEvents();
136 }
137
138 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific
139 * control requests that are not handled internally by the USB library (including the HID commands, which are
140 * all issued via the control endpoint), so that they can be handled appropriately for the application.
141 */
142 void EVENT_USB_Device_UnhandledControlRequest(void)
143 {
144 /* Handle HID Class specific requests */
145 switch (USB_ControlRequest.bRequest)
146 {
147 case REQ_GetReport:
148 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
149 {
150 USB_KeyboardReport_Data_t KeyboardReportData;
151
152 Endpoint_ClearSETUP();
153
154 /* Create the next keyboard report for transmission to the host */
155 CreateKeyboardReport(&KeyboardReportData);
156
157 /* Write the report data to the control endpoint */
158 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
159
160 /* Finalize the stream transfer to send the last packet or clear the host abort */
161 Endpoint_ClearOUT();
162 }
163
164 break;
165 case REQ_SetReport:
166 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
167 {
168 Endpoint_ClearSETUP();
169
170 /* Wait until the LED report has been sent by the host */
171 while (!(Endpoint_IsOUTReceived()))
172 {
173 if (USB_DeviceState == DEVICE_STATE_Unattached)
174 return;
175 }
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 Endpoint_ClearStatusStage();
187 }
188
189 break;
190 case REQ_GetProtocol:
191 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
192 {
193 Endpoint_ClearSETUP();
194
195 /* Write the current protocol flag to the host */
196 Endpoint_Write_Byte(UsingReportProtocol);
197
198 /* Send the flag to the host */
199 Endpoint_ClearIN();
200
201 Endpoint_ClearStatusStage();
202 }
203
204 break;
205 case REQ_SetProtocol:
206 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
207 {
208 Endpoint_ClearSETUP();
209
210 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
211 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
212
213 Endpoint_ClearStatusStage();
214 }
215
216 break;
217 case REQ_SetIdle:
218 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
219 {
220 Endpoint_ClearSETUP();
221
222 /* Get idle period in MSB, IdleCount must be multiplied by 4 to get number of milliseconds */
223 IdleCount = ((USB_ControlRequest.wValue & 0xFF00) >> 6);
224
225 Endpoint_ClearStatusStage();
226 }
227
228 break;
229 case REQ_GetIdle:
230 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
231 {
232 Endpoint_ClearSETUP();
233
234 /* Write the current idle duration to the host, must be divided by 4 before sent to host */
235 Endpoint_Write_Byte(IdleCount >> 2);
236
237 /* Send the flag to the host */
238 Endpoint_ClearIN();
239
240 Endpoint_ClearStatusStage();
241 }
242
243 break;
244 }
245 }
246
247 /** Event handler for the USB device Start Of Frame event. */
248 void EVENT_USB_Device_StartOfFrame(void)
249 {
250 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
251 if (IdleMSRemaining)
252 IdleMSRemaining--;
253 }
254
255 /** Fills the given HID report data structure with the next HID report to send to the host.
256 *
257 * \param[out] ReportData Pointer to a HID report data structure to be filled
258 */
259 void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
260 {
261 static uint8_t PrevUsedKeyCodes;
262 uint8_t UsedKeyCodes = 0;
263 uint8_t JoyStatus_LCL = Joystick_GetStatus();
264 uint8_t ButtonStatus_LCL = Buttons_GetStatus();
265
266 /* Clear the report contents */
267 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
268
269 if (JoyStatus_LCL & JOY_UP)
270 ReportData->KeyCode[UsedKeyCodes++] = 0x04; // A
271 else if (JoyStatus_LCL & JOY_DOWN)
272 ReportData->KeyCode[UsedKeyCodes++] = 0x05; // B
273
274 if (JoyStatus_LCL & JOY_LEFT)
275 ReportData->KeyCode[UsedKeyCodes++] = 0x06; // C
276 else if (JoyStatus_LCL & JOY_RIGHT)
277 ReportData->KeyCode[UsedKeyCodes++] = 0x07; // D
278
279 if (JoyStatus_LCL & JOY_PRESS)
280 ReportData->KeyCode[UsedKeyCodes++] = 0x08; // E
281
282 if (ButtonStatus_LCL & BUTTONS_BUTTON1)
283 ReportData->KeyCode[UsedKeyCodes++] = 0x09; // F
284
285 /* The host will ignore the device if we add a new keycode to the report while another keycode is currently
286 * being sent (i.e. the user has pressed another key while a key is already being pressed) - we need to intersperse
287 * the two reports with a zeroed report to force the host to accept the additional keys */
288 if (UsedKeyCodes != PrevUsedKeyCodes)
289 {
290 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
291 PrevUsedKeyCodes = UsedKeyCodes;
292 }
293 }
294
295 /** Processes a received LED report, and updates the board LEDs states to match.
296 *
297 * \param[in] LEDReport LED status report from the host
298 */
299 void ProcessLEDReport(uint8_t LEDReport)
300 {
301 uint8_t LEDMask = LEDS_LED2;
302
303 if (LEDReport & 0x01) // NUM Lock
304 LEDMask |= LEDS_LED1;
305
306 if (LEDReport & 0x02) // CAPS Lock
307 LEDMask |= LEDS_LED3;
308
309 if (LEDReport & 0x04) // SCROLL Lock
310 LEDMask |= LEDS_LED4;
311
312 /* Set the status LEDs to the current Keyboard LED status */
313 LEDs_SetAllLEDs(LEDMask);
314 }
315
316 /** Sends the next HID report to the host, via the keyboard data endpoint. */
317 void SendNextReport(void)
318 {
319 static USB_KeyboardReport_Data_t PrevKeyboardReportData;
320 USB_KeyboardReport_Data_t KeyboardReportData;
321 bool SendReport = true;
322
323 /* Create the next keyboard report for transmission to the host */
324 CreateKeyboardReport(&KeyboardReportData);
325
326 /* Check to see if the report data has changed - if so a report MUST be sent */
327 SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
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 /* Save the current report data for later comparison to check for changes */
346 PrevKeyboardReportData = KeyboardReportData;
347
348 /* Write Keyboard Report Data */
349 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
350
351 /* Finalize the stream transfer to send the last packet */
352 Endpoint_ClearIN();
353 }
354 }
355
356 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
357 void ReceiveNextReport(void)
358 {
359 /* Select the Keyboard LED Report Endpoint */
360 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
361
362 /* Check if Keyboard LED Endpoint contains a packet */
363 if (Endpoint_IsOUTReceived())
364 {
365 /* Check to see if the packet contains data */
366 if (Endpoint_IsReadWriteAllowed())
367 {
368 /* Read in the LED report from the host */
369 uint8_t LEDReport = Endpoint_Read_Byte();
370
371 /* Process the read LED report from the host */
372 ProcessLEDReport(LEDReport);
373 }
374
375 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
376 Endpoint_ClearOUT();
377 }
378 }
379
380 /** Function to manage HID report generation and transmission to the host, when in report mode. */
381 void HID_Task(void)
382 {
383 /* Device must be connected and configured for the task to run */
384 if (USB_DeviceState != DEVICE_STATE_Configured)
385 return;
386
387 /* Send the next keypress report to the host */
388 SendNextReport();
389
390 /* Process the LED report sent from the host */
391 ReceiveNextReport();
392 }