3 Copyright (C) Dean Camera, 2015.
5 dean [at] fourwalledcubicle [dot] com
10 Copyright 2015 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 #if (ARCH == ARCH_AVR8)
67 /* Disable watchdog if enabled by bootloader/fuses */
68 MCUSR
&= ~(1 << WDRF
);
71 /* Disable clock division */
72 clock_prescale_set(clock_div_1
);
75 /* Hardware Initialization */
76 Serial_Init(9600, false);
81 /* Create a stdio stream for the serial port for stdin and stdout */
82 Serial_CreateStream(NULL
);
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 void EVENT_USB_Host_DeviceAttached(void)
90 puts_P(PSTR(ESC_FG_GREEN
"Device Attached.\r\n" ESC_FG_WHITE
));
91 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
94 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
95 * stops the library USB task management process.
97 void EVENT_USB_Host_DeviceUnattached(void)
99 puts_P(PSTR(ESC_FG_GREEN
"\r\nDevice Unattached.\r\n" ESC_FG_WHITE
));
100 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
103 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
104 * enumerated by the host and is now ready to be used by the application.
106 void EVENT_USB_Host_DeviceEnumerationComplete(void)
108 puts_P(PSTR("Getting Config Data.\r\n"));
112 /* Get and process the configuration descriptor data */
113 if ((ErrorCode
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
)
115 if (ErrorCode
== ControlError
)
116 puts_P(PSTR(ESC_FG_RED
"Control Error (Get Configuration).\r\n"));
118 puts_P(PSTR(ESC_FG_RED
"Invalid Device.\r\n"));
120 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE
), ErrorCode
);
122 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
126 /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
127 if ((ErrorCode
= USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful
)
129 printf_P(PSTR(ESC_FG_RED
"Control Error (Set Configuration).\r\n"
130 " -- Error Code: %d\r\n" ESC_FG_WHITE
), ErrorCode
);
132 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
136 puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
137 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
140 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
141 void EVENT_USB_Host_HostError(const uint8_t ErrorCode
)
145 printf_P(PSTR(ESC_FG_RED
"Host Mode Error\r\n"
146 " -- Error Code %d\r\n" ESC_FG_WHITE
), ErrorCode
);
148 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
152 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
153 * enumerating an attached USB device.
155 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode
,
156 const uint8_t SubErrorCode
)
158 printf_P(PSTR(ESC_FG_RED
"Dev Enum Error\r\n"
159 " -- Error Code %d\r\n"
160 " -- Sub Error Code %d\r\n"
161 " -- In State %d\r\n" ESC_FG_WHITE
), ErrorCode
, SubErrorCode
, USB_HostState
);
163 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
166 /** Task to set the configuration of the attached device after it has been enumerated, and to read in blocks from
167 * the device and print them to the serial port.
169 void MassStorageHost_Task(void)
171 if (USB_HostState
!= HOST_STATE_Configured
)
174 /* Indicate device busy via the status LEDs */
175 LEDs_SetAllLEDs(LEDMASK_USB_BUSY
);
179 /* Send the request, display error and wait for device detach if request fails */
180 if ((ErrorCode
= MassStore_GetMaxLUN(&MassStore_MaxLUNIndex
)) != HOST_SENDCONTROL_Successful
)
182 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode
);
183 USB_Host_SetDeviceConfiguration(0);
187 /* Print number of LUNs detected in the attached device */
188 printf_P(PSTR("Total LUNs: %d - Using first LUN in device.\r\n"), (MassStore_MaxLUNIndex
+ 1));
190 /* Reset the Mass Storage device interface, ready for use */
191 if ((ErrorCode
= MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful
)
193 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode
);
194 USB_Host_SetDeviceConfiguration(0);
198 /* Get sense data from the device - many devices will not accept any other commands until the sense data
199 * is read - both on start-up and after a failed command */
200 SCSI_Request_Sense_Response_t SenseData
;
201 if ((ErrorCode
= MassStore_RequestSense(0, &SenseData
)) != 0)
203 ShowDiskReadError(PSTR("Request Sense"), ErrorCode
);
204 USB_Host_SetDeviceConfiguration(0);
208 /* Set the prevent removal flag for the device, allowing it to be accessed */
209 if ((ErrorCode
= MassStore_PreventAllowMediumRemoval(0, true)) != 0)
211 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode
);
212 USB_Host_SetDeviceConfiguration(0);
216 /* Get inquiry data from the device */
217 SCSI_Inquiry_Response_t InquiryData
;
218 if ((ErrorCode
= MassStore_Inquiry(0, &InquiryData
)) != 0)
220 ShowDiskReadError(PSTR("Inquiry"), ErrorCode
);
221 USB_Host_SetDeviceConfiguration(0);
225 /* Print vendor and product names of attached device */
226 printf_P(PSTR("Vendor \"%.8s\", Product \"%.16s\"\r\n"), InquiryData
.VendorID
, InquiryData
.ProductID
);
228 /* Wait until disk ready */
229 puts_P(PSTR("Waiting until ready.."));
233 Serial_SendByte('.');
235 /* Abort if device removed */
236 if (USB_HostState
== HOST_STATE_Unattached
)
239 /* Check to see if the attached device is ready for new commands */
240 ErrorCode
= MassStore_TestUnitReady(0);
242 /* If attached device is ready, abort the loop */
246 /* If an error other than a logical command failure (indicating device busy) returned, abort */
247 if (ErrorCode
!= MASS_STORE_SCSI_COMMAND_FAILED
)
249 ShowDiskReadError(PSTR("Test Unit Ready"), ErrorCode
);
250 USB_Host_SetDeviceConfiguration(0);
255 puts_P(PSTR("\r\nRetrieving Capacity... "));
257 /* Create new structure for the disk's capacity in blocks and block size */
258 SCSI_Capacity_t DiskCapacity
;
260 /* Retrieve disk capacity */
261 if ((ErrorCode
= MassStore_ReadCapacity(0, &DiskCapacity
)) != 0)
263 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode
);
264 USB_Host_SetDeviceConfiguration(0);
268 /* Display the disk capacity in blocks * block size bytes */
269 printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity
.Blocks
, DiskCapacity
.BlockSize
);
271 /* Create a new buffer capable of holding a single block from the device */
272 uint8_t BlockBuffer
[DiskCapacity
.BlockSize
];
274 /* Read in the first 512 byte block from the device */
275 if ((ErrorCode
= MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0)
277 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
278 USB_Host_SetDeviceConfiguration(0);
282 puts_P(PSTR("\r\nContents of first block:\r\n"));
284 /* Print out the first block in both HEX and ASCII, 16 bytes per line */
285 for (uint16_t Chunk
= 0; Chunk
< (DiskCapacity
.BlockSize
>> 4); Chunk
++)
287 /* Pointer to the start of the current 16-byte chunk in the read block of data */
288 uint8_t* ChunkPtr
= &BlockBuffer
[Chunk
<< 4];
290 /* Print out the 16 bytes of the chunk in HEX format */
291 for (uint8_t ByteOffset
= 0; ByteOffset
< (1 << 4); ByteOffset
++)
293 char CurrByte
= *(ChunkPtr
+ ByteOffset
);
295 printf_P(PSTR("%.2X "), CurrByte
);
300 /* Print out the 16 bytes of the chunk in ASCII format */
301 for (uint8_t ByteOffset
= 0; ByteOffset
< (1 << 4); ByteOffset
++)
303 char CurrByte
= *(ChunkPtr
+ ByteOffset
);
305 putchar(isprint(CurrByte
) ? CurrByte
: '.');
308 puts_P(PSTR("\r\n"));
311 puts_P(PSTR("\r\n\r\nPress board button to read entire ASCII contents of disk...\r\n\r\n"));
313 /* Wait for the board button to be pressed */
314 while (!(Buttons_GetStatus() & BUTTONS_BUTTON1
))
316 /* Abort if device removed */
317 if (USB_HostState
== HOST_STATE_Unattached
)
321 /* Print out the entire disk contents in ASCII format */
322 for (uint32_t CurrBlockAddress
= 0; CurrBlockAddress
< DiskCapacity
.Blocks
; CurrBlockAddress
++)
324 /* Read in the next block of data from the device */
325 if ((ErrorCode
= MassStore_ReadDeviceBlock(0, CurrBlockAddress
, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0)
327 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
328 USB_Host_SetDeviceConfiguration(0);
332 /* Send the ASCII data in the read in block to the serial port */
333 for (uint16_t Byte
= 0; Byte
< DiskCapacity
.BlockSize
; Byte
++)
335 char CurrByte
= BlockBuffer
[Byte
];
337 putchar(isprint(CurrByte
) ? CurrByte
: '.');
341 /* Indicate device no longer busy */
342 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
343 USB_Host_SetDeviceConfiguration(0);
346 /** Indicates that a communication error has occurred with the attached Mass Storage Device,
347 * printing error codes to the serial port and waiting until the device is removed before
350 * \param[in] CommandString ASCII string located in PROGMEM space indicating what operation failed
351 * \param[in] ErrorCode Error code of the function which failed to complete successfully
353 void ShowDiskReadError(const char* CommandString
,
354 const uint8_t ErrorCode
)
356 if (ErrorCode
== MASS_STORE_SCSI_COMMAND_FAILED
)
358 /* Display the error code */
359 printf_P(PSTR(ESC_FG_RED
"SCSI command error (%S).\r\n"), CommandString
);
363 /* Display the error code */
364 printf_P(PSTR(ESC_FG_RED
"Command error (%S).\r\n"), CommandString
);
365 printf_P(PSTR(" -- Error Code: %d" ESC_FG_WHITE
), ErrorCode
);
370 /* Indicate device error via the status LEDs */
371 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);