3 Copyright (C) Dean Camera, 2009.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
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.
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
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.
37 #include "StillImageHost.h"
39 /* Scheduler Task List */
42 { .Task
= USB_USBTask
, .TaskStatus
= TASK_STOP
},
43 { .Task
= USB_SImage_Host
, .TaskStatus
= TASK_STOP
},
47 /** Main program entry point. This routine configures the hardware required by the application, then
48 * starts the scheduler to run the application tasks.
52 /* Disable watchdog if enabled by bootloader/fuses */
53 MCUSR
&= ~(1 << WDRF
);
56 /* Disable Clock Division */
57 CLKPR
= (1 << CLKPCE
);
60 /* Hardware Initialization */
61 SerialStream_Init(9600, false);
64 /* Indicate USB not ready */
65 UpdateStatus(Status_USBNotReady
);
67 /* Initialize Scheduler so that it can be used */
70 /* Initialize USB Subsystem */
73 /* Start-up message */
74 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
75 "Still Image Host Demo running.\r\n" ESC_INVERSE_OFF
));
77 /* Scheduling - routine never returns, so put this last in the main function */
81 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
82 * starts the library USB task to begin the enumeration and USB management process.
84 EVENT_HANDLER(USB_DeviceAttached
)
86 puts_P(PSTR("Device Attached.\r\n"));
87 UpdateStatus(Status_USBEnumerating
);
89 /* Start USB management task to enumerate the device */
90 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
93 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
94 * stops the library USB task management process.
96 EVENT_HANDLER(USB_DeviceUnattached
)
98 /* Stop USB management and Still Image tasks */
99 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
100 Scheduler_SetTaskMode(USB_SImage_Host
, TASK_STOP
);
102 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
103 UpdateStatus(Status_USBNotReady
);
106 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
107 * enumerated by the host and is now ready to be used by the application.
109 EVENT_HANDLER(USB_DeviceEnumerationComplete
)
111 /* Once device is fully enumerated, start the Still Image Host task */
112 Scheduler_SetTaskMode(USB_SImage_Host
, TASK_RUN
);
114 /* Indicate device enumeration complete */
115 UpdateStatus(Status_USBReady
);
118 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
119 EVENT_HANDLER(USB_HostError
)
123 puts_P(PSTR(ESC_BG_RED
"Host Mode Error\r\n"));
124 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
126 UpdateStatus(Status_HardwareError
);
130 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
131 * enumerating an attached USB device.
133 EVENT_HANDLER(USB_DeviceEnumerationFailed
)
135 puts_P(PSTR(ESC_BG_RED
"Dev Enum Error\r\n"));
136 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
137 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode
);
138 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState
);
140 UpdateStatus(Status_EnumerationError
);
143 /** Task to set the configuration of the attached device after it has been enumerated, and to print device information
144 * through the serial port.
146 TASK(USB_SImage_Host
)
150 switch (USB_HostState
)
152 case HOST_STATE_Addressed
:
153 /* Standard request to set the device configuration to configuration 1 */
154 USB_ControlRequest
= (USB_Request_Header_t
)
156 .bmRequestType
= (REQDIR_HOSTTODEVICE
| REQTYPE_STANDARD
| REQREC_DEVICE
),
157 .bRequest
= REQ_SetConfiguration
,
163 /* Select the control pipe for the request transfer */
164 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
166 /* Send the request, display error and wait for device detach if request fails */
167 if (USB_Host_SendControlRequest(NULL
) != HOST_SENDCONTROL_Successful
)
169 puts_P(PSTR("Control error.\r\n"));
171 /* Indicate error via status LEDs */
172 UpdateStatus(Status_EnumerationError
);
174 /* Wait until USB device disconnected */
175 while (USB_IsConnected
);
179 USB_HostState
= HOST_STATE_Configured
;
181 case HOST_STATE_Configured
:
182 puts_P(PSTR("Getting Config Data.\r\n"));
184 /* Get and process the configuration descriptor data */
185 if ((ErrorCode
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
)
187 if (ErrorCode
== ControlError
)
188 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
190 puts_P(PSTR("Invalid Device.\r\n"));
192 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
194 /* Indicate error via status LEDs */
195 UpdateStatus(Status_EnumerationError
);
197 /* Wait until USB device disconnected */
198 while (USB_IsConnected
);
202 puts_P(PSTR("Still Image Device Enumerated.\r\n"));
204 USB_HostState
= HOST_STATE_Ready
;
206 case HOST_STATE_Ready
:
207 /* Indicate device busy via the status LEDs */
208 UpdateStatus(Status_Busy
);
210 puts_P(PSTR("Retrieving Device Info...\r\n"));
212 PIMA_SendBlock
= (PIMA_Container_t
)
214 .DataLength
= PIMA_COMMAND_SIZE(0),
215 .Type
= CType_CommandBlock
,
216 .Code
= PIMA_OPERATION_GETDEVICEINFO
,
217 .TransactionID
= 0x00000000,
221 /* Send the GETDEVICEINFO block */
222 SImage_SendBlockHeader();
224 /* Receive the response data block */
225 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
227 ShowCommandError(ErrorCode
, false);
231 /* Calculate the size of the returned device info data structure */
232 uint16_t DeviceInfoSize
= (PIMA_ReceivedBlock
.DataLength
- PIMA_COMMAND_SIZE(0));
234 /* Create a buffer large enough to hold the entire device info */
235 uint8_t DeviceInfo
[DeviceInfoSize
];
237 /* Read in the data block data (containing device info) */
238 SImage_ReadData(DeviceInfo
, DeviceInfoSize
);
240 /* Once all the data has been read, the pipe must be cleared before the response can be sent */
243 /* Create a pointer for walking through the info dataset */
244 uint8_t* DeviceInfoPos
= DeviceInfo
;
246 /* Skip over the data before the unicode device information strings */
247 DeviceInfoPos
+= 8; // Skip to VendorExtensionDesc String
248 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over VendorExtensionDesc String
249 DeviceInfoPos
+= 2; // Skip over FunctionalMode
250 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over OperationCode Array
251 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over EventCode Array
252 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over DevicePropCode Array
253 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over ObjectFormatCode Array
254 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over ObjectFormatCode Array
256 /* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
257 char Manufacturer
[*DeviceInfoPos
];
258 UnicodeToASCII(DeviceInfoPos
, Manufacturer
);
259 printf_P(PSTR(" Manufacturer: %s\r\n"), Manufacturer
);
261 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over Manufacturer String
263 /* Extract and convert the Model Unicode string to ASCII and print it through the USART */
264 char Model
[*DeviceInfoPos
];
265 UnicodeToASCII(DeviceInfoPos
, Model
);
266 printf_P(PSTR(" Model: %s\r\n"), Model
);
268 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over Model String
270 /* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
271 char DeviceVersion
[*DeviceInfoPos
];
272 UnicodeToASCII(DeviceInfoPos
, DeviceVersion
);
273 printf_P(PSTR(" Device Version: %s\r\n"), DeviceVersion
);
275 /* Receive the final response block from the device */
276 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
278 ShowCommandError(ErrorCode
, false);
282 /* Verify that the command completed successfully */
283 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
285 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
289 puts_P(PSTR("Opening Session...\r\n"));
291 PIMA_SendBlock
= (PIMA_Container_t
)
293 .DataLength
= PIMA_COMMAND_SIZE(1),
294 .Type
= CType_CommandBlock
,
295 .Code
= PIMA_OPERATION_OPENSESSION
,
296 .TransactionID
= 0x00000000,
297 .Params
= {0x00000001},
300 /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
301 SImage_SendBlockHeader();
303 /* Receive the response block from the device */
304 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
306 ShowCommandError(ErrorCode
, false);
310 /* Verify that the command completed successfully */
311 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
313 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
317 puts_P(PSTR("Closing Session...\r\n"));
319 PIMA_SendBlock
= (PIMA_Container_t
)
321 .DataLength
= PIMA_COMMAND_SIZE(1),
322 .Type
= CType_CommandBlock
,
323 .Code
= PIMA_OPERATION_CLOSESESSION
,
324 .TransactionID
= 0x00000001,
325 .Params
= {0x00000001},
328 /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
329 SImage_SendBlockHeader();
331 /* Receive the response block from the device */
332 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
334 ShowCommandError(ErrorCode
, false);
338 /* Verify that the command completed successfully */
339 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
341 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
345 puts_P(PSTR("Done.\r\n"));
347 /* Indicate device no longer busy */
348 UpdateStatus(Status_USBReady
);
350 /* Wait until USB device disconnected */
351 while (USB_IsConnected
);
357 /** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
358 * strings which contain ASCII printable characters only.
360 * \param UnicodeString Pointer to a Unicode encoded input string
361 * \param Buffer Pointer to a buffer where the converted ASCII string should be stored
363 void UnicodeToASCII(uint8_t* UnicodeString
, char* Buffer
)
365 /* Get the number of characters in the string, skip to the start of the string data */
366 uint8_t CharactersRemaining
= *(UnicodeString
++);
368 /* Loop through the entire unicode string */
369 while (CharactersRemaining
--)
371 /* Load in the next unicode character (only the lower byte, only Unicode coded ASCII supported) */
372 *(Buffer
++) = *UnicodeString
;
374 /* Jump to the next unicode character */
378 /* Null terminate the string */
382 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
383 * log to a serial port, or anything else that is suitable for status updates.
385 * \param CurrentStatus Current status of the system, from the StillImageHost_StatusCodes_t enum
387 void UpdateStatus(uint8_t CurrentStatus
)
389 uint8_t LEDMask
= LEDS_NO_LEDS
;
391 /* Set the LED mask to the appropriate LED mask based on the given status code */
392 switch (CurrentStatus
)
394 case Status_USBNotReady
:
395 LEDMask
= (LEDS_LED1
);
397 case Status_USBEnumerating
:
398 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
400 case Status_USBReady
:
401 LEDMask
= (LEDS_LED2
);
403 case Status_EnumerationError
:
404 case Status_HardwareError
:
405 case Status_PIMACommandError
:
406 LEDMask
= (LEDS_LED1
| LEDS_LED3
);
409 LEDMask
= (LEDS_LED1
| LEDS_LED3
| LEDS_LED4
);
413 /* Set the board LEDs to the new LED mask */
414 LEDs_SetAllLEDs(LEDMask
);
417 /** Displays a PIMA command error via the device's serial port.
419 * \param ErrorCode Error code of the function which failed to complete successfully
420 * \param ResponseCodeError Indicates if the error is due to a command failed indication from the device, or a communication failure
422 void ShowCommandError(uint8_t ErrorCode
, bool ResponseCodeError
)
424 char* FailureType
= ((ResponseCodeError
) ?
PSTR("Response Code != OK") : PSTR("Transaction Fail"));
426 printf_P(PSTR(ESC_BG_RED
"Command Error (%S).\r\n"), FailureType
);
427 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
429 /* Indicate error via status LEDs */
430 UpdateStatus(Status_PIMACommandError
);
432 /* Wait until USB device disconnected */
433 while (USB_IsConnected
);