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