Rewritten event system to remove all macros, to make user code clearer.
[pub/USBasp.git] / Demos / Host / GenericHIDHost / GenericHIDHost.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 GenericHIDHost demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
35 */
36
37 #include "GenericHIDHost.h"
38
39 /* Scheduler Task List */
40 TASK_LIST
41 {
42 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
43 { .Task = USB_HID_Host , .TaskStatus = TASK_STOP },
44 };
45
46
47 /** Main program entry point. This routine configures the hardware required by the application, then
48 * starts the scheduler to run the application tasks.
49 */
50 int main(void)
51 {
52 /* Disable watchdog if enabled by bootloader/fuses */
53 MCUSR &= ~(1 << WDRF);
54 wdt_disable();
55
56 /* Disable clock division */
57 clock_prescale_set(clock_div_1);
58
59 /* Hardware Initialization */
60 SerialStream_Init(9600, false);
61 LEDs_Init();
62
63 /* Indicate USB not ready */
64 UpdateStatus(Status_USBNotReady);
65
66 /* Initialize Scheduler so that it can be used */
67 Scheduler_Init();
68
69 /* Initialize USB Subsystem */
70 USB_Init();
71
72 /* Start-up message */
73 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
74 "Generic HID Host Demo running.\r\n" ESC_INVERSE_OFF));
75
76 /* Scheduling - routine never returns, so put this last in the main function */
77 Scheduler_Start();
78 }
79
80 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
81 * starts the library USB task to begin the enumeration and USB management process.
82 */
83 void EVENT_USB_DeviceAttached(void)
84 {
85 puts_P(PSTR("Device Attached.\r\n"));
86 UpdateStatus(Status_USBEnumerating);
87
88 /* Start USB management task to enumerate the device */
89 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
90 }
91
92 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
93 * stops the library USB task management process.
94 */
95 void EVENT_USB_DeviceUnattached(void)
96 {
97 /* Stop HID and USB management task */
98 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
99 Scheduler_SetTaskMode(USB_HID_Host, TASK_STOP);
100
101 puts_P(PSTR("Device Unattached.\r\n"));
102 UpdateStatus(Status_USBNotReady);
103 }
104
105 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
106 * enumerated by the host and is now ready to be used by the application.
107 */
108 void EVENT_USB_DeviceEnumerationComplete(void)
109 {
110 /* Start HID Host task */
111 Scheduler_SetTaskMode(USB_HID_Host, TASK_RUN);
112
113 /* Indicate device enumeration complete */
114 UpdateStatus(Status_USBReady);
115 }
116
117 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
118 void EVENT_USB_HostError(const uint8_t ErrorCode)
119 {
120 USB_ShutDown();
121
122 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
123 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
124
125 UpdateStatus(Status_HardwareError);
126 for(;;);
127 }
128
129 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
130 * enumerating an attached USB device.
131 */
132 void EVENT_USB_DeviceEnumerationFailed(const uint8_t ErrorCode, const uint8_t SubErrorCode)
133 {
134 puts_P(PSTR(ESC_BG_RED "Dev Enum Error\r\n"));
135 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
136 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode);
137 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState);
138
139 UpdateStatus(Status_EnumerationError);
140 }
141
142 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
143 * log to a serial port, or anything else that is suitable for status updates.
144 *
145 * \param CurrentStatus Current status of the system, from the GenericHIDHost_StatusCodes_t enum
146 */
147 void UpdateStatus(uint8_t CurrentStatus)
148 {
149 uint8_t LEDMask = LEDS_NO_LEDS;
150
151 /* Set the LED mask to the appropriate LED mask based on the given status code */
152 switch (CurrentStatus)
153 {
154 case Status_USBNotReady:
155 LEDMask = (LEDS_LED1);
156 break;
157 case Status_USBEnumerating:
158 LEDMask = (LEDS_LED1 | LEDS_LED2);
159 break;
160 case Status_USBReady:
161 LEDMask = (LEDS_LED2);
162 break;
163 case Status_EnumerationError:
164 case Status_HardwareError:
165 LEDMask = (LEDS_LED1 | LEDS_LED3);
166 break;
167 }
168
169 /* Set the board LEDs to the new LED mask */
170 LEDs_SetAllLEDs(LEDMask);
171 }
172
173 /** Reads in and processes the next report from the attached device, displaying the report
174 * contents on the board LEDs and via the serial port.
175 */
176 void ReadNextReport(void)
177 {
178 /* Select and unfreeze HID data IN pipe */
179 Pipe_SelectPipe(HID_DATA_IN_PIPE);
180 Pipe_Unfreeze();
181
182 /* Check to see if a packet has been received */
183 if (!(Pipe_IsINReceived()))
184 {
185 /* Refreeze HID data IN pipe */
186 Pipe_Freeze();
187
188 return;
189 }
190
191 /* Ensure pipe contains data before trying to read from it */
192 if (Pipe_IsReadWriteAllowed())
193 {
194 uint8_t ReportINData[Pipe_BytesInPipe()];
195
196 /* Read in HID report data */
197 Pipe_Read_Stream_LE(&ReportINData, sizeof(ReportINData));
198
199 /* Print report data through the serial port */
200 for (uint16_t CurrByte = 0; CurrByte < sizeof(ReportINData); CurrByte++)
201 printf_P(PSTR("0x%02X "), ReportINData[CurrByte]);
202
203 puts_P(PSTR("\r\n"));
204 }
205
206 /* Clear the IN endpoint, ready for next data packet */
207 Pipe_ClearIN();
208
209 /* Refreeze HID data IN pipe */
210 Pipe_Freeze();
211 }
212
213 /** Writes a report to the attached device.
214 *
215 * \param ReportOUTData Buffer containing the report to send to the device
216 * \param ReportIndex Index of the report in the device (zero if the device does not use multiple reports)
217 * \param ReportType Type of report to send, either HID_REPORTTYPE_OUTPUT or HID_REPORTTYPE_FEATURE
218 * \param ReportLength Length of the report to send
219 */
220 void WriteNextReport(uint8_t* ReportOUTData, uint8_t ReportIndex, uint8_t ReportType, uint16_t ReportLength)
221 {
222 /* Select and unfreeze HID data OUT pipe */
223 Pipe_SelectPipe(HID_DATA_OUT_PIPE);
224
225 /* Not all HID devices have an OUT endpoint (some require OUT reports to be sent over the
226 * control endpoint instead) - check to see if the OUT endpoint has been initialized */
227 if (Pipe_IsConfigured())
228 {
229 Pipe_Unfreeze();
230
231 /* Ensure pipe is ready to be written to before continuing */
232 if (!(Pipe_IsOUTReady()))
233 {
234 /* Refreeze the data OUT pipe */
235 Pipe_Freeze();
236
237 return;
238 }
239
240 /* If the report index is used, send it before the report data */
241 if (ReportIndex)
242 Pipe_Write_Byte(ReportIndex);
243
244 /* Write out HID report data */
245 Pipe_Write_Stream_LE(ReportOUTData, ReportLength);
246
247 /* Clear the OUT endpoint, send last data packet */
248 Pipe_ClearOUT();
249
250 /* Refreeze the data OUT pipe */
251 Pipe_Freeze();
252 }
253 else
254 {
255 /* Class specific request to send a HID report to the device */
256 USB_ControlRequest = (USB_Request_Header_t)
257 {
258 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
259 .bRequest = REQ_SetReport,
260 .wValue = ((ReportType << 8) | ReportIndex),
261 .wIndex = 0,
262 .wLength = ReportLength,
263 };
264
265 /* Select the control pipe for the request transfer */
266 Pipe_SelectPipe(PIPE_CONTROLPIPE);
267
268 /* Send the request to the device */
269 USB_Host_SendControlRequest(ReportOUTData);
270 }
271 }
272
273 /** Task to set the configuration of the attached device after it has been enumerated, and to read and process
274 * HID reports from the device and to send reports if desired.
275 */
276 TASK(USB_HID_Host)
277 {
278 uint8_t ErrorCode;
279
280 /* Switch to determine what user-application handled host state the host state machine is in */
281 switch (USB_HostState)
282 {
283 case HOST_STATE_Addressed:
284 /* Standard request to set the device configuration to configuration 1 */
285 USB_ControlRequest = (USB_Request_Header_t)
286 {
287 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
288 .bRequest = REQ_SetConfiguration,
289 .wValue = 1,
290 .wIndex = 0,
291 .wLength = 0,
292 };
293
294 /* Select the control pipe for the request transfer */
295 Pipe_SelectPipe(PIPE_CONTROLPIPE);
296
297 /* Send the request, display error and wait for device detach if request fails */
298 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
299 {
300 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
301 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
302
303 /* Indicate error status */
304 UpdateStatus(Status_EnumerationError);
305
306 /* Wait until USB device disconnected */
307 while (USB_IsConnected);
308 break;
309 }
310
311 USB_HostState = HOST_STATE_Configured;
312 break;
313 case HOST_STATE_Configured:
314 puts_P(PSTR("Getting Config Data.\r\n"));
315
316 /* Get and process the configuration descriptor data */
317 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
318 {
319 if (ErrorCode == ControlError)
320 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
321 else
322 puts_P(PSTR("Invalid Device.\r\n"));
323
324 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
325
326 /* Indicate error status */
327 UpdateStatus(Status_EnumerationError);
328
329 /* Wait until USB device disconnected */
330 while (USB_IsConnected);
331 break;
332 }
333
334 puts_P(PSTR("HID Device Enumerated.\r\n"));
335
336 USB_HostState = HOST_STATE_Ready;
337 break;
338 case HOST_STATE_Ready:
339 ReadNextReport();
340
341 break;
342 }
343 }