Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StillImageHost.c 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2014.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * Main source file for the StillImageHost demo. This file contains the main tasks of
  29. * the demo and is responsible for the initial application hardware configuration.
  30. */
  31. #include "StillImageHost.h"
  32. /** Main program entry point. This routine configures the hardware required by the application, then
  33. * enters a loop to run the application tasks in sequence.
  34. */
  35. int main(void)
  36. {
  37. SetupHardware();
  38. puts_P(PSTR(ESC_FG_CYAN "Still Image Host Demo running.\r\n" ESC_FG_WHITE));
  39. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  40. GlobalInterruptEnable();
  41. for (;;)
  42. {
  43. StillImageHost_Task();
  44. USB_USBTask();
  45. }
  46. }
  47. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  48. void SetupHardware(void)
  49. {
  50. #if (ARCH == ARCH_AVR8)
  51. /* Disable watchdog if enabled by bootloader/fuses */
  52. MCUSR &= ~(1 << WDRF);
  53. wdt_disable();
  54. /* Disable clock division */
  55. clock_prescale_set(clock_div_1);
  56. #endif
  57. /* Hardware Initialization */
  58. Serial_Init(9600, false);
  59. LEDs_Init();
  60. USB_Init();
  61. /* Create a stdio stream for the serial port for stdin and stdout */
  62. Serial_CreateStream(NULL);
  63. }
  64. /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
  65. * starts the library USB task to begin the enumeration and USB management process.
  66. */
  67. void EVENT_USB_Host_DeviceAttached(void)
  68. {
  69. puts_P(PSTR(ESC_FG_GREEN "Device Attached.\r\n" ESC_FG_WHITE));
  70. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  71. }
  72. /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
  73. * stops the library USB task management process.
  74. */
  75. void EVENT_USB_Host_DeviceUnattached(void)
  76. {
  77. puts_P(PSTR(ESC_FG_GREEN "\r\nDevice Unattached.\r\n" ESC_FG_WHITE));
  78. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  79. }
  80. /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
  81. * enumerated by the host and is now ready to be used by the application.
  82. */
  83. void EVENT_USB_Host_DeviceEnumerationComplete(void)
  84. {
  85. puts_P(PSTR("Getting Config Data.\r\n"));
  86. uint8_t ErrorCode;
  87. /* Get and process the configuration descriptor data */
  88. if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
  89. {
  90. if (ErrorCode == ControlError)
  91. puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
  92. else
  93. puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
  94. printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
  95. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  96. return;
  97. }
  98. /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
  99. if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
  100. {
  101. printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
  102. " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
  103. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  104. return;
  105. }
  106. puts_P(PSTR("Still Image Device Enumerated.\r\n"));
  107. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  108. }
  109. /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
  110. void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
  111. {
  112. USB_Disable();
  113. printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
  114. " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
  115. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  116. for(;;);
  117. }
  118. /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
  119. * enumerating an attached USB device.
  120. */
  121. void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
  122. const uint8_t SubErrorCode)
  123. {
  124. printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
  125. " -- Error Code %d\r\n"
  126. " -- Sub Error Code %d\r\n"
  127. " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
  128. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  129. }
  130. /** Task to print device information through the serial port, and open/close a test PIMA session with the
  131. * attached Still Image device.
  132. */
  133. void StillImageHost_Task(void)
  134. {
  135. if (USB_HostState != HOST_STATE_Configured)
  136. return;
  137. uint8_t ErrorCode;
  138. /* Indicate device busy via the status LEDs */
  139. LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
  140. puts_P(PSTR("Retrieving Device Info...\r\n"));
  141. PIMA_SendBlock = (PIMA_Container_t)
  142. {
  143. .DataLength = PIMA_COMMAND_SIZE(0),
  144. .Type = PIMA_CONTAINER_CommandBlock,
  145. .Code = PIMA_OPERATION_GETDEVICEINFO,
  146. .TransactionID = 0x00000000,
  147. .Params = {},
  148. };
  149. /* Send the GETDEVICEINFO block */
  150. SImage_SendBlockHeader();
  151. /* Receive the response data block */
  152. if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
  153. {
  154. ShowCommandError(ErrorCode, false);
  155. USB_Host_SetDeviceConfiguration(0);
  156. return;
  157. }
  158. /* Calculate the size of the returned device info data structure */
  159. uint16_t DeviceInfoSize = (PIMA_ReceivedBlock.DataLength - PIMA_COMMAND_SIZE(0));
  160. /* Create a buffer large enough to hold the entire device info */
  161. uint8_t DeviceInfo[DeviceInfoSize];
  162. /* Read in the data block data (containing device info) */
  163. SImage_ReadData(DeviceInfo, DeviceInfoSize);
  164. /* Once all the data has been read, the pipe must be cleared before the response can be sent */
  165. Pipe_ClearIN();
  166. /* Create a pointer for walking through the info dataset */
  167. uint8_t* DeviceInfoPos = DeviceInfo;
  168. /* Skip over the data before the unicode device information strings */
  169. DeviceInfoPos += 8; // Skip to VendorExtensionDesc String
  170. DeviceInfoPos += (1 + UNICODE_STRING_LENGTH(*DeviceInfoPos)); // Skip over VendorExtensionDesc String
  171. DeviceInfoPos += 2; // Skip over FunctionalMode
  172. DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Supported Operations Array
  173. DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Supported Events Array
  174. DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Supported Device Properties Array
  175. DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Capture Formats Array
  176. DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1)); // Skip over Image Formats Array
  177. /* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
  178. char Manufacturer[*DeviceInfoPos];
  179. UnicodeToASCII(DeviceInfoPos, Manufacturer);
  180. printf_P(PSTR(" Manufacturer: %s\r\n"), Manufacturer);
  181. DeviceInfoPos += 1 + UNICODE_STRING_LENGTH(*DeviceInfoPos); // Skip over Manufacturer String
  182. /* Extract and convert the Model Unicode string to ASCII and print it through the USART */
  183. char Model[*DeviceInfoPos];
  184. UnicodeToASCII(DeviceInfoPos, Model);
  185. printf_P(PSTR(" Model: %s\r\n"), Model);
  186. DeviceInfoPos += 1 + UNICODE_STRING_LENGTH(*DeviceInfoPos); // Skip over Model String
  187. /* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
  188. char DeviceVersion[*DeviceInfoPos];
  189. UnicodeToASCII(DeviceInfoPos, DeviceVersion);
  190. printf_P(PSTR(" Device Version: %s\r\n"), DeviceVersion);
  191. /* Receive the final response block from the device */
  192. if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
  193. {
  194. ShowCommandError(ErrorCode, false);
  195. USB_Host_SetDeviceConfiguration(0);
  196. return;
  197. }
  198. /* Verify that the command completed successfully */
  199. if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
  200. {
  201. ShowCommandError(PIMA_ReceivedBlock.Code, true);
  202. USB_Host_SetDeviceConfiguration(0);
  203. return;
  204. }
  205. puts_P(PSTR("Opening Session...\r\n"));
  206. PIMA_SendBlock = (PIMA_Container_t)
  207. {
  208. .DataLength = PIMA_COMMAND_SIZE(1),
  209. .Type = PIMA_CONTAINER_CommandBlock,
  210. .Code = PIMA_OPERATION_OPENSESSION,
  211. .TransactionID = 0x00000000,
  212. .Params = {0x00000001},
  213. };
  214. /* Send the OPENSESSION block, open a session with an ID of 0x0001 */
  215. SImage_SendBlockHeader();
  216. /* Receive the response block from the device */
  217. if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
  218. {
  219. ShowCommandError(ErrorCode, false);
  220. USB_Host_SetDeviceConfiguration(0);
  221. return;
  222. }
  223. /* Verify that the command completed successfully */
  224. if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
  225. {
  226. ShowCommandError(PIMA_ReceivedBlock.Code, true);
  227. USB_Host_SetDeviceConfiguration(0);
  228. return;
  229. }
  230. puts_P(PSTR("Closing Session...\r\n"));
  231. PIMA_SendBlock = (PIMA_Container_t)
  232. {
  233. .DataLength = PIMA_COMMAND_SIZE(1),
  234. .Type = PIMA_CONTAINER_CommandBlock,
  235. .Code = PIMA_OPERATION_CLOSESESSION,
  236. .TransactionID = 0x00000001,
  237. .Params = {0x00000001},
  238. };
  239. /* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
  240. SImage_SendBlockHeader();
  241. /* Receive the response block from the device */
  242. if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
  243. {
  244. ShowCommandError(ErrorCode, false);
  245. USB_Host_SetDeviceConfiguration(0);
  246. return;
  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. puts_P(PSTR("Done.\r\n"));
  256. /* Indicate device no longer busy */
  257. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  258. USB_Host_SetDeviceConfiguration(0);
  259. }
  260. /** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
  261. * strings which contain ASCII printable characters only.
  262. *
  263. * \param[in] UnicodeString Pointer to a Unicode encoded input string
  264. * \param[out] Buffer Pointer to a buffer where the converted ASCII string should be stored
  265. */
  266. void UnicodeToASCII(uint8_t* UnicodeString,
  267. char* Buffer)
  268. {
  269. /* Get the number of characters in the string, skip to the start of the string data */
  270. uint8_t CharactersRemaining = *(UnicodeString++);
  271. /* Loop through the entire unicode string */
  272. while (CharactersRemaining--)
  273. {
  274. /* Load in the next unicode character (only the lower byte, as only Unicode coded ASCII is supported) */
  275. *(Buffer++) = *UnicodeString;
  276. /* Jump to the next unicode character */
  277. UnicodeString += 2;
  278. }
  279. /* Null terminate the string */
  280. *Buffer = 0;
  281. }
  282. /** Displays a PIMA command error via the device's serial port.
  283. *
  284. * \param[in] ErrorCode Error code of the function which failed to complete successfully
  285. * \param[in] ResponseCodeError Indicates if the error is due to a command failed indication from the device, or a communication failure
  286. */
  287. void ShowCommandError(uint8_t ErrorCode,
  288. bool ResponseCodeError)
  289. {
  290. const char* FailureType = ((ResponseCodeError) ? PSTR("Response Code != OK") : PSTR("Transaction Fail"));
  291. printf_P(PSTR(ESC_FG_RED "Command Error (%S).\r\n"
  292. " -- Error Code %d\r\n" ESC_FG_WHITE), FailureType, ErrorCode);
  293. /* Indicate error via status LEDs */
  294. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  295. }