The USB_Host_SendControlRequest() function no longer automatically selects the Contro...
[pub/USBasp.git] / Demos / Host / StillImageHost / StillImageHost.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 StillImageHost demo. This file contains the main tasks of
34 * the demo and is responsible for the initial application hardware configuration.
35 */
36
37 #include "StillImageHost.h"
38
39 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName, "LUFA SIMG Host App");
41 BUTTLOADTAG(BuildTime, __TIME__);
42 BUTTLOADTAG(BuildDate, __DATE__);
43
44 /* Scheduler Task List */
45 TASK_LIST
46 {
47 { Task: USB_USBTask , TaskStatus: TASK_STOP },
48 { Task: USB_SImage_Host , TaskStatus: TASK_STOP },
49 };
50
51
52 /** Main program entry point. This routine configures the hardware required by the application, then
53 * starts the scheduler to run the application tasks.
54 */
55 int main(void)
56 {
57 /* Disable watchdog if enabled by bootloader/fuses */
58 MCUSR &= ~(1 << WDRF);
59 wdt_disable();
60
61 /* Disable Clock Division */
62 CLKPR = (1 << CLKPCE);
63 CLKPR = 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 /* Start-up message */
79 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
80 "Still Image 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 USB management and Still Image tasks */
104 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
105 Scheduler_SetTaskMode(USB_SImage_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 /* Once device is fully enumerated, start the Still Image Host task */
117 Scheduler_SetTaskMode(USB_SImage_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 occurred 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 print device information
149 * through the serial port.
150 */
151 TASK(USB_SImage_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 /* Select the control pipe for the request transfer */
169 Pipe_SelectPipe(PIPE_CONTROLPIPE);
170
171 /* Send the request, display error and wait for device detach if request fails */
172 if (USB_Host_SendControlRequest(NULL) != HOST_SENDCONTROL_Successful)
173 {
174 puts_P(PSTR("Control error.\r\n"));
175
176 /* Indicate error via status LEDs */
177 UpdateStatus(Status_EnumerationError);
178
179 /* Wait until USB device disconnected */
180 while (USB_IsConnected);
181 break;
182 }
183
184 USB_HostState = HOST_STATE_Configured;
185 break;
186 case HOST_STATE_Configured:
187 puts_P(PSTR("Getting Config Data.\r\n"));
188
189 /* Get and process the configuration descriptor data */
190 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
191 {
192 if (ErrorCode == ControlError)
193 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
194 else
195 puts_P(PSTR("Invalid Device.\r\n"));
196
197 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
198
199 /* Indicate error via status LEDs */
200 UpdateStatus(Status_EnumerationError);
201
202 /* Wait until USB device disconnected */
203 while (USB_IsConnected);
204 break;
205 }
206
207 puts_P(PSTR("Still Image Device Enumerated.\r\n"));
208
209 USB_HostState = HOST_STATE_Ready;
210 break;
211 case HOST_STATE_Ready:
212 /* Indicate device busy via the status LEDs */
213 UpdateStatus(Status_Busy);
214
215 puts_P(PSTR("Retrieving Device Info...\r\n"));
216
217 PIMA_SendBlock = (PIMA_Container_t)
218 {
219 DataLength: PIMA_COMMAND_SIZE(0),
220 Type: CType_CommandBlock,
221 Code: PIMA_OPERATION_GETDEVICEINFO,
222 TransactionID: 0x00000000,
223 Params: {},
224 };
225
226 /* Send the GETDEVICEINFO block */
227 SImage_SendBlockHeader();
228
229 /* Receive the response data block */
230 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
231 {
232 ShowCommandError(ErrorCode, false);
233 break;
234 }
235
236 /* Calculate the size of the returned device info data structure */
237 uint16_t DeviceInfoSize = (PIMA_ReceivedBlock.DataLength - PIMA_COMMAND_SIZE(0));
238
239 /* Create a buffer large enough to hold the entire device info */
240 uint8_t DeviceInfo[DeviceInfoSize];
241
242 /* Read in the data block data (containing device info) */
243 SImage_ReadData(DeviceInfo, DeviceInfoSize);
244
245 /* Once all the data has been read, the pipe must be cleared before the response can be sent */
246 Pipe_ClearCurrentBank();
247
248 /* Create a pointer for walking through the info dataset */
249 uint8_t* DeviceInfoPos = DeviceInfo;
250
251 /* Skip over the data before the unicode device information strings */
252 DeviceInfoPos += 8; // Skip to VendorExtensionDesc String
253 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over VendorExtensionDesc String
254 DeviceInfoPos += 2; // Skip over FunctionalMode
255 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over OperationCode Array
256 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over EventCode Array
257 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over DevicePropCode Array
258 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over ObjectFormatCode Array
259 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over ObjectFormatCode Array
260
261 /* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
262 char Manufacturer[*DeviceInfoPos];
263 UnicodeToASCII(DeviceInfoPos, Manufacturer);
264 printf_P(PSTR(" Manufacturer: %s\r\n"), Manufacturer);
265
266 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over Manufacturer String
267
268 /* Extract and convert the Model Unicode string to ASCII and print it through the USART */
269 char Model[*DeviceInfoPos];
270 UnicodeToASCII(DeviceInfoPos, Model);
271 printf_P(PSTR(" Model: %s\r\n"), Model);
272
273 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over Model String
274
275 /* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
276 char DeviceVersion[*DeviceInfoPos];
277 UnicodeToASCII(DeviceInfoPos, DeviceVersion);
278 printf_P(PSTR(" Device Version: %s\r\n"), DeviceVersion);
279
280 /* Receive the final response block from the device */
281 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
282 {
283 ShowCommandError(ErrorCode, false);
284 break;
285 }
286
287 /* Verify that the command completed successfully */
288 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
289 {
290 ShowCommandError(PIMA_ReceivedBlock.Code, true);
291 break;
292 }
293
294 puts_P(PSTR("Opening Session...\r\n"));
295
296 PIMA_SendBlock = (PIMA_Container_t)
297 {
298 DataLength: PIMA_COMMAND_SIZE(1),
299 Type: CType_CommandBlock,
300 Code: PIMA_OPERATION_OPENSESSION,
301 TransactionID: 0x00000000,
302 Params: {0x00000001},
303 };
304
305 /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
306 SImage_SendBlockHeader();
307
308 /* Receive the response block from the device */
309 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
310 {
311 ShowCommandError(ErrorCode, false);
312 break;
313 }
314
315 /* Verify that the command completed successfully */
316 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
317 {
318 ShowCommandError(PIMA_ReceivedBlock.Code, true);
319 break;
320 }
321
322 puts_P(PSTR("Closing Session...\r\n"));
323
324 PIMA_SendBlock = (PIMA_Container_t)
325 {
326 DataLength: PIMA_COMMAND_SIZE(1),
327 Type: CType_CommandBlock,
328 Code: PIMA_OPERATION_CLOSESESSION,
329 TransactionID: 0x00000001,
330 Params: {0x00000001},
331 };
332
333 /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
334 SImage_SendBlockHeader();
335
336 /* Receive the response block from the device */
337 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
338 {
339 ShowCommandError(ErrorCode, false);
340 break;
341 }
342
343 /* Verify that the command completed successfully */
344 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
345 {
346 ShowCommandError(PIMA_ReceivedBlock.Code, true);
347 break;
348 }
349
350 puts_P(PSTR("Done.\r\n"));
351
352 /* Indicate device no longer busy */
353 UpdateStatus(Status_USBReady);
354
355 /* Wait until USB device disconnected */
356 while (USB_IsConnected);
357
358 break;
359 }
360 }
361
362 /** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
363 * strings which contain ASCII printable characters only.
364 *
365 * \param UnicodeString Pointer to a Unicode encoded input string
366 * \param Buffer Pointer to a buffer where the converted ASCII string should be stored
367 */
368 void UnicodeToASCII(uint8_t* UnicodeString, char* Buffer)
369 {
370 /* Get the number of characters in the string, skip to the start of the string data */
371 uint8_t CharactersRemaining = *(UnicodeString++);
372
373 /* Loop through the entire unicode string */
374 while (CharactersRemaining--)
375 {
376 /* Load in the next unicode character (only the lower byte, only Unicode coded ASCII supported) */
377 *(Buffer++) = *UnicodeString;
378
379 /* Jump to the next unicode character */
380 UnicodeString += 2;
381 }
382
383 /* Null terminate the string */
384 *Buffer = 0;
385 }
386
387 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
388 * log to a serial port, or anything else that is suitable for status updates.
389 *
390 * \param CurrentStatus Current status of the system, from the StillImageHost_StatusCodes_t enum
391 */
392 void UpdateStatus(uint8_t CurrentStatus)
393 {
394 uint8_t LEDMask = LEDS_NO_LEDS;
395
396 /* Set the LED mask to the appropriate LED mask based on the given status code */
397 switch (CurrentStatus)
398 {
399 case Status_USBNotReady:
400 LEDMask = (LEDS_LED1);
401 break;
402 case Status_USBEnumerating:
403 LEDMask = (LEDS_LED1 | LEDS_LED2);
404 break;
405 case Status_USBReady:
406 LEDMask = (LEDS_LED2);
407 break;
408 case Status_EnumerationError:
409 case Status_HardwareError:
410 case Status_PIMACommandError:
411 LEDMask = (LEDS_LED1 | LEDS_LED3);
412 break;
413 case Status_Busy:
414 LEDMask = (LEDS_LED1 | LEDS_LED3 | LEDS_LED4);
415 break;
416 }
417
418 /* Set the board LEDs to the new LED mask */
419 LEDs_SetAllLEDs(LEDMask);
420 }
421
422 /** Displays a PIMA command error via the device's serial port.
423 *
424 * \param ErrorCode Error code of the function which failed to complete successfully
425 * \param ResponseErrorCode Indicates if the error is due to a command failed indication from the device, or a communication failure
426 */
427 void ShowCommandError(uint8_t ErrorCode, bool ResponseCodeError)
428 {
429 char* FailureType = ((ResponseCodeError) ? PSTR("Response Code != OK") : PSTR("Transaction Fail"));
430
431 printf_P(PSTR(ESC_BG_RED "Command Error (%S).\r\n"), FailureType);
432 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
433
434 /* Indicate error via status LEDs */
435 UpdateStatus(Status_PIMACommandError);
436
437 /* Wait until USB device disconnected */
438 while (USB_IsConnected);
439 }