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.

MassStorageHost.c 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 MassStorageHost demo. This file contains the main tasks of
  29. * the demo and is responsible for the initial application hardware configuration.
  30. */
  31. #include "MassStorageHost.h"
  32. /** Index of the highest available LUN (Logical Unit) in the attached Mass Storage Device */
  33. uint8_t MassStore_MaxLUNIndex;
  34. /** Main program entry point. This routine configures the hardware required by the application, then
  35. * enters a loop to run the application tasks in sequence.
  36. */
  37. int main(void)
  38. {
  39. SetupHardware();
  40. puts_P(PSTR(ESC_FG_CYAN "Mass Storage Host Demo running.\r\n" ESC_FG_WHITE));
  41. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  42. GlobalInterruptEnable();
  43. for (;;)
  44. {
  45. MassStorageHost_Task();
  46. USB_USBTask();
  47. }
  48. }
  49. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  50. void SetupHardware(void)
  51. {
  52. #if (ARCH == ARCH_AVR8)
  53. /* Disable watchdog if enabled by bootloader/fuses */
  54. MCUSR &= ~(1 << WDRF);
  55. wdt_disable();
  56. /* Disable clock division */
  57. clock_prescale_set(clock_div_1);
  58. #endif
  59. /* Hardware Initialization */
  60. Serial_Init(9600, false);
  61. LEDs_Init();
  62. Buttons_Init();
  63. USB_Init();
  64. /* Create a stdio stream for the serial port for stdin and stdout */
  65. Serial_CreateStream(NULL);
  66. }
  67. /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
  68. * starts the library USB task to begin the enumeration and USB management process.
  69. */
  70. void EVENT_USB_Host_DeviceAttached(void)
  71. {
  72. puts_P(PSTR(ESC_FG_GREEN "Device Attached.\r\n" ESC_FG_WHITE));
  73. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  74. }
  75. /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
  76. * stops the library USB task management process.
  77. */
  78. void EVENT_USB_Host_DeviceUnattached(void)
  79. {
  80. puts_P(PSTR(ESC_FG_GREEN "\r\nDevice Unattached.\r\n" ESC_FG_WHITE));
  81. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  82. }
  83. /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
  84. * enumerated by the host and is now ready to be used by the application.
  85. */
  86. void EVENT_USB_Host_DeviceEnumerationComplete(void)
  87. {
  88. puts_P(PSTR("Getting Config Data.\r\n"));
  89. uint8_t ErrorCode;
  90. /* Get and process the configuration descriptor data */
  91. if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
  92. {
  93. if (ErrorCode == ControlError)
  94. puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
  95. else
  96. puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
  97. printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
  98. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  99. return;
  100. }
  101. /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
  102. if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
  103. {
  104. printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
  105. " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
  106. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  107. return;
  108. }
  109. puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
  110. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  111. }
  112. /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
  113. void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
  114. {
  115. USB_Disable();
  116. printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
  117. " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
  118. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  119. for(;;);
  120. }
  121. /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
  122. * enumerating an attached USB device.
  123. */
  124. void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
  125. const uint8_t SubErrorCode)
  126. {
  127. printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
  128. " -- Error Code %d\r\n"
  129. " -- Sub Error Code %d\r\n"
  130. " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
  131. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  132. }
  133. /** Task to set the configuration of the attached device after it has been enumerated, and to read in blocks from
  134. * the device and print them to the serial port.
  135. */
  136. void MassStorageHost_Task(void)
  137. {
  138. if (USB_HostState != HOST_STATE_Configured)
  139. return;
  140. /* Indicate device busy via the status LEDs */
  141. LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
  142. uint8_t ErrorCode;
  143. /* Send the request, display error and wait for device detach if request fails */
  144. if ((ErrorCode = MassStore_GetMaxLUN(&MassStore_MaxLUNIndex)) != HOST_SENDCONTROL_Successful)
  145. {
  146. ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode);
  147. USB_Host_SetDeviceConfiguration(0);
  148. return;
  149. }
  150. /* Print number of LUNs detected in the attached device */
  151. printf_P(PSTR("Total LUNs: %d - Using first LUN in device.\r\n"), (MassStore_MaxLUNIndex + 1));
  152. /* Reset the Mass Storage device interface, ready for use */
  153. if ((ErrorCode = MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful)
  154. {
  155. ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode);
  156. USB_Host_SetDeviceConfiguration(0);
  157. return;
  158. }
  159. /* Get sense data from the device - many devices will not accept any other commands until the sense data
  160. * is read - both on start-up and after a failed command */
  161. SCSI_Request_Sense_Response_t SenseData;
  162. if ((ErrorCode = MassStore_RequestSense(0, &SenseData)) != 0)
  163. {
  164. ShowDiskReadError(PSTR("Request Sense"), ErrorCode);
  165. USB_Host_SetDeviceConfiguration(0);
  166. return;
  167. }
  168. /* Set the prevent removal flag for the device, allowing it to be accessed */
  169. if ((ErrorCode = MassStore_PreventAllowMediumRemoval(0, true)) != 0)
  170. {
  171. ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode);
  172. USB_Host_SetDeviceConfiguration(0);
  173. return;
  174. }
  175. /* Get inquiry data from the device */
  176. SCSI_Inquiry_Response_t InquiryData;
  177. if ((ErrorCode = MassStore_Inquiry(0, &InquiryData)) != 0)
  178. {
  179. ShowDiskReadError(PSTR("Inquiry"), ErrorCode);
  180. USB_Host_SetDeviceConfiguration(0);
  181. return;
  182. }
  183. /* Print vendor and product names of attached device */
  184. printf_P(PSTR("Vendor \"%.8s\", Product \"%.16s\"\r\n"), InquiryData.VendorID, InquiryData.ProductID);
  185. /* Wait until disk ready */
  186. puts_P(PSTR("Waiting until ready.."));
  187. for (;;)
  188. {
  189. Serial_SendByte('.');
  190. /* Abort if device removed */
  191. if (USB_HostState == HOST_STATE_Unattached)
  192. break;
  193. /* Check to see if the attached device is ready for new commands */
  194. ErrorCode = MassStore_TestUnitReady(0);
  195. /* If attached device is ready, abort the loop */
  196. if (!(ErrorCode))
  197. break;
  198. /* If an error other than a logical command failure (indicating device busy) returned, abort */
  199. if (ErrorCode != MASS_STORE_SCSI_COMMAND_FAILED)
  200. {
  201. ShowDiskReadError(PSTR("Test Unit Ready"), ErrorCode);
  202. USB_Host_SetDeviceConfiguration(0);
  203. return;
  204. }
  205. }
  206. puts_P(PSTR("\r\nRetrieving Capacity... "));
  207. /* Create new structure for the disk's capacity in blocks and block size */
  208. SCSI_Capacity_t DiskCapacity;
  209. /* Retrieve disk capacity */
  210. if ((ErrorCode = MassStore_ReadCapacity(0, &DiskCapacity)) != 0)
  211. {
  212. ShowDiskReadError(PSTR("Read Capacity"), ErrorCode);
  213. USB_Host_SetDeviceConfiguration(0);
  214. return;
  215. }
  216. /* Display the disk capacity in blocks * block size bytes */
  217. printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity.Blocks, DiskCapacity.BlockSize);
  218. /* Create a new buffer capable of holding a single block from the device */
  219. uint8_t BlockBuffer[DiskCapacity.BlockSize];
  220. /* Read in the first 512 byte block from the device */
  221. if ((ErrorCode = MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
  222. {
  223. ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
  224. USB_Host_SetDeviceConfiguration(0);
  225. return;
  226. }
  227. puts_P(PSTR("\r\nContents of first block:\r\n"));
  228. /* Print out the first block in both HEX and ASCII, 16 bytes per line */
  229. for (uint16_t Chunk = 0; Chunk < (DiskCapacity.BlockSize >> 4); Chunk++)
  230. {
  231. /* Pointer to the start of the current 16-byte chunk in the read block of data */
  232. uint8_t* ChunkPtr = &BlockBuffer[Chunk << 4];
  233. /* Print out the 16 bytes of the chunk in HEX format */
  234. for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
  235. {
  236. char CurrByte = *(ChunkPtr + ByteOffset);
  237. printf_P(PSTR("%.2X "), CurrByte);
  238. }
  239. puts_P(PSTR(" "));
  240. /* Print out the 16 bytes of the chunk in ASCII format */
  241. for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
  242. {
  243. char CurrByte = *(ChunkPtr + ByteOffset);
  244. putchar(isprint(CurrByte) ? CurrByte : '.');
  245. }
  246. puts_P(PSTR("\r\n"));
  247. }
  248. puts_P(PSTR("\r\n\r\nPress board button to read entire ASCII contents of disk...\r\n\r\n"));
  249. /* Wait for the board button to be pressed */
  250. while (!(Buttons_GetStatus() & BUTTONS_BUTTON1))
  251. {
  252. /* Abort if device removed */
  253. if (USB_HostState == HOST_STATE_Unattached)
  254. return;
  255. }
  256. /* Print out the entire disk contents in ASCII format */
  257. for (uint32_t CurrBlockAddress = 0; CurrBlockAddress < DiskCapacity.Blocks; CurrBlockAddress++)
  258. {
  259. /* Read in the next block of data from the device */
  260. if ((ErrorCode = MassStore_ReadDeviceBlock(0, CurrBlockAddress, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
  261. {
  262. ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
  263. USB_Host_SetDeviceConfiguration(0);
  264. return;
  265. }
  266. /* Send the ASCII data in the read in block to the serial port */
  267. for (uint16_t Byte = 0; Byte < DiskCapacity.BlockSize; Byte++)
  268. {
  269. char CurrByte = BlockBuffer[Byte];
  270. putchar(isprint(CurrByte) ? CurrByte : '.');
  271. }
  272. }
  273. /* Indicate device no longer busy */
  274. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  275. USB_Host_SetDeviceConfiguration(0);
  276. }
  277. /** Indicates that a communication error has occurred with the attached Mass Storage Device,
  278. * printing error codes to the serial port and waiting until the device is removed before
  279. * continuing.
  280. *
  281. * \param[in] CommandString ASCII string located in PROGMEM space indicating what operation failed
  282. * \param[in] ErrorCode Error code of the function which failed to complete successfully
  283. */
  284. void ShowDiskReadError(const char* CommandString,
  285. const uint8_t ErrorCode)
  286. {
  287. if (ErrorCode == MASS_STORE_SCSI_COMMAND_FAILED)
  288. {
  289. /* Display the error code */
  290. printf_P(PSTR(ESC_FG_RED "SCSI command error (%S).\r\n"), CommandString);
  291. }
  292. else
  293. {
  294. /* Display the error code */
  295. printf_P(PSTR(ESC_FG_RED "Command error (%S).\r\n"), CommandString);
  296. printf_P(PSTR(" -- Error Code: %d" ESC_FG_WHITE), ErrorCode);
  297. }
  298. Pipe_Freeze();
  299. /* Indicate device error via the status LEDs */
  300. LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
  301. }