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 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName
, "LUFA MS Host App");
41 BUTTLOADTAG(BuildTime
, __TIME__
);
42 BUTTLOADTAG(BuildDate
, __DATE__
);
43 BUTTLOADTAG(LUFAVersion
, "LUFA V" LUFA_VERSION_STRING
);
45 /* Scheduler Task List */
48 { Task
: USB_USBTask
, TaskStatus
: TASK_STOP
},
49 { Task
: USB_MassStore_Host
, TaskStatus
: TASK_STOP
},
53 /** Index of the highest available LUN (Logical Unit) in the attached Mass Storage Device */
54 uint8_t MassStore_MaxLUNIndex
;
57 /** Main program entry point. This routine configures the hardware required by the application, then
58 * starts the scheduler to run the application tasks.
62 /* Disable watchdog if enabled by bootloader/fuses */
63 MCUSR
&= ~(1 << WDRF
);
66 /* Disable clock division */
67 clock_prescale_set(clock_div_1
);
69 /* Hardware Initialization */
70 SerialStream_Init(9600, false);
74 /* Indicate USB not ready */
75 UpdateStatus(Status_USBNotReady
);
77 /* Start-up message */
78 puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
79 "MassStore Host Demo running.\r\n" ESC_INVERSE_OFF
));
81 /* Initialize Scheduler so that it can be used */
84 /* Initialize USB Subsystem */
87 /* Scheduling routine never returns, so put this last in the main function */
91 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
92 * starts the library USB task to begin the enumeration and USB management process.
94 EVENT_HANDLER(USB_DeviceAttached
)
96 puts_P(PSTR("Device Attached.\r\n"));
97 UpdateStatus(Status_USBEnumerating
);
99 /* Start USB management task to enumerate the device */
100 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
103 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
104 * stops the library USB task management process.
106 EVENT_HANDLER(USB_DeviceUnattached
)
108 /* Stop USB management and Mass Storage tasks */
109 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
110 Scheduler_SetTaskMode(USB_MassStore_Host
, TASK_STOP
);
112 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
113 UpdateStatus(Status_USBNotReady
);
116 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
117 * enumerated by the host and is now ready to be used by the application.
119 EVENT_HANDLER(USB_DeviceEnumerationComplete
)
121 /* Once device is fully enumerated, start the Mass Storage Host task */
122 Scheduler_SetTaskMode(USB_MassStore_Host
, TASK_RUN
);
124 /* Indicate device enumeration complete */
125 UpdateStatus(Status_USBReady
);
128 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
129 EVENT_HANDLER(USB_HostError
)
133 puts_P(PSTR(ESC_BG_RED
"Host Mode Error\r\n"));
134 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
136 UpdateStatus(Status_HardwareError
);
140 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
141 * enumerating an attached USB device.
143 EVENT_HANDLER(USB_DeviceEnumerationFailed
)
145 puts_P(PSTR(ESC_BG_RED
"Dev Enum Error\r\n"));
146 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
);
147 printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode
);
148 printf_P(PSTR(" -- In State %d\r\n"), USB_HostState
);
150 UpdateStatus(Status_EnumerationError
);
153 /** Task to set the configuration of the attached device after it has been enumerated, and to read in blocks from
154 * the device and print them to the serial port.
156 TASK(USB_MassStore_Host
)
160 switch (USB_HostState
)
162 case HOST_STATE_Addressed
:
163 /* Standard request to set the device configuration to configuration 1 */
164 USB_HostRequest
= (USB_Host_Request_Header_t
)
166 bmRequestType
: (REQDIR_HOSTTODEVICE
| REQTYPE_STANDARD
| REQREC_DEVICE
),
167 bRequest
: REQ_SetConfiguration
,
173 /* Select the control pipe for the request transfer */
174 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
176 /* Send the request, display error and wait for device detach if request fails */
177 if ((ErrorCode
= USB_Host_SendControlRequest(NULL
)) != HOST_SENDCONTROL_Successful
)
179 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
180 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
182 /* Indicate error via status LEDs */
183 UpdateStatus(Status_EnumerationError
);
185 /* Wait until USB device disconnected */
186 while (USB_IsConnected
);
190 USB_HostState
= HOST_STATE_Configured
;
192 case HOST_STATE_Configured
:
193 puts_P(PSTR("Getting Config Data.\r\n"));
195 /* Get and process the configuration descriptor data */
196 if ((ErrorCode
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
)
198 if (ErrorCode
== ControlError
)
199 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
201 puts_P(PSTR("Invalid Device.\r\n"));
203 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
205 /* Indicate error via status LEDs */
206 UpdateStatus(Status_EnumerationError
);
208 /* Wait until USB device disconnected */
209 while (USB_IsConnected
);
213 puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
215 USB_HostState
= HOST_STATE_Ready
;
217 case HOST_STATE_Ready
:
218 /* Indicate device busy via the status LEDs */
219 UpdateStatus(Status_Busy
);
221 /* Reset the Mass Storage device interface, ready for use */
222 if ((ErrorCode
= MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful
)
224 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode
);
228 /* Send the request, display error and wait for device detach if request fails */
229 if ((ErrorCode
= MassStore_GetMaxLUN(&MassStore_MaxLUNIndex
)) != HOST_SENDCONTROL_Successful
)
231 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode
);
235 /* Print number of LUNs detected in the attached device */
236 printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex
+ 1));
238 /* Set the prevent removal flag for the device, allowing it to be accessed */
239 if ((ErrorCode
= MassStore_PreventAllowMediumRemoval(0, true)) != 0)
241 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode
);
245 /* Get sense data from the device - many devices will not accept any other commands until the sense data
246 * is read - both on start-up and after a failed command */
247 SCSI_Request_Sense_Response_t SenseData
;
248 if ((ErrorCode
= MassStore_RequestSense(0, &SenseData
)) != 0)
250 ShowDiskReadError(PSTR("Request Sense"), ErrorCode
);
254 puts_P(PSTR("Waiting until ready"));
256 /* Wait until disk ready */
260 MassStore_TestUnitReady(0);
262 while ((SCSICommandStatus
.Status
!= Command_Pass
) && USB_IsConnected
);
264 /* Abort if device removed */
265 if (!(USB_IsConnected
))
268 puts_P(PSTR("\r\nRetrieving Capacity... "));
270 /* Create new structure for the disk's capacity in blocks and block size */
271 SCSI_Capacity_t DiskCapacity
;
273 /* Retrieve disk capacity */
274 if ((ErrorCode
= MassStore_ReadCapacity(0, &DiskCapacity
)) != 0)
276 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode
);
280 /* Display the disk capacity in blocks * block size bytes */
281 printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity
.Blocks
, DiskCapacity
.BlockSize
);
283 /* Create a new buffer capabable of holding a single block from the device */
284 uint8_t BlockBuffer
[DiskCapacity
.BlockSize
];
286 /* Read in the first 512 byte block from the device */
287 if ((ErrorCode
= MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0)
289 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
293 /* Show the number of bytes not transferred in the previous command */
294 printf_P(PSTR("Transfer Residue: %lu\r\n"), SCSICommandStatus
.DataTransferResidue
);
296 puts_P(PSTR("\r\nContents of first block:\r\n"));
298 /* Print out the first block in both HEX and ASCII, 16 bytes per line */
299 for (uint16_t Chunk
= 0; Chunk
< (DiskCapacity
.BlockSize
>> 4); Chunk
++)
301 /* Pointer to the start of the current 16-byte chunk in the read block of data */
302 uint8_t* ChunkPtr
= &BlockBuffer
[Chunk
<< 4];
304 /* Print out the 16 bytes of the chunk in HEX format */
305 for (uint8_t ByteOffset
= 0; ByteOffset
< (1 << 4); ByteOffset
++)
307 char CurrByte
= *(ChunkPtr
+ ByteOffset
);
309 printf_P(PSTR("%.2X "), CurrByte
);
314 /* Print out the 16 bytes of the chunk in ASCII format */
315 for (uint8_t ByteOffset
= 0; ByteOffset
< (1 << 4); ByteOffset
++)
317 char CurrByte
= *(ChunkPtr
+ ByteOffset
);
319 putchar(isprint(CurrByte
) ? CurrByte
: '.');
322 puts_P(PSTR("\r\n"));
325 puts_P(PSTR("\r\n\r\nPress HWB to read entire ASCII contents of disk...\r\n\r\n"));
327 /* Wait for HWB to be pressed */
328 while (!(HWB_GetStatus()))
330 /* Abort if device removed */
331 if (!(USB_IsConnected
))
335 /* Print out the entire disk contents in ASCII format */
336 for (uint32_t CurrBlock
= 0; CurrBlock
< DiskCapacity
.Blocks
; CurrBlock
++)
338 /* Read in the next block of data from the device */
339 if ((ErrorCode
= MassStore_ReadDeviceBlock(0, CurrBlock
, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0)
341 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
345 /* Send the ASCII data in the read in block to the serial port */
346 for (uint16_t Byte
= 0; Byte
< DiskCapacity
.BlockSize
; Byte
++)
348 char CurrByte
= BlockBuffer
[Byte
];
350 putchar(isprint(CurrByte
) ? CurrByte
: '.');
353 /* Abort if device removed */
354 if (!(USB_IsConnected
))
358 /* Indicate device no longer busy */
359 UpdateStatus(Status_USBReady
);
361 /* Wait until USB device disconnected */
362 while (USB_IsConnected
);
368 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
369 * log to a serial port, or anything else that is suitable for status updates.
371 * \param CurrentStatus Current status of the system, from the MassStorageHost_StatusCodes_t enum
373 void UpdateStatus(uint8_t CurrentStatus
)
375 uint8_t LEDMask
= LEDS_NO_LEDS
;
377 /* Set the LED mask to the appropriate LED mask based on the given status code */
378 switch (CurrentStatus
)
380 case Status_USBNotReady
:
381 LEDMask
= (LEDS_LED1
);
383 case Status_USBEnumerating
:
384 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
386 case Status_USBReady
:
387 LEDMask
= (LEDS_LED2
);
389 case Status_EnumerationError
:
390 case Status_HardwareError
:
391 case Status_SCSICommandError
:
392 LEDMask
= (LEDS_LED1
| LEDS_LED3
);
395 LEDMask
= (LEDS_LED1
| LEDS_LED4
);
399 /* Set the board LEDs to the new LED mask */
400 LEDs_SetAllLEDs(LEDMask
);
403 /** Indicates that a communication error has occurred with the attached Mass Storage Device,
404 * printing error codes to the serial port and waiting until the device is removed before
407 * \param CommandString ASCII string located in PROGMEM space indicating what operation failed
408 * \param ErrorCode Error code of the function which failed to complete successfully
410 void ShowDiskReadError(char* CommandString
, uint8_t ErrorCode
)
412 /* Display the error code */
413 printf_P(PSTR(ESC_BG_RED
"Command error (%S).\r\n"), CommandString
);
414 printf_P(PSTR(" -- Error Code: %d"), ErrorCode
);
418 /* Indicate device error via the status LEDs */
419 UpdateStatus(Status_SCSICommandError
);
421 /* Wait until USB device disconnected */
422 while (USB_IsConnected
);