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