3      Copyright (C) Dean Camera, 2013. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2013  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  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. 
  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 
  33  *  Main source file for the MassStorageHost demo. This file contains the main tasks of 
  34  *  the demo and is responsible for the initial application hardware configuration. 
  37 #include "MassStorageHost.h" 
  39 /** Index of the highest available LUN (Logical Unit) in the attached Mass Storage Device */ 
  40 uint8_t MassStore_MaxLUNIndex
; 
  43 /** Main program entry point. This routine configures the hardware required by the application, then 
  44  *  enters a loop to run the application tasks in sequence. 
  50         puts_P(PSTR(ESC_FG_CYAN 
"Mass Storage Host Demo running.\r\n" ESC_FG_WHITE
)); 
  52         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
  53         GlobalInterruptEnable(); 
  57                 MassStorageHost_Task(); 
  63 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
  64 void SetupHardware(void) 
  66         /* Disable watchdog if enabled by bootloader/fuses */ 
  67         MCUSR 
&= ~(1 << WDRF
); 
  70         /* Disable clock division */ 
  71         clock_prescale_set(clock_div_1
); 
  73         /* Hardware Initialization */ 
  74         Serial_Init(9600, false); 
  79         /* Create a stdio stream for the serial port for stdin and stdout */ 
  80         Serial_CreateStream(NULL
); 
  83 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and 
  84  *  starts the library USB task to begin the enumeration and USB management process. 
  86 void EVENT_USB_Host_DeviceAttached(void) 
  88         puts_P(PSTR(ESC_FG_GREEN 
"Device Attached.\r\n" ESC_FG_WHITE
)); 
  89         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
  92 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and 
  93  *  stops the library USB task management process. 
  95 void EVENT_USB_Host_DeviceUnattached(void) 
  97         puts_P(PSTR(ESC_FG_GREEN 
"\r\nDevice Unattached.\r\n" ESC_FG_WHITE
)); 
  98         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 101 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully 
 102  *  enumerated by the host and is now ready to be used by the application. 
 104 void EVENT_USB_Host_DeviceEnumerationComplete(void) 
 106         puts_P(PSTR("Getting Config Data.\r\n")); 
 110         /* Get and process the configuration descriptor data */ 
 111         if ((ErrorCode 
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
) 
 113                 if (ErrorCode 
== ControlError
) 
 114                   puts_P(PSTR(ESC_FG_RED 
"Control Error (Get Configuration).\r\n")); 
 116                   puts_P(PSTR(ESC_FG_RED 
"Invalid Device.\r\n")); 
 118                 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE
), ErrorCode
); 
 120                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 124         /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */ 
 125         if ((ErrorCode 
= USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful
) 
 127                 printf_P(PSTR(ESC_FG_RED 
"Control Error (Set Configuration).\r\n" 
 128                                          " -- Error Code: %d\r\n" ESC_FG_WHITE
), ErrorCode
); 
 130                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 134         puts_P(PSTR("Mass Storage Disk Enumerated.\r\n")); 
 135         LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 138 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */ 
 139 void EVENT_USB_Host_HostError(const uint8_t ErrorCode
) 
 143         printf_P(PSTR(ESC_FG_RED 
"Host Mode Error\r\n" 
 144                                  " -- Error Code %d\r\n" ESC_FG_WHITE
), ErrorCode
); 
 146         LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 150 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while 
 151  *  enumerating an attached USB device. 
 153 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode
, 
 154                                             const uint8_t SubErrorCode
) 
 156         printf_P(PSTR(ESC_FG_RED 
"Dev Enum Error\r\n" 
 157                                  " -- Error Code %d\r\n" 
 158                                  " -- Sub Error Code %d\r\n" 
 159                                  " -- In State %d\r\n" ESC_FG_WHITE
), ErrorCode
, SubErrorCode
, USB_HostState
); 
 161         LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 164 /** Task to set the configuration of the attached device after it has been enumerated, and to read in blocks from 
 165  *  the device and print them to the serial port. 
 167 void MassStorageHost_Task(void) 
 169         if (USB_HostState 
!= HOST_STATE_Configured
) 
 172         /* Indicate device busy via the status LEDs */ 
 173         LEDs_SetAllLEDs(LEDMASK_USB_BUSY
); 
 177         /* Send the request, display error and wait for device detach if request fails */ 
 178         if ((ErrorCode 
= MassStore_GetMaxLUN(&MassStore_MaxLUNIndex
)) != HOST_SENDCONTROL_Successful
) 
 180                 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode
); 
 181                 USB_Host_SetDeviceConfiguration(0); 
 185         /* Print number of LUNs detected in the attached device */ 
 186         printf_P(PSTR("Total LUNs: %d - Using first LUN in device.\r\n"), (MassStore_MaxLUNIndex 
+ 1)); 
 188         /* Reset the Mass Storage device interface, ready for use */ 
 189         if ((ErrorCode 
= MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful
) 
 191                 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode
); 
 192                 USB_Host_SetDeviceConfiguration(0); 
 196         /* Get sense data from the device - many devices will not accept any other commands until the sense data 
 197          * is read - both on start-up and after a failed command */ 
 198         SCSI_Request_Sense_Response_t SenseData
