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 /* Reset the Mass Storage device interface, ready for use */
216 if ((ErrorCode
= MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful
)
218 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode
);
222 /* Send the request, display error and wait for device detach if request fails */
223 if ((ErrorCode
= MassStore_GetMaxLUN(&MassStore_MaxLUNIndex
)) != HOST_SENDCONTROL_Successful
)
225 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode
);
229 /* Print number of LUNs detected in the attached device */
230 printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex
+ 1));
232 /* Set the prevent removal flag for the device, allowing it to be accessed */
233 if ((ErrorCode
= MassStore_PreventAllowMediumRemoval(0, true)) != 0)
235 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode
);
239 /* Get sense data from the device - many devices will not accept any other commands until the sense data
240 * is read - both on start-up and after a failed command */
241 SCSI_Request_Sense_Response_t SenseData
;
242 if ((ErrorCode
= MassStore_RequestSense(0, &SenseData
)) != 0)
244 ShowDiskReadError(PSTR("Request Sense"), ErrorCode
);
248 puts_P(PSTR("Waiting until ready"));
250 /* Wait until disk ready */
254 MassStore_TestUnitReady(0);
256 while ((SCSICommandStatus
.Status
!= Command_Pass
) && USB_IsConnected
);
258 /* Abort if device removed */
259 if (!(USB_IsConnected
))
262 puts_P(PSTR("\r\nRetrieving Capacity... "));
264 /* Create new structure for the disk's capacity in blocks and block size */
265 SCSI_Capacity_t DiskCapacity
;
267 /* Retrieve disk capacity */
268 if ((ErrorCode
= MassStore_ReadCapacity(0, &DiskCapacity
)) != 0)
270 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode
);
274 /* Display the disk capacity in blocks * block size bytes */
275 printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity
.Blocks
, DiskCapacity
.BlockSize
);
277 /* Create a new buffer capabable of holding a single block from the device */
278 uint8_t BlockBuffer
[DiskCapacity
.BlockSize
];
280 /* Read in the first 512 byte block from the device */
281 if ((ErrorCode
= MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0)
283 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
287 /* Show the number of bytes not transferred in the previous command */
288 printf_P(PSTR("Transfer Residue: %lu\r\n"), SCSICommandStatus
.DataTransferResidue
);
290 puts_P(PSTR("\r\nContents of first block:\r\n"));
292 /* Print out the first block in both HEX and ASCII, 16 bytes per line */
293 for (uint16_t Chunk
= 0; Chunk
< (DiskCapacity
.BlockSize
>> 4); Chunk
++)
295 /* Pointer to the start of the current 16-byte chunk in the read block of data */
296 uint8_t* ChunkPtr
= &BlockBuffer
[Chunk
<< 4];
298 /* Print out the 16 bytes of the chunk in HEX format */
299 for (uint8_t ByteOffset
= 0; ByteOffset
< (1 << 4); ByteOffset
++)
301 char CurrByte
= *(ChunkPtr
+ ByteOffset
);
303 printf_P(PSTR("%.2X "), CurrByte
);
308 /* Print out the 16 bytes of the chunk in ASCII format */
309 for (uint8_t ByteOffset
= 0; ByteOffset
< (1 << 4); ByteOffset
++)
311 char CurrByte
= *(ChunkPtr
+ ByteOffset
);
313 putchar(isprint(CurrByte
) ? CurrByte
: '.');
316 puts_P(PSTR("\r\n"));
319 puts_P(PSTR("\r\n\r\nPress HWB to read entire ASCII contents of disk...\r\n\r\n"));
321 /* Wait for HWB to be pressed */
322 while (!(HWB_GetStatus()))
324 /* Abort if device removed */
325 if (!(USB_IsConnected
))
329 /* Print out the entire disk contents in ASCII format */
330 for (uint32_t CurrBlock
= 0; CurrBlock
< DiskCapacity
.Blocks
; CurrBlock
++)
332 /* Read in the next block of data from the device */
333 if ((ErrorCode
= MassStore_ReadDeviceBlock(0, CurrBlock
, 1, DiskCapacity
.BlockSize
, BlockBuffer
)) != 0)
335 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode
);
339 /* Send the ASCII data in the read in block to the serial port */
340 for (uint16_t Byte
= 0; Byte
< DiskCapacity
.BlockSize
; Byte
++)
342 char CurrByte
= BlockBuffer
[Byte
];
344 putchar(isprint(CurrByte
) ? CurrByte
: '.');
347 /* Abort if device removed */
348 if (!(USB_IsConnected
))
352 /* Indicate device no longer busy */
353 UpdateStatus(Status_USBReady
);
355 /* Wait until USB device disconnected */
356 while (USB_IsConnected
);
362 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
363 * log to a serial port, or anything else that is suitable for status updates.
365 * \param CurrentStatus Current status of the system, from the MassStorageHost_StatusCodes_t enum
367 void UpdateStatus(uint8_t CurrentStatus
)
369 uint8_t LEDMask
= LEDS_NO_LEDS
;
371 /* Set the LED mask to the appropriate LED mask based on the given status code */
372 switch (CurrentStatus
)
374 case Status_USBNotReady
:
375 LEDMask
= (LEDS_LED1
);
377 case Status_USBEnumerating
:
378 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
380 case Status_USBReady
:
381 LEDMask
= (LEDS_LED2
);
383 case Status_EnumerationError
:
384 case Status_HardwareError
:
385 case Status_SCSICommandError
:
386 LEDMask
= (LEDS_LED1
| LEDS_LED3
);
389 LEDMask
= (LEDS_LED1
| LEDS_LED4
);
393 /* Set the board LEDs to the new LED mask */
394 LEDs_SetAllLEDs(LEDMask
);
397 /** Indicates that a communication error has occurred with the attached Mass Storage Device,
398 * printing error codes to the serial port and waiting until the device is removed before
401 * \param CommandString ASCII string located in PROGMEM space indicating what operation failed
402 * \param ErrorCode Error code of the function which failed to complete successfully
404 void ShowDiskReadError(char* CommandString
, uint8_t ErrorCode
)
406 /* Display the error code */
407 printf_P(PSTR(ESC_BG_RED
"Command error (%S).\r\n"), CommandString
);
408 printf_P(PSTR(" -- Error Code: %d"), ErrorCode
);
412 /* Indicate device error via the status LEDs */
413 UpdateStatus(Status_SCSICommandError
);
415 /* Wait until USB device disconnected */
416 while (USB_IsConnected
);