Fixed incorrect defined in Version.h.
[pub/USBasp.git] / Demos / Host / StillImageHost / StillImageHost.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
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 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName, "LUFA SIMG Host App");
41 BUTTLOADTAG(BuildTime, __TIME__);
42 BUTTLOADTAG(BuildDate, __DATE__);
43
44 /* Scheduler Task List */
45 TASK_LIST
46 {
47 { Task: USB_USBTask , TaskStatus: TASK_STOP },
48 { Task: USB_SImage_Host , TaskStatus: TASK_STOP },
49 };
50
51
52 /** Main program entry point. This routine configures the hardware required by the application, then
53 * starts the scheduler to run the application tasks.
54 */
55 int main(void)
56 {
57 /* Disable watchdog if enabled by bootloader/fuses */
58 MCUSR &= ~(1 << WDRF);
59 wdt_disable();
60
61 /* Disable Clock Division */
62 CLKPR = (1 << CLKPCE);
63 CLKPR = 0;
64
65 /* Hardware Initialization */
66 SerialStream_Init(9600, false);
67 LEDs_Init();
68
69 /* Indicate USB not ready */
70 UpdateStatus(Status_USBNotReady);
71
72 /* Initialize Scheduler so that it can be used */
73 Scheduler_Init();
74
75 /* Initialize USB Subsystem */
76 USB_Init();
77
78 /* Startup 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));
81
82 /* Scheduling - routine never returns, so put this last in the main function */
83 Scheduler_Start();
84 }
85
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.
88 */
89 EVENT_HANDLER(USB_DeviceAttached)
90 {
91 puts_P(PSTR("Device Attached.\r\n"));
92 UpdateStatus(Status_USBEnumerating);
93
94 /* Start USB management task to enumerate the device */
95 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
96 }
97
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.
100 */
101 EVENT_HANDLER(USB_DeviceUnattached)
102 {
103 /* Stop USB management and Still Image tasks */
104 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
105 Scheduler_SetTaskMode(USB_SImage_Host, TASK_STOP);
106
107 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
108 UpdateStatus(Status_USBNotReady);
109 }
110
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.
113 */
114 EVENT_HANDLER(USB_DeviceEnumerationComplete)
115 {
116 /* Once device is fully enumerated, start the Still Image Host task */
117 Scheduler_SetTaskMode(USB_SImage_Host, TASK_RUN);
118
119 /* Indicate device enumeration complete */
120 UpdateStatus(Status_USBReady);
121 }
122
123 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
124 EVENT_HANDLER(USB_HostError)
125 {
126 USB_ShutDown();
127
128 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
129 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
130
131 UpdateStatus(Status_HardwareError);
132 for(;;);
133 }
134
135 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occured while
136 * enumerating an attached USB device.
137 */
138 EVENT_HANDLER(USB_DeviceEnumerationFailed)
139 {
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);
144
145 UpdateStatus(Status_EnumerationError);
146 }
147
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.
150 */
151 TASK(USB_SImage_Host)
152 {
153 uint8_t ErrorCode;
154
155 switch (USB_HostState)
156 {
157 case HOST_STATE_Addressed:
158 /* Standard request to set the device configuration to configuration 1 */
159 USB_HostRequest = (USB_Host_Request_Header_t)
160 {
161 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
162 bRequest: REQ_SetConfiguration,
163 wValue: 1,
164 wIndex: 0,
165 wLength: 0,
166 };
167
168 /* Send the request, display error and wait for device detatch if request fails */
169 if (USB_Host_SendControlRequest(NULL) != HOST_SENDCONTROL_Successful)
170 {
171 puts_P(PSTR("Control error.\r\n"));
172
173 /* Indicate error via status LEDs */
174 UpdateStatus(Status_EnumerationError);
175
176 /* Wait until USB device disconnected */
177 while (USB_IsConnected);
178 break;
179 }
180
181 USB_HostState = HOST_STATE_Configured;
182 break;
183 case HOST_STATE_Configured:
184 puts_P(PSTR("Getting Config Data.\r\n"));
185
186 /* Get and process the configuration descriptor data */
187 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
188 {
189 if (ErrorCode == ControlError)
190 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
191 else
192 puts_P(PSTR("Invalid Device.\r\n"));
193
194 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
195
196 /* Indicate error via status LEDs */
197 UpdateStatus(Status_EnumerationError);
198
199 /* Wait until USB device disconnected */
200 while (USB_IsConnected);
201 break;
202 }
203
204 puts_P(PSTR("Still Image Device Enumerated.\r\n"));
205
206 USB_HostState = HOST_STATE_Ready;
207 break;
208 case HOST_STATE_Ready:
209 /* Indicate device busy via the status LEDs */
210 UpdateStatus(Status_Busy);
211
212 puts_P(PSTR("Retrieving Device Info...\r\n"));
213
214 PIMA_SendBlock = (PIMA_Container_t)
215 {
216 DataLength: PIMA_COMMAND_SIZE(0),
217 Type: CType_CommandBlock,
218 Code: PIMA_OPERATION_GETDEVICEINFO,
219 TransactionID: 0x00000000,
220 Params: {},
221 };
222
223 /* Send the GETDEVICEINFO block */
224 SImage_SendBlockHeader();
225
226 /* Recieve the response data block */
227 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
228 {
229 ShowCommandError(ErrorCode, false);
230 break;
231 }
232
233 /* Calculate the size of the returned device info data structure */
234 uint16_t DeviceInfoSize = (PIMA_ReceivedBlock.DataLength - PIMA_COMMAND_SIZE(0));
235
236 /* Create a buffer large enough to hold the entire device info */
237 uint8_t DeviceInfo[DeviceInfoSize];
238
239 /* Read in the data block data (containing device info) */
240 SImage_ReadData(DeviceInfo, DeviceInfoSize);
241
242 /* Once all the data has been read, the pipe must be cleared before the response can be sent */
243 Pipe_ClearCurrentBank();
244
245 /* Create a pointer for walking through the info dataset */
246 uint8_t* DeviceInfoPos = DeviceInfo;
247
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
257
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);
262
263 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over Manufacturer String
264
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);
269
270 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over Model String
271
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);
276
277 /* Recieve the final response block from the device */
278 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
279 {
280 ShowCommandError(ErrorCode, false);
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 break;
289 }
290
291 puts_P(PSTR("Opening Session...\r\n"));
292
293 PIMA_SendBlock = (PIMA_Container_t)
294 {
295 DataLength: PIMA_COMMAND_SIZE(1),
296 Type: CType_CommandBlock,
297 Code: PIMA_OPERATION_OPENSESSION,
298 TransactionID: 0x00000000,
299 Params: {0x00000001},
300 };
301
302 /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
303 SImage_SendBlockHeader();
304
305 /* Recieve the response block from the device */
306 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
307 {
308 ShowCommandError(ErrorCode, false);
309 break;
310 }
311
312 /* Verify that the command completed successfully */
313 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
314 {
315 ShowCommandError(PIMA_ReceivedBlock.Code, true);
316 break;
317 }
318
319 puts_P(PSTR("Closing Session...\r\n"));
320
321 PIMA_SendBlock = (PIMA_Container_t)
322 {
323 DataLength: PIMA_COMMAND_SIZE(1),
324 Type: CType_CommandBlock,
325 Code: PIMA_OPERATION_CLOSESESSION,
326 TransactionID: 0x00000001,
327 Params: {0x00000001},
328 };
329
330 /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
331 SImage_SendBlockHeader();
332
333 /* Recieve the response block from the device */
334 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_ERROR_NoError)
335 {
336 ShowCommandError(ErrorCode, false);
337 break;
338 }
339
340 /* Verify that the command completed successfully */
341 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
342 {
343 ShowCommandError(PIMA_ReceivedBlock.Code, true);
344 break;
345 }
346
347 puts_P(PSTR("Done.\r\n"));
348
349 /* Indicate device no longer busy */
350 UpdateStatus(Status_USBReady);
351
352 /* Wait until USB device disconnected */
353 while (USB_IsConnected);
354
355 break;
356 }
357 }
358
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.
361 *
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
364 */
365 void UnicodeToASCII(uint8_t* UnicodeString, char* Buffer)
366 {
367 /* Get the number of characters in the string, skip to the start of the string data */
368 uint8_t CharactersRemaining = *(UnicodeString++);
369
370 /* Loop through the entire unicode string */
371 while (CharactersRemaining--)
372 {
373 /* Load in the next unicode character (only the lower byte, only Unicode coded ASCII supported) */
374 *(Buffer++) = *UnicodeString;
375
376 /* Jump to the next unicode character */
377 UnicodeString += 2;
378 }
379
380 /* Null terminate the string */
381 *Buffer = 0;
382 }
383
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.
386 *
387 * \param CurrentStatus Current status of the system, from the StillImageHost_StatusCodes_t enum
388 */
389 void UpdateStatus(uint8_t CurrentStatus)
390 {
391 uint8_t LEDMask = LEDS_NO_LEDS;
392
393 /* Set the LED mask to the appropriate LED mask based on the given status code */
394 switch (CurrentStatus)
395 {
396 case Status_USBNotReady:
397 LEDMask = (LEDS_LED1);
398 break;
399 case Status_USBEnumerating:
400 LEDMask = (LEDS_LED1 | LEDS_LED2);
401 break;
402 case Status_USBReady:
403 LEDMask = (LEDS_LED2);
404 break;
405 case Status_EnumerationError:
406 case Status_HardwareError:
407 case Status_PIMACommandError:
408 LEDMask = (LEDS_LED1 | LEDS_LED3);
409 break;
410 case Status_Busy:
411 LEDMask = (LEDS_LED1 | LEDS_LED3 | LEDS_LED4);
412 break;
413 }
414
415 /* Set the board LEDs to the new LED mask */
416 LEDs_SetAllLEDs(LEDMask);
417 }
418
419 /** Displays a PIMA command error via the device's serial port.
420 *
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
423 */
424 void ShowCommandError(uint8_t ErrorCode, bool ResponseCodeError)
425 {
426 char* FailureType = ((ResponseCodeError) ? PSTR("Response Code != OK") : PSTR("Transaction Fail"));
427
428 printf_P(PSTR(ESC_BG_RED "Command Error (%S).\r\n"), FailureType);
429 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
430
431 /* Indicate error via status LEDs */
432 UpdateStatus(Status_PIMACommandError);
433
434 /* Wait until USB device disconnected */
435 while (USB_IsConnected);
436 }