; 
 199         if ((ErrorCode 
= MassStore_RequestSense(0, &SenseData
)) != 0) 
 201                 ShowDiskReadError(PSTR("Request Sense"), ErrorCode
); 
 202                 USB_Host_SetDeviceConfiguration(0); 
 206         /* Set the prevent removal flag for the device, allowing it to be accessed */ 
 207         if ((ErrorCode 
= MassStore_PreventAllowMediumRemoval(0, true)) != 0) 
 209                 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode
); 
 210                 USB_Host_SetDeviceConfiguration(0); 
 214         /* Get inquiry data from the device */ 
 215         SCSI_Inquiry_Response_t InquiryData
; 
 216         if ((ErrorCode 
= MassStore_Inquiry(0, &InquiryData
)) != 0) 
 218                 ShowDiskReadError(PSTR("Inquiry"), ErrorCode
); 
 219                 USB_Host_SetDeviceConfiguration(0); 
 223         /* Print vendor and product names of attached device */ 
 224         printf_P(PSTR("Vendor \"%.8s\", Product \"%.16s\"\r\n"), InquiryData
.VendorID
, InquiryData
.ProductID
); 
 226         /* Wait until disk ready */ 
 227         puts_P(PSTR("Waiting until ready..")); 
 231                 Serial_SendByte('.'); 
 233                 /* Abort if device removed */ 
 234                 if (USB_HostState 
== HOST_STATE_Unattached
) 
 237                 /* Check to see if the attached device is ready for new commands */ 
 238                 ErrorCode 
= MassStore_TestUnitReady(0); 
 240                 /* If attached device is ready, abort the loop */ 
 244                 /* If an error other than a logical command failure (indicating device busy) returned, abort */ 
 245                 if (ErrorCode 
!= MASS_STORE_SCSI_COMMAND_FAILED
) 
 247                         ShowDiskReadError(PSTR("Test Unit Ready"), ErrorCode
); 
 248                         USB_Host_SetDeviceConfiguration(0); 
 253         puts_P(PSTR("\r\nRetrieving Capacity... ")); 
 255         /* Create new structure for the disk's capacity in blocks and block size */ 
 256         SCSI_Capacity_t DiskCapacity
; 
 258         /* Retrieve disk capacity */ 
 259         if ((ErrorCode 
= MassStore_ReadCapacity(0, &DiskCapacity
)) != 0) 
 261                 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode
); 
 262                 USB_Host_SetDeviceConfiguration(0); 
 266         /* Display the disk capacity in blocks * block size bytes */ 
 267         printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity
.Blocks
, DiskCapacity
.BlockSize
); 
 269         /* Create a new buffer capable of holding a single block from the device */ 
 270         uint8_t BlockBuffer
