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 */
78 /* Start-up message */
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 occurred 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 /* Select the control pipe for the request transfer */
169 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
171 /* Send the request, display error and wait for device detach if request fails */
172 if (USB_Host_SendControlRequest(NULL
) != HOST_SENDCONTROL_Successful
)
174 puts_P(PSTR("Control error.\r\n"));
176 /* Indicate error via status LEDs */
177 UpdateStatus(Status_EnumerationError
);
179 /* Wait until USB device disconnected */
180 while (USB_IsConnected
);
184 USB_HostState
= HOST_STATE_Configured
;
186 case HOST_STATE_Configured
:
187 puts_P(PSTR("Getting Config Data.\r\n"));
189 /* Get and process the configuration descriptor data */
190 if ((ErrorCode
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
)
192 if (ErrorCode
== ControlError
)
193 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
195 puts_P(PSTR("Invalid Device.\r\n"));
197 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
199 /* Indicate error via status LEDs */
200 UpdateStatus(Status_EnumerationError
);
202 /* Wait until USB device disconnected */
203 while (USB_IsConnected
);
207 puts_P(PSTR("Still Image Device Enumerated.\r\n"));
209 USB_HostState
= HOST_STATE_Ready
;
211 case HOST_STATE_Ready
:
212 /* Indicate device busy via the status LEDs */
213 UpdateStatus(Status_Busy
);
215 puts_P(PSTR("Retrieving Device Info...\r\n"));
217 PIMA_SendBlock
= (PIMA_Container_t
)
219 DataLength
: PIMA_COMMAND_SIZE(0),
220 Type
: CType_CommandBlock
,
221 Code
: PIMA_OPERATION_GETDEVICEINFO
,
222 TransactionID
: 0x00000000,
226 /* Send the GETDEVICEINFO block */
227 SImage_SendBlockHeader();
229 /* Receive the response data block */
230 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
232 ShowCommandError(ErrorCode
, false);
236 /* Calculate the size of the returned device info data structure */
237 uint16_t DeviceInfoSize
= (PIMA_ReceivedBlock
.DataLength
- PIMA_COMMAND_SIZE(0));
239 /* Create a buffer large enough to hold the entire device info */
240 uint8_t DeviceInfo
[DeviceInfoSize
];
242 /* Read in the data block data (containing device info) */
243 SImage_ReadData(DeviceInfo
, DeviceInfoSize
);
245 /* Once all the data has been read, the pipe must be cleared before the response can be sent */
246 Pipe_ClearCurrentBank();
248 /* Create a pointer for walking through the info dataset */
249 uint8_t* DeviceInfoPos
= DeviceInfo
;
251 /* Skip over the data before the unicode device information strings */
252 DeviceInfoPos
+= 8; // Skip to VendorExtensionDesc String
253 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over VendorExtensionDesc String
254 DeviceInfoPos
+= 2; // Skip over FunctionalMode
255 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over OperationCode Array
256 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over EventCode Array
257 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over DevicePropCode Array
258 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over ObjectFormatCode Array
259 DeviceInfoPos
+= (4 + (*(uint32_t*)DeviceInfoPos
<< 1)); // Skip over ObjectFormatCode Array
261 /* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
262 char Manufacturer
[*DeviceInfoPos
];
263 UnicodeToASCII(DeviceInfoPos
, Manufacturer
);
264 printf_P(PSTR(" Manufacturer: %s\r\n"), Manufacturer
);
266 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over Manufacturer String
268 /* Extract and convert the Model Unicode string to ASCII and print it through the USART */
269 char Model
[*DeviceInfoPos
];
270 UnicodeToASCII(DeviceInfoPos
, Model
);
271 printf_P(PSTR(" Model: %s\r\n"), Model
);
273 DeviceInfoPos
+= ((*DeviceInfoPos
<< 1) + 1); // Skip over Model String
275 /* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
276 char DeviceVersion
[*DeviceInfoPos
];
277 UnicodeToASCII(DeviceInfoPos
, DeviceVersion
);
278 printf_P(PSTR(" Device Version: %s\r\n"), DeviceVersion
);
280 /* Receive the final response block from the device */
281 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
283 ShowCommandError(ErrorCode
, false);
287 /* Verify that the command completed successfully */
288 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
290 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
294 puts_P(PSTR("Opening Session...\r\n"));
296 PIMA_SendBlock
= (PIMA_Container_t
)
298 DataLength
: PIMA_COMMAND_SIZE(1),
299 Type
: CType_CommandBlock
,
300 Code
: PIMA_OPERATION_OPENSESSION
,
301 TransactionID
: 0x00000000,
302 Params
: {0x00000001},
305 /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
306 SImage_SendBlockHeader();
308 /* Receive the response block from the device */
309 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
311 ShowCommandError(ErrorCode
, false);
315 /* Verify that the command completed successfully */
316 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
318 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
322 puts_P(PSTR("Closing Session...\r\n"));
324 PIMA_SendBlock
= (PIMA_Container_t
)
326 DataLength
: PIMA_COMMAND_SIZE(1),
327 Type
: CType_CommandBlock
,
328 Code
: PIMA_OPERATION_CLOSESESSION
,
329 TransactionID
: 0x00000001,
330 Params
: {0x00000001},
333 /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
334 SImage_SendBlockHeader();
336 /* Receive the response block from the device */
337 if ((ErrorCode
= SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError
)
339 ShowCommandError(ErrorCode
, false);
343 /* Verify that the command completed successfully */
344 if ((PIMA_ReceivedBlock
.Type
!= CType_ResponseBlock
) || (PIMA_ReceivedBlock
.Code
!= PIMA_RESPONSE_OK
))
346 ShowCommandError(PIMA_ReceivedBlock
.Code
, true);
350 puts_P(PSTR("Done.\r\n"));
352 /* Indicate device no longer busy */
353 UpdateStatus(Status_USBReady
);
355 /* Wait until USB device disconnected */
356 while (USB_IsConnected
);
362 /** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
363 * strings which contain ASCII printable characters only.
365 * \param UnicodeString Pointer to a Unicode encoded input string
366 * \param Buffer Pointer to a buffer where the converted ASCII string should be stored
368 void UnicodeToASCII(uint8_t* UnicodeString
, char* Buffer
)
370 /* Get the number of characters in the string, skip to the start of the string data */
371 uint8_t CharactersRemaining
= *(UnicodeString
++);
373 /* Loop through the entire unicode string */
374 while (CharactersRemaining
--)
376 /* Load in the next unicode character (only the lower byte, only Unicode coded ASCII supported) */
377 *(Buffer
++) = *UnicodeString
;
379 /* Jump to the next unicode character */
383 /* Null terminate the string */
387 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
388 * log to a serial port, or anything else that is suitable for status updates.
390 * \param CurrentStatus Current status of the system, from the StillImageHost_StatusCodes_t enum
392 void UpdateStatus(uint8_t CurrentStatus
)
394 uint8_t LEDMask
= LEDS_NO_LEDS
;
396 /* Set the LED mask to the appropriate LED mask based on the given status code */
397 switch (CurrentStatus
)
399 case Status_USBNotReady
:
400 LEDMask
= (LEDS_LED1
);
402 case Status_USBEnumerating
:
403 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
405 case Status_USBReady
:
406 LEDMask
= (LEDS_LED2
);
408 case Status_EnumerationError
:
409 case Status_HardwareError
:
410 case Status_PIMACommandError
:
411 LEDMask
= (LEDS_LED1
| LEDS_LED3
);
414 LEDMask
= (LEDS_LED1
| LEDS_LED3
| LEDS_LED4
);
418 /* Set the board LEDs to the new LED mask */
419 LEDs_SetAllLEDs(LEDMask
);
422 /** Displays a PIMA command error via the device's serial port.
424 * \param ErrorCode Error code of the function which failed to complete successfully
425 * \param ResponseErrorCode Indicates if the error is due to a command failed indication from the device, or a communication failure
427 void ShowCommandError(uint8_t ErrorCode
, bool ResponseCodeError
)
429 char* FailureType
= ((ResponseCodeError
) ?
PSTR("Response Code != OK") : PSTR("Transaction Fail"));
431 printf_P(PSTR(ESC_BG_RED
"Command Error (%S).\r\n"), FailureType
);
432 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
434 /* Indicate error via status LEDs */
435 UpdateStatus(Status_PIMACommandError
);
437 /* Wait until USB device disconnected */
438 while (USB_IsConnected
);