d4e7cca732614cd577ec4ed0d97c40de4579db67
[pub/USBasp.git] / Demos / Device / GenericHID / GenericHID.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 GenericHID demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #include "GenericHID.h"
38
39 /* Scheduler Task List */
40 TASK_LIST
41 {
42 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
43 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
44 #endif
45
46 { .Task = USB_HID_Report , .TaskStatus = TASK_STOP },
47 };
48
49 /** Static buffer to hold the last received report from the host, so that it can be echoed back in the next sent report */
50 static uint8_t LastReceived[GENERIC_REPORT_SIZE];
51
52
53 /** Main program entry point. This routine configures the hardware required by the application, then
54 * starts the scheduler to run the USB management task.
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 clock_prescale_set(clock_div_1);
64
65 /* Indicate USB not ready */
66 UpdateStatus(Status_USBNotReady);
67
68 /* Initialize Scheduler so that it can be used */
69 Scheduler_Init();
70
71 /* Initialize USB Subsystem */
72 USB_Init();
73
74 /* Scheduling - routine never returns, so put this last in the main function */
75 Scheduler_Start();
76 }
77
78 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
79 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
80 * asynchronously when they arrive rather than when the control endpoint is polled manually.
81 */
82 EVENT_HANDLER(USB_Reset)
83 {
84 #if defined(INTERRUPT_CONTROL_ENDPOINT)
85 /* Select the control endpoint */
86 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
87
88 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
89 USB_INT_Enable(ENDPOINT_INT_SETUP);
90 #endif
91 }
92
93 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
94 * starts the library USB task to begin the enumeration and USB management process.
95 */
96 EVENT_HANDLER(USB_Connect)
97 {
98 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
99 /* Start USB management task */
100 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
101 #endif
102
103 /* Indicate USB enumerating */
104 UpdateStatus(Status_USBEnumerating);
105 }
106
107 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
108 * the status LEDs and stops the USB management task.
109 */
110 EVENT_HANDLER(USB_Disconnect)
111 {
112 /* Stop running HID reporting and USB management tasks */
113 Scheduler_SetTaskMode(USB_HID_Report, TASK_STOP);
114
115 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
116 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
117 #endif
118
119 /* Indicate USB not ready */
120 UpdateStatus(Status_USBNotReady);
121 }
122
123 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
124 * of the USB device after enumeration, and configures the generic HID device endpoints.
125 */
126 EVENT_HANDLER(USB_ConfigurationChanged)
127 {
128 /* Setup Generic IN Report Endpoint */
129 Endpoint_ConfigureEndpoint(GENERIC_IN_EPNUM, EP_TYPE_INTERRUPT,
130 ENDPOINT_DIR_IN, GENERIC_EPSIZE,
131 ENDPOINT_BANK_SINGLE);
132
133 /* Setup Generic OUT Report Endpoint */
134 Endpoint_ConfigureEndpoint(GENERIC_OUT_EPNUM, EP_TYPE_INTERRUPT,
135 ENDPOINT_DIR_OUT, GENERIC_EPSIZE,
136 ENDPOINT_BANK_SINGLE);
137
138 /* Indicate USB connected and ready */
139 UpdateStatus(Status_USBReady);
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 EVENT_HANDLER(USB_UnhandledControlPacket)
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 uint8_t GenericData[GENERIC_REPORT_SIZE];
155
156 Endpoint_ClearSETUP();
157
158 CreateGenericHIDReport(GenericData);
159
160 /* Write the report data to the control endpoint */
161 Endpoint_Write_Control_Stream_LE(&GenericData, sizeof(GenericData));
162
163 /* Finalize the stream transfer to send the last packet or clear the host abort */
164 Endpoint_ClearOUT();
165 }
166
167 break;
168 case REQ_SetReport:
169 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
170 {
171 uint8_t GenericData[GENERIC_REPORT_SIZE];
172
173 Endpoint_ClearSETUP();
174
175 /* Wait until the generic report has been sent by the host */
176 while (!(Endpoint_IsOUTReceived()));
177
178 Endpoint_Read_Control_Stream_LE(&GenericData, sizeof(GenericData));
179
180 ProcessGenericHIDReport(GenericData);
181
182 /* Clear the endpoint data */
183 Endpoint_ClearOUT();
184
185 /* Wait until the host is ready to receive the request confirmation */
186 while (!(Endpoint_IsINReady()));
187
188 /* Handshake the request by sending an empty IN packet */
189 Endpoint_ClearIN();
190 }
191
192 break;
193 }
194 }
195
196 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
197 * log to a serial port, or anything else that is suitable for status updates.
198 *
199 * \param CurrentStatus Current status of the system, from the GenericHID_StatusCodes_t enum
200 */
201 void UpdateStatus(uint8_t CurrentStatus)
202 {
203 uint8_t LEDMask = LEDS_NO_LEDS;
204
205 /* Set the LED mask to the appropriate LED mask based on the given status code */
206 switch (CurrentStatus)
207 {
208 case Status_USBNotReady:
209 LEDMask = (LEDS_LED1);
210 break;
211 case Status_USBEnumerating:
212 LEDMask = (LEDS_LED1 | LEDS_LED2);
213 break;
214 case Status_USBReady:
215 LEDMask = (LEDS_LED2 | LEDS_LED4);
216 break;
217 }
218
219 /* Set the board LEDs to the new LED mask */
220 LEDs_SetAllLEDs(LEDMask);
221 }
222
223 /** Function to process the lest received report from the host.
224 *
225 * \param DataArray Pointer to a buffer where the last report data is stored
226 */
227 void ProcessGenericHIDReport(uint8_t* DataArray)
228 {
229 /*
230 This is where you need to process the reports being sent from the host to the device.
231 DataArray is an array holding the last report from the host. This function is called
232 each time the host has sent a report to the device.
233 */
234
235 for (uint8_t i = 0; i < GENERIC_REPORT_SIZE; i++)
236 LastReceived[i] = DataArray[i];
237 }
238
239 /** Function to create the next report to send back to the host at the next reporting interval.
240 *
241 * \param DataArray Pointer to a buffer where the next report data should be stored
242 */
243 void CreateGenericHIDReport(uint8_t* DataArray)
244 {
245 /*
246 This is where you need to create reports to be sent to the host from the device. This
247 function is called each time the host is ready to accept a new report. DataArray is
248 an array to hold the report to the host.
249 */
250
251 for (uint8_t i = 0; i < GENERIC_REPORT_SIZE; i++)
252 DataArray[i] = LastReceived[i];
253 }
254
255 TASK(USB_HID_Report)
256 {
257 /* Check if the USB system is connected to a host */
258 if (USB_IsConnected)
259 {
260 Endpoint_SelectEndpoint(GENERIC_OUT_EPNUM);
261
262 /* Check to see if a packet has been sent from the host */
263 if (Endpoint_IsOUTReceived())
264 {
265 /* Check to see if the packet contains data */
266 if (Endpoint_IsReadWriteAllowed())
267 {
268 /* Create a temporary buffer to hold the read in report from the host */
269 uint8_t GenericData[GENERIC_REPORT_SIZE];
270
271 /* Read Generic Report Data */
272 Endpoint_Read_Stream_LE(&GenericData, sizeof(GenericData));
273
274 /* Process Generic Report Data */
275 ProcessGenericHIDReport(GenericData);
276 }
277
278 /* Finalize the stream transfer to send the last packet */
279 Endpoint_ClearOUT();
280 }
281
282 Endpoint_SelectEndpoint(GENERIC_IN_EPNUM);
283
284 /* Check to see if the host is ready to accept another packet */
285 if (Endpoint_IsINReady())
286 {
287 /* Create a temporary buffer to hold the report to send to the host */
288 uint8_t GenericData[GENERIC_REPORT_SIZE];
289
290 /* Create Generic Report Data */
291 CreateGenericHIDReport(GenericData);
292
293 /* Write Generic Report Data */
294 Endpoint_Write_Stream_LE(&GenericData, sizeof(GenericData));
295
296 /* Finalize the stream transfer to send the last packet */
297 Endpoint_ClearIN();
298 }
299 }
300 }
301
302 #if defined(INTERRUPT_CONTROL_ENDPOINT)
303 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
304 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
305 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
306 * controller.
307 */
308 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
309 {
310 /* Save previously selected endpoint before selecting a new endpoint */
311 uint8_t PrevSelectedEndpoint = Endpoint_GetCurrentEndpoint();
312
313 /* Check if the control endpoint has received a request */
314 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
315 {
316 /* Clear the endpoint interrupt */
317 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP);
318
319 /* Process the control request */
320 USB_USBTask();
321
322 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
323 USB_INT_Clear(ENDPOINT_INT_SETUP);
324 }
325
326 /* Restore previously selected endpoint */
327 Endpoint_SelectEndpoint(PrevSelectedEndpoint);
328 }
329 #endif