[DiskCapacity
.BlockSize
]; 
 272         /* Read in the first 512 byte block from the device */ 
 273         if ((ErrorCode 
= MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0) 
 275                 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
); 
 276                 USB_Host_SetDeviceConfiguration(0); 
 280         puts_P(PSTR("\r\nContents of first block:\r\n")); 
 282         /* Print out the first block in both HEX and ASCII, 16 bytes per line */ 
 283         for (uint16_t Chunk 
= 0; Chunk 
< (DiskCapacity
.BlockSize 
>> 4); Chunk
++) 
 285                 /* Pointer to the start of the current 16-byte chunk in the read block of data */ 
 286                 uint8_t* ChunkPtr 
= &BlockBuffer
[Chunk 
<< 4]; 
 288                 /* Print out the 16 bytes of the chunk in HEX format */ 
 289                 for (uint8_t ByteOffset 
= 0; ByteOffset 
< (1 << 4); ByteOffset
++) 
 291                         char CurrByte 
= *(ChunkPtr 
+ ByteOffset
); 
 293                         printf_P(PSTR("%.2X "), CurrByte
); 
 298                 /* Print out the 16 bytes of the chunk in ASCII format */ 
 299                 for (uint8_t ByteOffset 
= 0; ByteOffset 
< (1 << 4); ByteOffset
++) 
 301                         char CurrByte 
= *(ChunkPtr 
+ ByteOffset
); 
 303                         putchar(isprint(CurrByte
) ? CurrByte 
: '.'); 
 306                 puts_P(PSTR("\r\n")); 
 309         puts_P(PSTR("\r\n\r\nPress board button to read entire ASCII contents of disk...\r\n\r\n")); 
 311         /* Wait for the board button to be pressed */ 
 312         while (!(Buttons_GetStatus() & BUTTONS_BUTTON1
)) 
 314                 /* Abort if device removed */ 
 315                 if (USB_HostState 
== HOST_STATE_Unattached
) 
 319         /* Print out the entire disk contents in ASCII format */ 
 320         for (uint32_t CurrBlockAddress 
= 0; CurrBlockAddress 
< DiskCapacity
.Blocks
; CurrBlockAddress
++) 
 322                 /* Read in the next block of data from the device */ 
 323                 if ((ErrorCode 
= MassStore_ReadDeviceBlock(0, CurrBlockAddress
, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0) 
 325                         ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
); 
 326                         USB_Host_SetDeviceConfiguration(0); 
 330                 /* Send the ASCII data in the read in block to the serial port */ 
 331                 for (uint16_t Byte 
= 0; Byte 
< DiskCapacity
.BlockSize
; Byte
++) 
 333                         char CurrByte 
= BlockBuffer
[Byte
]; 
 335                         putchar(isprint(CurrByte
) ? CurrByte 
: '.'); 
 339         /* Indicate device no longer busy */ 
 340         LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 341         USB_Host_SetDeviceConfiguration(0); 
 344 /** Indicates that a communication error has occurred with the attached Mass Storage Device, 
 345  *  printing error codes to the serial port and waiting until the device is removed before 
 348  *  \param[in] CommandString  ASCII string located in PROGMEM space indicating what operation failed 
 349  *  \param[in] ErrorCode      Error code of the function which failed to complete successfully 
 351 void ShowDiskReadError(const char* CommandString
, 
 352                        const uint8_t ErrorCode
) 
 354         if (ErrorCode 
== MASS_STORE_SCSI_COMMAND_FAILED
) 
 356                 /* Display the error code */ 
 357                 printf_P(PSTR(ESC_FG_RED 
"SCSI command error (%S).\r\n"), CommandString
); 
 361                 /* Display the error code */ 
 362                 printf_P(PSTR(ESC_FG_RED 
"Command error (%S).\r\n"), CommandString
); 
 363                 printf_P(PSTR("  -- Error Code: %d" ESC_FG_WHITE
), ErrorCode
); 
 368         /* Indicate device error via the status LEDs */ 
 369         LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);