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