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