Changed over www.fourwalledcubicle.com links to the new www.lufa-lib.org redirect...
[pub/USBasp.git] / Demos / Host / LowLevel / StillImageHost / StillImageHost.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2010.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all 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 /** Main program entry point. This routine configures the hardware required by the application, then
40 * enters a loop to run the application tasks in sequence.
41 */
42 int main(void)
43 {
44 SetupHardware();
45
46 puts_P(PSTR(ESC_FG_CYAN "Still Image Host Demo running.\r\n" ESC_FG_WHITE));
47
48 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
49 sei();
50
51 for (;;)
52 {
53 StillImage_Task();
54 USB_USBTask();
55 }
56 }
57
58 /** Configures the board hardware and chip peripherals for the demo's functionality. */
59 void SetupHardware(void)
60 {
61 /* Disable watchdog if enabled by bootloader/fuses */
62 MCUSR &= ~(1 << WDRF);
63 wdt_disable();
64
65 /* Disable Clock Division */
66 CLKPR = (1 << CLKPCE);
67 CLKPR = 0;
68
69 /* Hardware Initialization */
70 SerialStream_Init(9600, false);
71 LEDs_Init();
72 USB_Init();
73 }
74
75 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
76 * starts the library USB task to begin the enumeration and USB management process.
77 */
78 void EVENT_USB_Host_DeviceAttached(void)
79 {
80 puts_P(PSTR(ESC_FG_GREEN "Device Attached.\r\n" ESC_FG_WHITE));
81 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
82 }
83
84 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
85 * stops the library USB task management process.
86 */
87 void EVENT_USB_Host_DeviceUnattached(void)
88 {
89 puts_P(PSTR(ESC_FG_GREEN "\r\nDevice Unattached.\r\n" ESC_FG_WHITE));
90 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
91 }
92
93 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
94 * enumerated by the host and is now ready to be used by the application.
95 */
96 void EVENT_USB_Host_DeviceEnumerationComplete(void)
97 {
98 LEDs_SetAllLEDs(LEDMASK_USB_READY);
99 }
100
101 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
102 void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
103 {
104 USB_ShutDown();
105
106 printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
107 " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
108
109 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
110 for(;;);
111 }
112
113 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
114 * enumerating an attached USB device.
115 */
116 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
117 const uint8_t SubErrorCode)
118 {
119 printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
120 " -- Error Code %d\r\n"
121 " -- Sub Error Code %d\r\n"
122 " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
123
124 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
125 }
126
127 /** Task to set the configuration of the attached device after it has been enumerated, and to print device information
128 * through the serial port.
129 */
130 void StillImage_Task(void)
131 {
132 uint8_t ErrorCode;
133
134 switch (USB_HostState)
135 {
136 case HOST_STATE_Addressed:
137 puts_P(PSTR("Getting Config Data.\r\n"));
138
139 /* Get and process the configuration descriptor data */
140 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
141 {
142 if (ErrorCode == ControlError)
143 puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
144 else
145 puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
146
147 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
148
149 /* Indicate error via status LEDs */
150 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
151
152 /* Wait until USB device disconnected */
153 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
154 break;
155 }
156
157 /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
158 if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
159 {
160 printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
161 " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
162
163 /* Indicate error via status LEDs */
164 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
165
166 /* Wait until USB device disconnected */
167 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
168 break;
169 }
170
171 puts_P(PSTR("Still Image Device Enumerated.\r\n"));
172 USB_HostState = HOST_STATE_Configured;
173 break;
174 case HOST_STATE_Configured:
175 /* Indicate device busy via the status LEDs */
176 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
177
178 puts_P(PSTR("Retrieving Device Info...\r\n"));
179
180 PIMA_SendBlock = (PIMA_Container_t)
181 {
182 .DataLength = PIMA_COMMAND_SIZE(0),
183 .Type = PIMA_CONTAINER_CommandBlock,
184 .Code = PIMA_OPERATION_GETDEVICEINFO,
185 .TransactionID = 0x00000000,
186 .Params = {},
187 };
188
189 /* Send the GETDEVICEINFO block */
190 SImage_SendBlockHeader();
191
192 /* Receive the response data block */
193 if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
194 {
195 ShowCommandError(ErrorCode, false);
196
197 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
198 break;
199 }
200
201 /* Calculate the size of the returned device info data structure */
202 uint16_t DeviceInfoSize = (PIMA_ReceivedBlock.DataLength - PIMA_COMMAND_SIZE(0));
203
204 /* Create a buffer large enough to hold the entire device info */
205 uint8_t DeviceInfo[DeviceInfoSize];
206
207 /* Read in the data block data (containing device info) */
208 SImage_ReadData(DeviceInfo, DeviceInfoSize);
209
210 /* Once all the data has been read, the pipe must be cleared before the response can be sent */
211 Pipe_ClearIN();
212
213 /* Create a pointer for walking through the info dataset */
214 uint8_t* DeviceInfoPos = DeviceInfo;
215
216 /* Skip over the data before the unicode device information strings */
217 DeviceInfoPos += 8; // Skip to VendorExtensionDesc String
218 DeviceInfoPos += (1 + UNICODE_STRING_LENGTH(*DeviceInfoPos)); // Skip over VendorExtensionDesc String
219 DeviceInfoPos += 2; // Skip over FunctionalMode
220 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Supported Operations Array
221 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Supported Events Array
222 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Supported Device Properties Array
223 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Capture Formats Array
224 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Image Formats Array
225
226 /* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
227 char Manufacturer[*DeviceInfoPos];
228 UnicodeToASCII(DeviceInfoPos, Manufacturer);
229 printf_P(PSTR(" Manufacturer: %s\r\n"), Manufacturer);
230
231 DeviceInfoPos += 1 + UNICODE_STRING_LENGTH(*DeviceInfoPos); // Skip over Manufacturer String
232
233 /* Extract and convert the Model Unicode string to ASCII and print it through the USART */
234 char Model[*DeviceInfoPos];
235 UnicodeToASCII(DeviceInfoPos, Model);
236 printf_P(PSTR(" Model: %s\r\n"), Model);
237
238 DeviceInfoPos += 1 + UNICODE_STRING_LENGTH(*DeviceInfoPos); // Skip over Model String
239
240 /* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
241 char DeviceVersion[*DeviceInfoPos];
242 UnicodeToASCII(DeviceInfoPos, DeviceVersion);
243 printf_P(PSTR(" Device Version: %s\r\n"), DeviceVersion);
244
245 /* Receive the final response block from the device */
246 if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
247 {
248 ShowCommandError(ErrorCode, false);
249
250 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
251 break;
252 }
253
254 /* Verify that the command completed successfully */
255 if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
256 {
257 ShowCommandError(PIMA_ReceivedBlock.Code, true);
258
259 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
260 break;
261 }
262
263 puts_P(PSTR("Opening Session...\r\n"));
264
265 PIMA_SendBlock = (PIMA_Container_t)
266 {
267 .DataLength = PIMA_COMMAND_SIZE(1),
268 .Type = PIMA_CONTAINER_CommandBlock,
269 .Code = PIMA_OPERATION_OPENSESSION,
270 .TransactionID = 0x00000000,
271 .Params = {0x00000001},
272 };
273
274 /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
275 SImage_SendBlockHeader();
276
277 /* Receive the response block from the device */
278 if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
279 {
280 ShowCommandError(ErrorCode, false);
281
282 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
283 break;
284 }
285
286 /* Verify that the command completed successfully */
287 if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
288 {
289 ShowCommandError(PIMA_ReceivedBlock.Code, true);
290
291 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
292 break;
293 }
294
295 puts_P(PSTR("Closing Session...\r\n"));
296
297 PIMA_SendBlock = (PIMA_Container_t)
298 {
299 .DataLength = PIMA_COMMAND_SIZE(1),
300 .Type = PIMA_CONTAINER_CommandBlock,
301 .Code = PIMA_OPERATION_CLOSESESSION,
302 .TransactionID = 0x00000001,
303 .Params = {0x00000001},
304 };
305
306 /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
307 SImage_SendBlockHeader();
308
309 /* Receive the response block from the device */
310 if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
311 {
312 ShowCommandError(ErrorCode, false);
313
314 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
315 break;
316 }
317
318 /* Verify that the command completed successfully */
319 if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
320 {
321 ShowCommandError(PIMA_ReceivedBlock.Code, true);
322
323 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
324 break;
325 }
326
327 puts_P(PSTR("Done.\r\n"));
328
329 /* Indicate device no longer busy */
330 LEDs_SetAllLEDs(LEDMASK_USB_READY);
331
332 USB_HostState = HOST_STATE_WaitForDeviceRemoval;
333 break;
334 }
335 }
336
337 /** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
338 * strings which contain ASCII printable characters only.
339 *
340 * \param[in] UnicodeString Pointer to a Unicode encoded input string
341 * \param[out] Buffer Pointer to a buffer where the converted ASCII string should be stored
342 */
343 void UnicodeToASCII(uint8_t* UnicodeString,
344 char* Buffer)
345 {
346 /* Get the number of characters in the string, skip to the start of the string data */
347 uint8_t CharactersRemaining = *(UnicodeString++);
348
349 /* Loop through the entire unicode string */
350 while (CharactersRemaining--)
351 {
352 /* Load in the next unicode character (only the lower byte, as only Unicode coded ASCII is supported) */
353 *(Buffer++) = *UnicodeString;
354
355 /* Jump to the next unicode character */
356 UnicodeString += 2;
357 }
358
359 /* Null terminate the string */
360 *Buffer = 0;
361 }
362
363 /** Displays a PIMA command error via the device's serial port.
364 *
365 * \param[in] ErrorCode Error code of the function which failed to complete successfully
366 * \param[in] ResponseCodeError Indicates if the error is due to a command failed indication from the device, or a communication failure
367 */
368 void ShowCommandError(uint8_t ErrorCode,
369 bool ResponseCodeError)
370 {
371 char* FailureType = ((ResponseCodeError) ? PSTR("Response Code != OK") : PSTR("Transaction Fail"));
372
373 printf_P(PSTR(ESC_FG_RED "Command Error (%S).\r\n"
374 " -- Error Code %d\r\n" ESC_FG_WHITE), FailureType, ErrorCode);
375
376 /* Indicate error via status LEDs */
377 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
378 }
379