Updated makefiles to reflect new dfu-ee programming target invocations (supplied...
[pub/USBasp.git] / Demos / KeyboardHostViaInt / KeyboardHostViaInt.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 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /** \file
32 *
33 * Main source file for the KeyboardHostViaInt demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
35 */
36
37 #include "KeyboardHostViaInt.h"
38
39 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName, "LUFA KBD Host App");
41 BUTTLOADTAG(BuildTime, __TIME__);
42 BUTTLOADTAG(BuildDate, __DATE__);
43 BUTTLOADTAG(LUFAVersion, "LUFA V" LUFA_VERSION_STRING);
44
45 /* Scheduler Task List */
46 TASK_LIST
47 {
48 { Task: USB_USBTask , TaskStatus: TASK_STOP },
49 { Task: USB_Keyboard_Host , TaskStatus: TASK_STOP },
50 };
51
52
53 /** Main program entry point. This routine configures the hardware required by the application, then
54 * starts the scheduler to run the application tasks.
55 */
56 int main(void)
57 {
58 /* Disable watchdog if enabled by bootloader/fuses */
59 MCUSR &= ~(1 << WDRF);
60 wdt_disable();
61
62 /* Disable Clock Division */
63 SetSystemClockPrescaler(0);
64
65 /* Hardware Initialization */
66 SerialStream_Init(9600, false);
67 LEDs_Init();
68
69 /* Indicate USB not ready */
70 UpdateStatus(Status_USBNotReady);
71
72 /* Initialize Scheduler so that it can be used */
73 Scheduler_Init();
74
75 /* Initialize USB Subsystem */
76 USB_Init();
77
78 /* Startup message */
79 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
80 "Keyboard Host Demo running.\r\n" ESC_INVERSE_OFF));
81
82 /* Scheduling - routine never returns, so put this last in the main function */
83 Scheduler_Start();
84 }
85
86 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
87 * starts the library USB task to begin the enumeration and USB management process.
88 */
89 EVENT_HANDLER(USB_DeviceAttached)
90 {
91 puts_P(PSTR("Device Attached.\r\n"));
92 UpdateStatus(Status_USBEnumerating);
93
94 /* Start USB management task to enumerate the device */
95 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
96 }
97
98 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
99 * stops the library USB task management process.
100 */
101 EVENT_HANDLER(USB_DeviceUnattached)
102 {
103 /* Stop keyboard and USB management task */
104 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
105 Scheduler_SetTaskMode(USB_Keyboard_Host, TASK_STOP);
106
107 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
108 UpdateStatus(Status_USBNotReady);
109 }
110
111 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
112 * enumerated by the host and is now ready to be used by the application.
113 */
114 EVENT_HANDLER(USB_DeviceEnumerationComplete)
115 {
116 /* Start Keyboard Host task */
117 Scheduler_SetTaskMode(USB_Keyboard_Host, TASK_RUN);
118
119 /* Indicate device enumeration complete */
120 UpdateStatus(Status_USBReady);
121 }
122
123 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
124 EVENT_HANDLER(USB_HostError)
125 {
126 USB_ShutDown();
127
128 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
129 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
130
131 UpdateStatus(Status_HardwareError);
132 for(;;);
133 }
134
135 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occured while
136 * enumerating an attached USB device.
137 */
138 EVENT_HANDLER(USB_DeviceEnumerationFailed)
139 {
140 puts_P(PSTR(ESC_BG_RED "Dev Enum Error\r\n"));
141 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
142 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode);
143 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState);
144
145 UpdateStatus(Status_EnumerationError);
146 }
147
148 /** Task to set the configuration of the attached device after it has been enumerated, and to enable the pipe
149 * interrupts so that reports can be processed as they arrive from the device.
150 */
151 TASK(USB_Keyboard_Host)
152 {
153 uint8_t ErrorCode;
154
155 switch (USB_HostState)
156 {
157 case HOST_STATE_Addressed:
158 /* Standard request to set the device configuration to configuration 1 */
159 USB_HostRequest = (USB_Host_Request_Header_t)
160 {
161 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
162 bRequest: REQ_SetConfiguration,
163 wValue: 1,
164 wIndex: 0,
165 wLength: 0,
166 };
167
168 /* Send the request, display error and wait for device detatch if request fails */
169 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
170 {
171 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
172 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
173
174 /* Indicate error via status LEDs */
175 UpdateStatus(Status_EnumerationError);
176
177 /* Wait until USB device disconnected */
178 while (USB_IsConnected);
179 break;
180 }
181
182 USB_HostState = HOST_STATE_Configured;
183 break;
184 case HOST_STATE_Configured:
185 puts_P(PSTR("Getting Config Data.\r\n"));
186
187 /* Get and process the configuration descriptor data */
188 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
189 {
190 if (ErrorCode == ControlError)
191 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
192 else
193 puts_P(PSTR("Invalid Device.\r\n"));
194
195 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
196
197 /* Indicate error via status LEDs */
198 UpdateStatus(Status_EnumerationError);
199
200 /* Wait until USB device disconnected */
201 while (USB_IsConnected);
202 break;
203 }
204
205 /* HID class request to set the keyboard protocol to the Boot Protocol */
206 USB_HostRequest = (USB_Host_Request_Header_t)
207 {
208 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
209 bRequest: REQ_SetProtocol,
210 wValue: 0,
211 wIndex: 0,
212 wLength: 0,
213 };
214
215 /* Send the request, display error and wait for device detatch if request fails */
216 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
217 {
218 puts_P(PSTR("Control Error (Set Protocol).\r\n"));
219 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
220
221 /* Indicate error status */
222 UpdateStatus(Status_EnumerationError);
223
224 /* Wait until USB device disconnected */
225 while (USB_IsConnected);
226 break;
227 }
228
229 puts_P(PSTR("Keyboard Enumerated.\r\n"));
230
231 USB_HostState = HOST_STATE_Ready;
232 break;
233 }
234 }
235
236 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
237 * log to a serial port, or anything else that is suitable for status updates.
238 *
239 * \param CurrentStatus Current status of the system, from the KeyboardHostViaInt_StatusCodes_t enum
240 */
241 void UpdateStatus(uint8_t CurrentStatus)
242 {
243 uint8_t LEDMask = LEDS_NO_LEDS;
244
245 /* Set the LED mask to the appropriate LED mask based on the given status code */
246 switch (CurrentStatus)
247 {
248 case Status_USBNotReady:
249 LEDMask = (LEDS_LED1);
250 break;
251 case Status_USBEnumerating:
252 LEDMask = (LEDS_LED1 | LEDS_LED2);
253 break;
254 case Status_USBReady:
255 LEDMask = (LEDS_LED2);
256 break;
257 case Status_EnumerationError:
258 case Status_HardwareError:
259 LEDMask = (LEDS_LED1 | LEDS_LED3);
260 break;
261 }
262
263 /* Set the board LEDs to the new LED mask */
264 LEDs_SetAllLEDs(LEDMask);
265 }
266
267 /** Interrupt handler for the Endpoint/Pipe interrupt vector. This interrupt fires each time an enabled
268 * pipe interrupt occurs on a pipe which has had that interrupt enabled.
269 */
270 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
271 {
272 USB_KeyboardReport_Data_t KeyboardReport;
273 char PressedKey = 0;
274
275 /* Check to see if the keyboard data pipe has caused the interrupt */
276 if (Pipe_HasPipeInterrupted(KEYBOARD_DATAPIPE))
277 {
278 /* Clear the pipe interrupt, and select the keyboard pipe */
279 Pipe_ClearPipeInterrupt(KEYBOARD_DATAPIPE);
280 Pipe_SelectPipe(KEYBOARD_DATAPIPE);
281
282 /* Check to see if the pipe IN interrupt has fired */
283 if (USB_INT_HasOccurred(PIPE_INT_IN) && USB_INT_IsEnabled(PIPE_INT_IN))
284 {
285 /* Clear interrupt flag */
286 USB_INT_Clear(PIPE_INT_IN);
287
288 /* Read in keyboard report data */
289 Pipe_Read_Stream_LE(&KeyboardReport, sizeof(KeyboardReport));
290
291 /* Clear the IN endpoint, ready for next data packet */
292 Pipe_ClearCurrentBank();
293
294 LEDs_ChangeLEDs(LEDS_LED1, (KeyboardReport.Modifier) ? LEDS_LED1 : 0);
295
296 /* Check if a key has been pressed */
297 if (KeyboardReport.KeyCode)
298 {
299 /* Toggle status LED to indicate keypress */
300 if (LEDs_GetLEDs() & LEDS_LED4)
301 LEDs_TurnOffLEDs(LEDS_LED4);
302 else
303 LEDs_TurnOnLEDs(LEDS_LED4);
304
305 /* Retrieve pressed key character if alphanumeric */
306 if ((KeyboardReport.KeyCode >= 0x04) && (KeyboardReport.KeyCode <= 0x1D))
307 PressedKey = (KeyboardReport.KeyCode - 0x04) + 'A';
308 else if ((KeyboardReport.KeyCode >= 0x1E) && (KeyboardReport.KeyCode <= 0x27))
309 PressedKey = (KeyboardReport.KeyCode - 0x1E) + '0';
310 else if (KeyboardReport.KeyCode == 0x2C)
311 PressedKey = ' ';
312 else if (KeyboardReport.KeyCode == 0x28)
313 PressedKey = '\n';
314
315 /* Print the pressed key character out through the serial port if valid */
316 if (PressedKey)
317 putchar(PressedKey);
318 }
319 }
320 }
321 }