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