Converted Host mode demos to schedulerless. Fixed host mode broken due to earlier...
[pub/USBasp.git] / Demos / Host / LowLevel / 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 /** Main program entry point. This routine configures the hardware required by the application, then
40 * starts the scheduler to run the application tasks.
41 */
42 int main(void)
43 {
44 SetupHardware();
45
46 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
47 "Still Image Host Demo running.\r\n" ESC_INVERSE_OFF));
48
49 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
50
51 for (;;)
52 {
53 StillImage_Task();
54 USB_USBTask();
55 }
56 }
57
58 /** Configures the board hardware and chip peripherals for the demo's functionality. */
59 void SetupHardware(void)
60 {
61 /* Disable watchdog if enabled by bootloader/fuses */
62 MCUSR &= ~(1 << WDRF);
63 wdt_disable();
64
65 /* Disable Clock Division */
66 CLKPR = (1 << CLKPCE);
67 CLKPR = 0;
68
69 /* Hardware Initialization */
70 SerialStream_Init(9600, false);
71 LEDs_Init();
72 USB_Init();
73 }
74
75 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
76 * starts the library USB task to begin the enumeration and USB management process.
77 */
78 void EVENT_USB_DeviceAttached(void)
79 {
80 puts_P(PSTR("Device Attached.\r\n"));
81 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
82 }
83
84 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
85 * stops the library USB task management process.
86 */
87 void EVENT_USB_DeviceUnattached(void)
88 {
89 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
90 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
91 }
92
93 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
94 * enumerated by the host and is now ready to be used by the application.
95 */
96 void EVENT_USB_DeviceEnumerationComplete(void)
97 {
98 LEDs_SetAllLEDs(LEDMASK_USB_READY);
99 }
100
101 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
102 void EVENT_USB_HostError(const uint8_t ErrorCode)
103 {
104 USB_ShutDown();
105
106 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
107 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
108
109 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
110 for(;;);
111 }
112
113 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
114 * enumerating an attached USB device.
115 */
116 void EVENT_USB_DeviceEnumerationFailed(const uint8_t ErrorCode, const uint8_t SubErrorCode)
117 {
118 puts_P(PSTR(ESC_BG_RED "Dev Enum Error\r\n"));
119 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
120 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode);
121 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState);
122
123 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
124 }
125
126 /** Task to set the configuration of the attached device after it has been enumerated, and to print device information
127 * through the serial port.
128 */
129 void StillImage_Task(void)
130 {
131 uint8_t ErrorCode;
132
133 switch (USB_HostState)
134 {
135 case HOST_STATE_Addressed:
136 /* Standard request to set the device configuration to configuration 1 */
137 USB_ControlRequest = (USB_Request_Header_t)
138 {
139 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
140 .bRequest = REQ_SetConfiguration,
141 .wValue = 1,
142 .wIndex = 0,
143 .wLength = 0,
144 };
145
146 /* Select the control pipe for the request transfer */
147 Pipe_SelectPipe(PIPE_CONTROLPIPE);
148
149 /* Send the request, display error and wait for device detach if request fails */
150 if (USB_Host_SendControlRequest(NULL) != HOST_SENDCONTROL_Successful)
151 {
152 puts_P(PSTR("Control error.\r\n"));
153
154 /* Indicate error via status LEDs */
155 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
156
157 /* Wait until USB device disconnected */
158 while (USB_IsConnected);
159 break;
160 }
161
162 USB_HostState = HOST_STATE_Configured;
163 break;
164 case HOST_STATE_Configured:
165 puts_P(PSTR("Getting Config Data.\r\n"));
166
167 /* Get and process the configuration descriptor data */
168 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
169 {
170 if (ErrorCode == ControlError)
171 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
172 else
173 puts_P(PSTR("Invalid Device.\r\n"));
174
175 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
176
177 /* Indicate error via status LEDs */
178 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
179
180 /* Wait until USB device disconnected */
181 while (USB_IsConnected);
182 break;
183 }
184
185 puts_P(PSTR("Still Image Device Enumerated.\r\n"));
186
187 USB_HostState = HOST_STATE_Ready;
188 break;
189 case HOST_STATE_Ready:
190 /* Indicate device busy via the status LEDs */
191 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
192
193 puts_P(PSTR("Retrieving Device Info...\r\n"));
194
195 PIMA_SendBlock = (PIMA_Container_t)
196 {
197 .DataLength = PIMA_COMMAND_SIZE(0),
198 .Type = CType_CommandBlock,
199 .Code = PIMA_OPERATION_GETDEVICEINFO,
200 .TransactionID = 0x00000000,
201 .Params = {},
202 };
203
204 /* Send the GETDEVICEINFO block */
205 SImage_SendBlockHeader();
206
207 /* Receive the response data block */
208 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_NoError)
209 {
210 ShowCommandError(ErrorCode, false);
211 break;
212 }
213
214 /* Calculate the size of the returned device info data structure */
215 uint16_t DeviceInfoSize = (PIMA_ReceivedBlock.DataLength - PIMA_COMMAND_SIZE(0));
216
217 /* Create a buffer large enough to hold the entire device info */
218 uint8_t DeviceInfo[DeviceInfoSize];
219
220 /* Read in the data block data (containing device info) */
221 SImage_ReadData(DeviceInfo, DeviceInfoSize);
222
223 /* Once all the data has been read, the pipe must be cleared before the response can be sent */
224 Pipe_ClearIN();
225
226 /* Create a pointer for walking through the info dataset */
227 uint8_t* DeviceInfoPos = DeviceInfo;
228
229 /* Skip over the data before the unicode device information strings */
230 DeviceInfoPos += 8; // Skip to VendorExtensionDesc String
231 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over VendorExtensionDesc String
232 DeviceInfoPos += 2; // Skip over FunctionalMode
233 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over OperationCode Array
234 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over EventCode Array
235 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over DevicePropCode Array
236 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over ObjectFormatCode Array
237 DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over ObjectFormatCode Array
238
239 /* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
240 char Manufacturer[*DeviceInfoPos];
241 UnicodeToASCII(DeviceInfoPos, Manufacturer);
242 printf_P(PSTR(" Manufacturer: %s\r\n"), Manufacturer);
243
244 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over Manufacturer String
245
246 /* Extract and convert the Model Unicode string to ASCII and print it through the USART */
247 char Model[*DeviceInfoPos];
248 UnicodeToASCII(DeviceInfoPos, Model);
249 printf_P(PSTR(" Model: %s\r\n"), Model);
250
251 DeviceInfoPos += ((*DeviceInfoPos << 1) + 1); // Skip over Model String
252
253 /* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
254 char DeviceVersion[*DeviceInfoPos];
255 UnicodeToASCII(DeviceInfoPos, DeviceVersion);
256 printf_P(PSTR(" Device Version: %s\r\n"), DeviceVersion);
257
258 /* Receive the final response block from the device */
259 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_NoError)
260 {
261 ShowCommandError(ErrorCode, false);
262 break;
263 }
264
265 /* Verify that the command completed successfully */
266 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
267 {
268 ShowCommandError(PIMA_ReceivedBlock.Code, true);
269 break;
270 }
271
272 puts_P(PSTR("Opening Session...\r\n"));
273
274 PIMA_SendBlock = (PIMA_Container_t)
275 {
276 .DataLength = PIMA_COMMAND_SIZE(1),
277 .Type = CType_CommandBlock,
278 .Code = PIMA_OPERATION_OPENSESSION,
279 .TransactionID = 0x00000000,
280 .Params = {0x00000001},
281 };
282
283 /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
284 SImage_SendBlockHeader();
285
286 /* Receive the response block from the device */
287 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_NoError)
288 {
289 ShowCommandError(ErrorCode, false);
290 break;
291 }
292
293 /* Verify that the command completed successfully */
294 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
295 {
296 ShowCommandError(PIMA_ReceivedBlock.Code, true);
297 break;
298 }
299
300 puts_P(PSTR("Closing Session...\r\n"));
301
302 PIMA_SendBlock = (PIMA_Container_t)
303 {
304 .DataLength = PIMA_COMMAND_SIZE(1),
305 .Type = CType_CommandBlock,
306 .Code = PIMA_OPERATION_CLOSESESSION,
307 .TransactionID = 0x00000001,
308 .Params = {0x00000001},
309 };
310
311 /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
312 SImage_SendBlockHeader();
313
314 /* Receive the response block from the device */
315 if ((ErrorCode = SImage_RecieveBlockHeader()) != PIPE_RWSTREAM_NoError)
316 {
317 ShowCommandError(ErrorCode, false);
318 break;
319 }
320
321 /* Verify that the command completed successfully */
322 if ((PIMA_ReceivedBlock.Type != CType_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
323 {
324 ShowCommandError(PIMA_ReceivedBlock.Code, true);
325 break;
326 }
327
328 puts_P(PSTR("Done.\r\n"));
329
330 /* Indicate device no longer busy */
331 LEDs_SetAllLEDs(LEDMASK_USB_READY);
332
333 /* Wait until USB device disconnected */
334 while (USB_IsConnected);
335
336 break;
337 }
338 }
339
340 /** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
341 * strings which contain ASCII printable characters only.
342 *
343 * \param UnicodeString Pointer to a Unicode encoded input string
344 * \param Buffer Pointer to a buffer where the converted ASCII string should be stored
345 */
346 void UnicodeToASCII(uint8_t* UnicodeString, char* Buffer)
347 {
348 /* Get the number of characters in the string, skip to the start of the string data */
349 uint8_t CharactersRemaining = *(UnicodeString++);
350
351 /* Loop through the entire unicode string */
352 while (CharactersRemaining--)
353 {
354 /* Load in the next unicode character (only the lower byte, only Unicode coded ASCII supported) */
355 *(Buffer++) = *UnicodeString;
356
357 /* Jump to the next unicode character */
358 UnicodeString += 2;
359 }
360
361 /* Null terminate the string */
362 *Buffer = 0;
363 }
364
365 /** Displays a PIMA command error via the device's serial port.
366 *
367 * \param ErrorCode Error code of the function which failed to complete successfully
368 * \param ResponseCodeError Indicates if the error is due to a command failed indication from the device, or a communication failure
369 */
370 void ShowCommandError(uint8_t ErrorCode, bool ResponseCodeError)
371 {
372 char* FailureType = ((ResponseCodeError) ? PSTR("Response Code != OK") : PSTR("Transaction Fail"));
373
374 printf_P(PSTR(ESC_BG_RED "Command Error (%S).\r\n"), FailureType);
375 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
376
377 /* Indicate error via status LEDs */
378 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
379
380 /* Wait until USB device disconnected */
381 while (USB_IsConnected);
382 }