3      Copyright (C) Dean Camera, 2009. 
   5   dean [at] fourwalledcubicle [dot] com 
   6       www.fourwalledcubicle.com 
  10   Copyright 2009  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  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. 
  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 
  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 /* Scheduler Task List */ 
  42         { .Task 
= USB_USBTask          
, .TaskStatus 
= TASK_STOP 
}, 
  43         { .Task 
= USB_MassStore_Host   
, .TaskStatus 
= TASK_STOP 
}, 
  47 /** Index of the highest available LUN (Logical Unit) in the attached Mass Storage Device */ 
  48 uint8_t MassStore_MaxLUNIndex
; 
  51 /** Main program entry point. This routine configures the hardware required by the application, then 
  52  *  starts the scheduler to run the application tasks. 
  56         /* Disable watchdog if enabled by bootloader/fuses */ 
  57         MCUSR 
&= ~(1 << WDRF
); 
  60         /* Disable clock division */ 
  61         clock_prescale_set(clock_div_1
); 
  63         /* Hardware Initialization */ 
  64         SerialStream_Init(9600, false); 
  68         /* Indicate USB not ready */ 
  69         UpdateStatus(Status_USBNotReady
); 
  71         /* Start-up message */ 
  72         puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
 
  73                "MassStore Host Demo running.\r\n" ESC_INVERSE_OFF
)); 
  75         /* Initialize Scheduler so that it can be used */ 
  78         /* Initialize USB Subsystem */ 
  81         /* Scheduling routine never returns, so put this last in the main function */ 
  85 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and 
  86  *  starts the library USB task to begin the enumeration and USB management process. 
  88 EVENT_HANDLER(USB_DeviceAttached
) 
  90         puts_P(PSTR("Device Attached.\r\n")); 
  91         UpdateStatus(Status_USBEnumerating
); 
  93         /* Start USB management task to enumerate the device */ 
  94         Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
); 
  97 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and 
  98  *  stops the library USB task management process. 
 100 EVENT_HANDLER(USB_DeviceUnattached
) 
 102         /* Stop USB management and Mass Storage tasks */ 
 103         Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
); 
 104         Scheduler_SetTaskMode(USB_MassStore_Host
, TASK_STOP
); 
 106         puts_P(PSTR("\r\nDevice Unattached.\r\n")); 
 107         UpdateStatus(Status_USBNotReady
); 
 110 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully 
 111  *  enumerated by the host and is now ready to be used by the application. 
 113 EVENT_HANDLER(USB_DeviceEnumerationComplete
) 
 115         /* Once device is fully enumerated, start the Mass Storage Host task */ 
 116         Scheduler_SetTaskMode(USB_MassStore_Host
, TASK_RUN
); 
 118         /* Indicate device enumeration complete */ 
 119         UpdateStatus(Status_USBReady
); 
 122 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */ 
 123 EVENT_HANDLER(USB_HostError
) 
 127         puts_P(PSTR(ESC_BG_RED 
"Host Mode Error\r\n")); 
 128         printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
); 
 130         UpdateStatus(Status_HardwareError
); 
 134 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while 
 135  *  enumerating an attached USB device. 
 137 EVENT_HANDLER(USB_DeviceEnumerationFailed
) 
 139         puts_P(PSTR(ESC_BG_RED 
"Dev Enum Error\r\n")); 
 140         printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
); 
 141         printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode
); 
 142         printf_P(PSTR(" -- In State %d\r\n"), USB_HostState
); 
 144         UpdateStatus(Status_EnumerationError
); 
 147 /** Task to set the configuration of the attached device after it has been enumerated, and to read in blocks from 
 148  *  the device and print them to the serial port. 
 150 TASK(USB_MassStore_Host
) 
 154         switch (USB_HostState
) 
 156                 case HOST_STATE_Addressed
: 
 157                         /* Standard request to set the device configuration to configuration 1 */ 
 158                         USB_ControlRequest 
= (USB_Request_Header_t
) 
 160                                         .bmRequestType 
= (REQDIR_HOSTTODEVICE 
| REQTYPE_STANDARD 
| REQREC_DEVICE
), 
 161                                         .bRequest      
= REQ_SetConfiguration
, 
 167                         /* Select the control pipe for the request transfer */ 
 168                         Pipe_SelectPipe(PIPE_CONTROLPIPE
); 
 170                         /* Send the request, display error and wait for device detach if request fails */ 
 171                         if ((ErrorCode 
= USB_Host_SendControlRequest(NULL
)) != HOST_SENDCONTROL_Successful
) 
 173                                 puts_P(PSTR("Control Error (Set Configuration).\r\n")); 
 174                                 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
); 
 176                                 /* Indicate error via status LEDs */ 
 177                                 UpdateStatus(Status_EnumerationError
); 
 179                                 /* Wait until USB device disconnected */ 
 180                                 while (USB_IsConnected
); 
 184                         USB_HostState 
= HOST_STATE_Configured
; 
 186                 case HOST_STATE_Configured
