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 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName
, "LUFA SIMG Host App");
41 BUTTLOADTAG(BuildTime
, __TIME__
);
42 BUTTLOADTAG(BuildDate
, __DATE__
);
44 /* Scheduler Task List */
47 { Task
: USB_USBTask
, TaskStatus
: TASK_STOP
},
48 { Task
: USB_SImage_Host
, TaskStatus
: TASK_STOP
},
52 /** Main program entry point. This routine configures the hardware required by the application, then
53 * starts the scheduler to run the application tasks.
57 /* Disable watchdog if enabled by bootloader/fuses */
58 MCUSR
&= ~(1 << WDRF
);
61 /* Disable Clock Division */
62 CLKPR
= (1 << CLKPCE
);
65 /* Hardware Initialization */
66 SerialStream_Init(9600, false);
69 /* Indicate USB not ready */
70 UpdateStatus(Status_USBNotReady
);
72 /* Initialize Scheduler so that it can be used */
75 /* Initialize USB Subsystem */
79 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
80 "Still Image Host Demo running.\r\n" ESC_INVERSE_OFF
));
82 /* Scheduling - routine never returns, so put this last in the main function */
86 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
87 * starts the library USB task to begin the enumeration and USB management process.
89 EVENT_HANDLER(USB_DeviceAttached
)
91 puts_P(PSTR("Device Attached.\r\n"));
92 UpdateStatus(Status_USBEnumerating
);
94 /* Start USB management task to enumerate the device */
95 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
98 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
99 * stops the library USB task management process.
101 EVENT_HANDLER(USB_DeviceUnattached
)
103 /* Stop USB management and Still Image tasks */
104 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
105 Scheduler_SetTaskMode(USB_SImage_Host
, TASK_STOP
);
107 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
108 UpdateStatus(Status_USBNotReady
);
111 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
112 * enumerated by the host and is now ready to be used by the application.
114 EVENT_HANDLER(USB_DeviceEnumerationComplete
)
116 /* Once device is fully enumerated, start the Still Image Host task */
117 Scheduler_SetTaskMode(USB_SImage_Host
, TASK_RUN
);
119 /* Indicate device enumeration complete */
120 UpdateStatus(Status_USBReady
);
123 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
124 EVENT_HANDLER(USB_HostError
)
128 puts_P(PSTR(ESC_BG_RED
"Host Mode Error\r\n"));
129 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
131 UpdateStatus(Status_HardwareError
);
135 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occured while
136 * enumerating an attached USB device.
138 EVENT_HANDLER(USB_DeviceEnumerationFailed
)
140 puts_P(PSTR(ESC_BG_RED
"Dev Enum Error\r\n"));
141 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
142 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode
);
143 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState
);
145 UpdateStatus(Status_EnumerationError
);
148 /** Task to set the configuration of the attached device after it has been enumerated, and to print device information
149 * through the serial port.
151 TASK(USB_SImage_Host
)
155 switch (USB_HostState
)
157 case HOST_STATE_Addressed
:
158 /* Standard request to set the device configuration to configuration 1 */
159 USB_HostRequest
= (USB_Host_Request_Header_t
)
161 bmRequestType
: (REQDIR_HOSTTODEVICE
| REQTYPE_STANDARD
| REQREC_DEVICE
),
162 bRequest
: REQ_SetConfiguration
,
168 /* Send the request, display error and wait for device detatch if request fails */
169 if (USB_Host_SendControlRequest(NULL
) != HOST_SENDCONTROL_Successful
)
171 puts_P(PSTR("Control error.\r\n"));
173 /* Indicate error via status LEDs */
174 UpdateStatus(Status_EnumerationError
);
176 /* Wait until USB device disconnected */
177 while (USB_IsConnected
);
181 USB_HostState
= HOST_STATE_Configured
;
183 case HOST_STATE_Configured
:
184 puts_P(PSTR("Getting Config Data.\r\n"));
186 /* Get and process the configuration descriptor data */
187 if ((ErrorCode
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
)
189 if (ErrorCode
== ControlError
)
190 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
192 puts_P(PSTR("Invalid Device.\r\n"));
194 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
196 /* Indicate error via status LEDs */
197 UpdateStatus(Status_EnumerationError
);
199 /* Wait until USB device disconnected */
200 while (USB_IsConnected
);
204 puts_P(PSTR("Still Image Device Enumerated.\r\n"));
206 USB_HostState
= HOST_STATE_Ready
;
208 case HOST_STATE_Ready
:
209 /* Indicate device busy via the status LEDs */
210 UpdateStatus(Status_Busy
);
212 puts_P(PSTR("Retrieving Device Info...\r\n"));
214 PIMA_SendBlock
= (PIMA_Container_t
)
216 DataLength
: PIMA_COMMAND_SIZE(0),
217 Type
: CType_CommandBlock
,
218 Code
: PIMA_OPERATION_GETDEVICEINFO
,
219 TransactionID
: 0x00000000,
223 /* Send the GETDEVICEINFO block */
224 SImage_SendBlockHeader();
226 /* Recieve the response data block */
227 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
229 ShowCommandError(ErrorCode
, false);
233 /* Calculate the size of the returned device info data structure */
234 uint16_t DeviceInfoSize
= (PIMA_ReceivedBlock
.DataLength
- PIMA_COMMAND_SIZE(0));
236 /* Create a buffer large enough to hold the entire device info */
237 uint8_t DeviceInfo
[DeviceInfoSize
];
239 /* Read in the data block data (containing device info) */
240 SImage_ReadData(DeviceInfo
, DeviceInfoSize
);
242 /* Once all the data has been read, the pipe must be cleared before the response can be sent */
243 Pipe_ClearCurrentBank();
245 /* Create a pointer for walking through the info dataset */
246 uint8_t* DeviceInfoPos
= DeviceInfo
;
248 /* Skip over the data before the unicode device information strings */
249 DeviceInfoPos
+= 8; // Skip to VendorExtensionDesc String
250 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over VendorExtensionDesc String
251 DeviceInfoPos
+= 2; // Skip over FunctionalMode
252 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over OperationCode Array
253 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over EventCode Array
254 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over DevicePropCode Array
255 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over ObjectFormatCode Array
256 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over ObjectFormatCode Array
258 /* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
259 char Manufacturer
[*DeviceInfoPos
];
260 UnicodeToASCII(DeviceInfoPos
, Manufacturer
);
261 printf_P(PSTR(" Manufacturer: %s\r\n"), Manufacturer
);
263 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over Manufacturer String
265 /* Extract and convert the Model Unicode string to ASCII and print it through the USART */
266 char Model
[*DeviceInfoPos
];
267 UnicodeToASCII(DeviceInfoPos
, Model
);
268 printf_P(PSTR(" Model: %s\r\n"), Model
);
270 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over Model String
272 /* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
273 char DeviceVersion
[*DeviceInfoPos
];
274 UnicodeToASCII(DeviceInfoPos
, DeviceVersion
);
275 printf_P(PSTR(" Device Version: %s\r\n"), DeviceVersion
);
277 /* Recieve the final response block from the device */
278 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
280 ShowCommandError(ErrorCode
, false);
284 /* Verify that the command completed successfully */
285 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
287 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
291 puts_P(PSTR("Opening Session...\r\n"));
293 PIMA_SendBlock
= (PIMA_Container_t
)
295 DataLength
: PIMA_COMMAND_SIZE(1),
296 Type
: CType_CommandBlock
,
297 Code
: PIMA_OPERATION_OPENSESSION
,
298 TransactionID
: 0x00000000,
299 Params
: {0x00000001},
302 /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
303 SImage_SendBlockHeader();
305 /* Recieve the response block from the device */
306 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
308 ShowCommandError(ErrorCode
, false);
312 /* Verify that the command completed successfully */
313 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
315 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
319 puts_P(PSTR("Closing Session...\r\n"));
321 PIMA_SendBlock
= (PIMA_Container_t
)
323 DataLength
: PIMA_COMMAND_SIZE(1),
324 Type
: CType_CommandBlock
,
325 Code
: PIMA_OPERATION_CLOSESESSION
,
326 TransactionID
: 0x00000001,
327 Params
: {0x00000001},
330 /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
331 SImage_SendBlockHeader();
333 /* Recieve the response block from the device */
334 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
336 ShowCommandError(ErrorCode
, false);
340 /* Verify that the command completed successfully */
341 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
343 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
347 puts_P(PSTR("Done.\r\n"));
349 /* Indicate device no longer busy */
350 UpdateStatus(Status_USBReady
);
352 /* Wait until USB device disconnected */
353 while (USB_IsConnected
);
359 /** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
360 * strings which contain ASCII printable characters only.
362 * \param UnicodeString Pointer to a Unicode encoded input string
363 * \param Buffer Pointer to a buffer where the converted ASCII string should be stored
365 void UnicodeToASCII(uint8_t* UnicodeString
, char* Buffer
)
367 /* Get the number of characters in the string, skip to the start of the string data */
368 uint8_t CharactersRemaining
= *(UnicodeString
++);
370 /* Loop through the entire unicode string */
371 while (CharactersRemaining
--)
373 /* Load in the next unicode character (only the lower byte, only Unicode coded ASCII supported) */
374 *(Buffer
++) = *UnicodeString
;
376 /* Jump to the next unicode character */
380 /* Null terminate the string */
384 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
385 * log to a serial port, or anything else that is suitable for status updates.
387 * \param CurrentStatus Current status of the system, from the StillImageHost_StatusCodes_t enum
389 void UpdateStatus(uint8_t CurrentStatus
)
391 uint8_t LEDMask
= LEDS_NO_LEDS
;
393 /* Set the LED mask to the appropriate LED mask based on the given status code */
394 switch (CurrentStatus
)
396 case Status_USBNotReady
:
397 LEDMask
= (LEDS_LED1
);
399 case Status_USBEnumerating
:
400 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
402 case Status_USBReady
:
403 LEDMask
= (LEDS_LED2
);
405 case Status_EnumerationError
:
406 case Status_HardwareError
:
407 case Status_PIMACommandError
:
408 LEDMask
= (LEDS_LED1
| LEDS_LED3
);
411 LEDMask
= (LEDS_LED1
| LEDS_LED3
| LEDS_LED4
);
415 /* Set the board LEDs to the new LED mask */
416 LEDs_SetAllLEDs(LEDMask
);
419 /** Displays a PIMA command error via the device's serial port.
421 * \param ErrorCode Error code of the function which failed to complete successfully
422 * \param ResponseErrorCode Indicates if the error is due to a command failed indication from the device, or a communication failure
424 void ShowCommandError(uint8_t ErrorCode
, bool ResponseCodeError
)
426 char* FailureType
= ((ResponseCodeError
) ?
PSTR("Response Code != OK") : PSTR("Transaction Fail"));
428 printf_P(PSTR(ESC_BG_RED
"Command Error (%S).\r\n"), FailureType
);
429 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
431 /* Indicate error via status LEDs */
432 UpdateStatus(Status_PIMACommandError
);
434 /* Wait until USB device disconnected */
435 while (USB_IsConnected
);