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 SetSystemClockPrescaler(0);
69 /* Hardware Initialization */
70 SerialStream_Init(9600, false);
74 /* Indicate USB not ready */
75 UpdateStatus(Status_USBNotReady
);
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 occured 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 /* Send the request, display error and wait for device detatch if request fails */
174 if ((ErrorCode
= USB_Host_SendControlRequest(NULL
)) != HOST_SENDCONTROL_Successful
)
176 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
177 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
179 /* Indicate error via status LEDs */
180 UpdateStatus(Status_EnumerationError
);
182 /* Wait until USB device disconnected */
183 while (USB_IsConnected
);
187 USB_HostState
= HOST_STATE_Configured
;
189 case HOST_STATE_Configured
:
190 puts_P(PSTR("Getting Config Data.\r\n"));
192 /* Get and process the configuration descriptor data */
193 if ((ErrorCode
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
)
195 if (ErrorCode
== ControlError
)
196 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
198 puts_P(PSTR("Invalid Device.\r\n"));
200 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
);
202 /* Indicate error via status LEDs */
203 UpdateStatus(Status_EnumerationError
);
205 /* Wait until USB device disconnected */
206 while (USB_IsConnected
);
210 puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
212 USB_HostState
= HOST_STATE_Ready
;
214 case HOST_STATE_Ready
:
215 /* Indicate device busy via the status LEDs */
216 UpdateStatus(Status_Busy
);
218 /* Reset the Mass Storage device interface, ready for use */
219 if ((ErrorCode
= MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful
)
221 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode
);
225 /* Send the request, display error and wait for device detatch if request fails */
226 if ((ErrorCode
= MassStore_GetMaxLUN(&MassStore_MaxLUNIndex
)) != HOST_SENDCONTROL_Successful
)
228 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode
);
232 /* Print number of LUNs detected in the attached device */
233 printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex
+ 1));
235 /* Set the prevent removal flag for the device, allowing it to be accessed */
236 if ((ErrorCode
= MassStore_PreventAllowMediumRemoval(0, true)) != 0)
238 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode
);
242 /* Get sense data from the device - many devices will not accept any other commands until the sense data
243 * is read - both on startup and after a failed command */
244 SCSI_Request_Sense_Response_t SenseData
;
245 if ((ErrorCode
= MassStore_RequestSense(0, &SenseData
)) != 0)
247 ShowDiskReadError(PSTR("Request Sense"), ErrorCode
);
251 puts_P(PSTR("Waiting until ready"));
253 /* Wait until disk ready */
257 MassStore_TestUnitReady(0);
259 while ((SCSICommandStatus
.Status
!= Command_Pass
) && USB_IsConnected
);
261 /* Abort if device removed */
262 if (!(USB_IsConnected
))
265 puts_P(PSTR("\r\nRetrieving Capacity... "));
267 /* Create new structure for the disk's capacity in blocks and block size */
268 SCSI_Capacity_t DiskCapacity
;
270 /* Retrieve disk capacity */
271 if ((ErrorCode
= MassStore_ReadCapacity(0, &DiskCapacity
)) != 0)
273 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode
);
277 /* Display the disk capacity in blocks * block size bytes */
278 printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity
.Blocks
, DiskCapacity
.BlockSize
);
280 /* Create a new buffer capabable of holding a single block from the device */
281 uint8_t BlockBuffer
[DiskCapacity
.BlockSize
];
283 /* Read in the first 512 byte block from the device */
284 if ((ErrorCode
= MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0)
286 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
290 /* Show the number of bytes not transferred in the previous command */
291 printf_P(PSTR("Transfer Residue: %lu\r\n"), SCSICommandStatus
.DataTransferResidue
);
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 HWB to read entire ASCII contents of disk...\r\n\r\n"));
324 /* Wait for HWB to be pressed */
325 while (!(HWB_GetStatus()))
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)
338 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
342 /* Send the ASCII data in the read in block to the serial port */
343 for (uint16_t Byte
= 0; Byte
< DiskCapacity
.BlockSize
; Byte
++)
345 char CurrByte
= BlockBuffer
[Byte
];
347 putchar(isprint(CurrByte
) ? CurrByte
: '.');
350 /* Abort if device removed */
351 if (!(USB_IsConnected
))
355 /* Indicate device no longer busy */
356 UpdateStatus(Status_USBReady
);
358 /* Wait until USB device disconnected */
359 while (USB_IsConnected
);
365 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
366 * log to a serial port, or anything else that is suitable for status updates.
368 * \param CurrentStatus Current status of the system, from the MassStorageHost_StatusCodes_t enum
370 void UpdateStatus(uint8_t CurrentStatus
)
372 uint8_t LEDMask
= LEDS_NO_LEDS
;
374 /* Set the LED mask to the appropriate LED mask based on the given status code */
375 switch (CurrentStatus
)
377 case Status_USBNotReady
:
378 LEDMask
= (LEDS_LED1
);
380 case Status_USBEnumerating
:
381 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
383 case Status_USBReady
:
384 LEDMask
= (LEDS_LED2
);
386 case Status_EnumerationError
:
387 case Status_HardwareError
:
388 case Status_SCSICommandError
:
389 LEDMask
= (LEDS_LED1
| LEDS_LED3
);
392 LEDMask
= (LEDS_LED1
| LEDS_LED4
);
396 /* Set the board LEDs to the new LED mask */
397 LEDs_SetAllLEDs(LEDMask
);
400 /** Indicates that a communication error has ocurred with the attached Mass Storage Device,
401 * printing error codes to the serial port and waiting until the device is removed before
404 * \param CommandString ASCII string located in PROGMEM space indicating what operation failed
405 * \param ErrorCode Error code of the function which failed to complete successfully
407 void ShowDiskReadError(char* CommandString
, uint8_t ErrorCode
)
409 /* Display the error code */
410 printf_P(PSTR(ESC_BG_RED
"Command error (%S).\r\n"), CommandString
);
411 printf_P(PSTR(" -- Error Code: %d"), ErrorCode
);
415 /* Indicate device error via the status LEDs */
416 UpdateStatus(Status_SCSICommandError
);
418 /* Wait until USB device disconnected */
419 while (USB_IsConnected
);