: 
 187                         puts_P(PSTR("Getting Config Data.\r\n")); 
 189                         /* Get and process the configuration descriptor data */ 
 190                         if ((ErrorCode 
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
) 
 192                                 if (ErrorCode 
== ControlError
) 
 193                                   puts_P(PSTR("Control Error (Get Configuration).\r\n")); 
 195                                   puts_P(PSTR("Invalid Device.\r\n")); 
 197                                 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
); 
 199                                 /* Indicate error via status LEDs */ 
 200                                 UpdateStatus(Status_EnumerationError
); 
 202                                 /* Wait until USB device disconnected */ 
 203                                 while (USB_IsConnected
); 
 207                         puts_P(PSTR("Mass Storage Disk Enumerated.\r\n")); 
 209                         USB_HostState 
= HOST_STATE_Ready
; 
 211                 case HOST_STATE_Ready
: 
 212                         /* Indicate device busy via the status LEDs */ 
 213                         UpdateStatus(Status_Busy
); 
 215                         /* Send the request, display error and wait for device detach if request fails */ 
 216                         if ((ErrorCode 
= MassStore_GetMaxLUN(&MassStore_MaxLUNIndex
)) != HOST_SENDCONTROL_Successful
) 
 218                                 ShowDiskReadError(PSTR("Get Max LUN"), false, ErrorCode
); 
 222                         /* Print number of LUNs detected in the attached device */ 
 223                         printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex 
+ 1)); 
 225                         /* Reset the Mass Storage device interface, ready for use */ 
 226                         if ((ErrorCode 
= MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful
) 
 228                                 ShowDiskReadError(PSTR("Mass Storage Reset"), false, ErrorCode
); 
 232                         /* Get sense data from the device - many devices will not accept any other commands until the sense data 
 233                          * is read - both on start-up and after a failed command */ 
 234                         SCSI_Request_Sense_Response_t SenseData
; 
 235                         if (((ErrorCode 
= MassStore_RequestSense(0, &SenseData
)) != 0) || (SCSICommandStatus
.Status 
!= Command_Pass
)) 
 237                                 ShowDiskReadError(PSTR("Request Sense"), (SCSICommandStatus
.Status 
!= Command_Pass
), ErrorCode
); 
 241                         /* Set the prevent removal flag for the device, allowing it to be accessed */ 
 242                         if (((ErrorCode 
= MassStore_PreventAllowMediumRemoval(0, true)) != 0) || (SCSICommandStatus
.Status 
!= Command_Pass
)) 
 244                                 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), (SCSICommandStatus
.Status 
!= Command_Pass
), ErrorCode
); 
 248                         puts_P(PSTR("Waiting until ready..")); 
 250                         /* Wait until disk ready */ 
 255                                 if ((ErrorCode 
= MassStore_TestUnitReady(0)) != 0) 
 257                                         ShowDiskReadError(PSTR("Test Unit Ready"), false, ErrorCode
); 
 261                         while ((SCSICommandStatus
.Status 
!= Command_Pass
) && USB_IsConnected
); 
 263                         /* Abort if device removed */ 
 264                         if (!(USB_IsConnected
)) 
 267                         puts_P(PSTR("\r\nRetrieving Capacity... ")); 
 269                         /* Create new structure for the disk's capacity in blocks and block size */ 
 270                         SCSI_Capacity_t DiskCapacity
; 
 272                         /* Retrieve disk capacity */ 
 273                         if (((ErrorCode 
= MassStore_ReadCapacity(0, &DiskCapacity
)) != 0) || (SCSICommandStatus
.Status 
!= Command_Pass
)) 
 275                                 ShowDiskReadError(PSTR("Read Capacity"), (SCSICommandStatus
.Status 
!= Command_Pass
), ErrorCode
); 
 279                         /* Display the disk capacity in blocks * block size bytes */ 
 280                         printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity
.Blocks
, DiskCapacity
.BlockSize
); 
 282                         /* Create a new buffer capabable of holding a single block from the device */ 
 283                         uint8_t BlockBuffer
