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