[DiskCapacity
.BlockSize
]; 
 285                         /* Read in the first 512 byte block from the device */ 
 286                         if (((ErrorCode 
= MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0) || 
 287                             (SCSICommandStatus
.Status 
!= Command_Pass
)) 
 289                                 ShowDiskReadError(PSTR("Read Device Block"), (SCSICommandStatus
.Status 
!= Command_Pass
), ErrorCode
); 
 293                         puts_P(PSTR("\r\nContents of first block:\r\n")); 
 295                         /* Print out the first block in both HEX and ASCII, 16 bytes per line */ 
 296                         for (uint16_t Chunk 
= 0; Chunk 
< (DiskCapacity
.BlockSize 
>> 4); Chunk
++) 
 298                                 /* Pointer to the start of the current 16-byte chunk in the read block of data */ 
 299                                 uint8_t* ChunkPtr 
= &BlockBuffer
[Chunk 
<< 4]; 
 301                                 /* Print out the 16 bytes of the chunk in HEX format */ 
 302                                 for (uint8_t ByteOffset 
= 0; ByteOffset 
< (1 << 4); ByteOffset
++) 
 304                                         char CurrByte 
= *(ChunkPtr 
+ ByteOffset
); 
 306                                         printf_P(PSTR("%.2X "), CurrByte
); 
 311                                 /* Print out the 16 bytes of the chunk in ASCII format */ 
 312                                 for (uint8_t ByteOffset 
= 0; ByteOffset 
< (1 << 4); ByteOffset
++) 
 314                                         char CurrByte 
= *(ChunkPtr 
+ ByteOffset
); 
 316                                         putchar(isprint(CurrByte
) ? CurrByte 
: '.'); 
 319                                 puts_P(PSTR("\r\n")); 
 322                         puts_P(PSTR("\r\n\r\nPress board button to read entire ASCII contents of disk...\r\n\r\n")); 
 324                         /* Wait for the board button to be pressed */ 
 325                         while (!(Buttons_GetStatus() & BUTTONS_BUTTON1
)) 
 327                                 /* Abort if device removed */ 
 328                                 if (!(USB_IsConnected
)) 
 332                         /* Print out the entire disk contents in ASCII format */ 
 333                         for (uint32_t CurrBlock 
= 0; CurrBlock 
< DiskCapacity
.Blocks
; CurrBlock
++) 
 335                                 /* Read in the next block of data from the device */ 
 336                                 if (((ErrorCode 
= MassStore_ReadDeviceBlock(0, CurrBlock
, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0) || 
 337                                     (SCSICommandStatus
.Status 
!= Command_Pass
)) 
 339                                         ShowDiskReadError(PSTR("Read Device Block"), (SCSICommandStatus
.Status 
!= Command_Pass
), ErrorCode
); 
 343                                 /* Send the ASCII data in the read in block to the serial port */ 
 344                                 for (uint16_t Byte 
= 0; Byte 
< DiskCapacity
.BlockSize
; Byte
++) 
 346                                         char CurrByte 
= BlockBuffer
[Byte
]; 
 348                                         putchar(isprint(CurrByte
) ? CurrByte 
: '.'); 
 351                                 /* Abort if device removed */ 
 352                                 if (!(USB_IsConnected
)) 
 356                         /* Indicate device no longer busy */ 
 357                         UpdateStatus(Status_USBReady
); 
 359                         /* Wait until USB device disconnected */ 
 360                         while (USB_IsConnected
); 
 366 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to 
 367  *  log to a serial port, or anything else that is suitable for status updates. 
 369  *  \param CurrentStatus  Current status of the system, from the MassStorageHost_StatusCodes_t enum 
 371 void UpdateStatus(uint8_t CurrentStatus
) 
 373         uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 375         /* Set the LED mask to the appropriate LED mask based on the given status code */ 
 376         switch (CurrentStatus
) 
 378                 case Status_USBNotReady
: 
 379                         LEDMask 
= (LEDS_LED1
); 
 381                 case Status_USBEnumerating
: 
 382                         LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 384                 case Status_USBReady
: 
 385                         LEDMask 
= (LEDS_LED2
); 
 387                 case Status_EnumerationError
: 
 388                 case Status_HardwareError
: 
 389                 case Status_SCSICommandError
: 
 390                         LEDMask 
= (LEDS_LED1 
| LEDS_LED3
); 
 393                         LEDMask 
= (LEDS_LED1 
| LEDS_LED4
); 
 397         /* Set the board LEDs to the new LED mask */ 
 398         LEDs_SetAllLEDs(LEDMask
); 
 401 /** Indicates that a communication error has occurred with the attached Mass Storage Device, 
 402  *  printing error codes to the serial port and waiting until the device is removed before 
 405  *  \param CommandString  ASCII string located in PROGMEM space indicating what operation failed 
 406  *  \param FailedAtSCSILayer  Indicates if the command failed at the (logical) SCSI layer or at the physical USB layer 
 407  *  \param ErrorCode      Error code of the function which failed to complete successfully 
 409 void ShowDiskReadError(char* CommandString
, bool FailedAtSCSILayer
, uint8_t ErrorCode
) 
 411         if (FailedAtSCSILayer
) 
 413                 /* Display the error code */ 
 414                 printf_P(PSTR(ESC_BG_RED 
"SCSI command error (%S).\r\n"), CommandString
); 
 415                 printf_P(PSTR("  -- Status Code: %d"), ErrorCode
); 
 419                 /* Display the error code */ 
 420                 printf_P(PSTR(ESC_BG_RED 
"Command error (%S).\r\n"), CommandString
); 
 421                 printf_P(PSTR("  -- Error Code: %d"), ErrorCode
);        
 426         /* Indicate device error via the status LEDs */ 
 427         UpdateStatus(Status_SCSICommandError
); 
 429         /* Wait until USB device disconnected */ 
 430         while (USB_IsConnected
);