Add tag for the 120219 release.
[pub/USBasp.git] / Demos / Host / LowLevel / MassStorageHost / MassStorageHost.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2012.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
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
28 this software.
29 */
30
31 /** \file
32 *
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.
35 */
36
37 #include "MassStorageHost.h"
38
39 /** Index of the highest available LUN (Logical Unit) in the attached Mass Storage Device */
40 uint8_t MassStore_MaxLUNIndex;
41
42
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.
45 */
46 int main(void)
47 {
48 SetupHardware();
49
50 puts_P(PSTR(ESC_FG_CYAN "Mass Storage Host Demo running.\r\n" ESC_FG_WHITE));
51
52 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
53 sei();
54
55 for (;;)
56 {
57 MassStorageHost_Task();
58
59 USB_USBTask();
60 }
61 }
62
63 /** Configures the board hardware and chip peripherals for the demo's functionality. */
64 void SetupHardware(void)
65 {
66 /* Disable watchdog if enabled by bootloader/fuses */
67 MCUSR &= ~(1 << WDRF);
68 wdt_disable();
69
70 /* Disable clock division */
71 clock_prescale_set(clock_div_1);
72
73 /* Hardware Initialization */
74 Serial_Init(9600, false);
75 LEDs_Init();
76 Buttons_Init();
77 USB_Init();
78
79 /* Create a stdio stream for the serial port for stdin and stdout */
80 Serial_CreateStream(NULL);
81 }
82
83 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
84 * starts the library USB task to begin the enumeration and USB management process.
85 */
86 void EVENT_USB_Host_DeviceAttached(void)
87 {
88 puts_P(PSTR(ESC_FG_GREEN "Device Attached.\r\n" ESC_FG_WHITE));
89 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
90 }
91
92 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
93 * stops the library USB task management process.
94 */
95 void EVENT_USB_Host_DeviceUnattached(void)
96 {
97 puts_P(PSTR(ESC_FG_GREEN "\r\nDevice Unattached.\r\n" ESC_FG_WHITE));
98 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
99 }
100
101 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
102 * enumerated by the host and is now ready to be used by the application.
103 */
104 void EVENT_USB_Host_DeviceEnumerationComplete(void)
105 {
106 puts_P(PSTR("Getting Config Data.\r\n"));
107
108 uint8_t ErrorCode;
109
110 /* Get and process the configuration descriptor data */
111 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
112 {
113 if (ErrorCode == ControlError)
114 puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
115 else
116 puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));
117
118 printf_P(PSTR(" -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
119
120 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
121 return;
122 }
123
124 /* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
125 if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
126 {
127 printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
128 " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);
129
130 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
131 return;
132 }
133
134 puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
135 LEDs_SetAllLEDs(LEDMASK_USB_READY);
136 }
137
138 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
139 void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
140 {
141 USB_Disable();
142
143 printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
144 " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);
145
146 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
147 for(;;);
148 }
149
150 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
151 * enumerating an attached USB device.
152 */
153 void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
154 const uint8_t SubErrorCode)
155 {
156 printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
157 " -- Error Code %d\r\n"
158 " -- Sub Error Code %d\r\n"
159 " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);
160
161 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
162 }
163
164 /** Task to set the configuration of the attached device after it has been enumerated, and to read in blocks from
165 * the device and print them to the serial port.
166 */
167 void MassStorageHost_Task(void)
168 {
169 if (USB_HostState != HOST_STATE_Configured)
170 return;
171
172 /* Indicate device busy via the status LEDs */
173 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
174
175 uint8_t ErrorCode;
176
177 /* Send the request, display error and wait for device detach if request fails */
178 if ((ErrorCode = MassStore_GetMaxLUN(&MassStore_MaxLUNIndex)) != HOST_SENDCONTROL_Successful)
179 {
180 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode);
181 USB_Host_SetDeviceConfiguration(0);
182 return;
183 }
184
185 /* Print number of LUNs detected in the attached device */
186 printf_P(PSTR("Total LUNs: %d - Using first LUN in device.\r\n"), (MassStore_MaxLUNIndex + 1));
187
188 /* Reset the Mass Storage device interface, ready for use */
189 if ((ErrorCode = MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful)
190 {
191 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode);
192 USB_Host_SetDeviceConfiguration(0);
193 return;
194 }
195
196 /* Get sense data from the device - many devices will not accept any other commands until the sense data
197 * is read - both on start-up and after a failed command */
198 SCSI_Request_Sense_Response_t SenseData;
199 if ((ErrorCode = MassStore_RequestSense(0, &SenseData)) != 0)
200 {
201 ShowDiskReadError(PSTR("Request Sense"), ErrorCode);
202 USB_Host_SetDeviceConfiguration(0);
203 return;
204 }
205
206 /* Set the prevent removal flag for the device, allowing it to be accessed */
207 if ((ErrorCode = MassStore_PreventAllowMediumRemoval(0, true)) != 0)
208 {
209 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode);
210 USB_Host_SetDeviceConfiguration(0);
211 return;
212 }
213
214 /* Get inquiry data from the device */
215 SCSI_Inquiry_Response_t InquiryData;
216 if ((ErrorCode = MassStore_Inquiry(0, &InquiryData)) != 0)
217 {
218 ShowDiskReadError(PSTR("Inquiry"), ErrorCode);
219 USB_Host_SetDeviceConfiguration(0);
220 return;
221 }
222
223 /* Print vendor and product names of attached device */
224 printf_P(PSTR("Vendor \"%.8s\", Product \"%.16s\"\r\n"), InquiryData.VendorID, InquiryData.ProductID);
225
226 /* Wait until disk ready */
227 puts_P(PSTR("Waiting until ready.."));
228
229 for (;;)
230 {
231 Serial_SendByte('.');
232
233 /* Abort if device removed */
234 if (USB_HostState == HOST_STATE_Unattached)
235 break;
236
237 /* Check to see if the attached device is ready for new commands */
238 ErrorCode = MassStore_TestUnitReady(0);
239
240 /* If attached device is ready, abort the loop */
241 if (!(ErrorCode))
242 break;
243
244 /* If an error other than a logical command failure (indicating device busy) returned, abort */
245 if (ErrorCode != MASS_STORE_SCSI_COMMAND_FAILED)
246 {
247 ShowDiskReadError(PSTR("Test Unit Ready"), ErrorCode);
248 USB_Host_SetDeviceConfiguration(0);
249 return;
250 }
251 }
252
253 puts_P(PSTR("\r\nRetrieving Capacity... "));
254
255 /* Create new structure for the disk's capacity in blocks and block size */
256 SCSI_Capacity_t DiskCapacity;
257
258 /* Retrieve disk capacity */
259 if ((ErrorCode = MassStore_ReadCapacity(0, &DiskCapacity)) != 0)
260 {
261 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode);
262 USB_Host_SetDeviceConfiguration(0);
263 return;
264 }
265
266 /* Display the disk capacity in blocks * block size bytes */
267 printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity.Blocks, DiskCapacity.BlockSize);
268
269 /* Create a new buffer capable of holding a single block from the device */
270 uint8_t BlockBuffer[DiskCapacity.BlockSize];
271
272 /* Read in the first 512 byte block from the device */
273 if ((ErrorCode = MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
274 {
275 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
276 USB_Host_SetDeviceConfiguration(0);
277 return;
278 }
279
280 puts_P(PSTR("\r\nContents of first block:\r\n"));
281
282 /* Print out the first block in both HEX and ASCII, 16 bytes per line */
283 for (uint16_t Chunk = 0; Chunk < (DiskCapacity.BlockSize >> 4); Chunk++)
284 {
285 /* Pointer to the start of the current 16-byte chunk in the read block of data */
286 uint8_t* ChunkPtr = &BlockBuffer[Chunk << 4];
287
288 /* Print out the 16 bytes of the chunk in HEX format */
289 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
290 {
291 char CurrByte = *(ChunkPtr + ByteOffset);
292
293 printf_P(PSTR("%.2X "), CurrByte);
294 }
295
296 puts_P(PSTR(" "));
297
298 /* Print out the 16 bytes of the chunk in ASCII format */
299 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
300 {
301 char CurrByte = *(ChunkPtr + ByteOffset);
302
303 putchar(isprint(CurrByte) ? CurrByte : '.');
304 }
305
306 puts_P(PSTR("\r\n"));
307 }
308
309 puts_P(PSTR("\r\n\r\nPress board button to read entire ASCII contents of disk...\r\n\r\n"));
310
311 /* Wait for the board button to be pressed */
312 while (!(Buttons_GetStatus() & BUTTONS_BUTTON1))
313 {
314 /* Abort if device removed */
315 if (USB_HostState == HOST_STATE_Unattached)
316 return;
317 }
318
319 /* Print out the entire disk contents in ASCII format */
320 for (uint32_t CurrBlockAddress = 0; CurrBlockAddress < DiskCapacity.Blocks; CurrBlockAddress++)
321 {
322 /* Read in the next block of data from the device */
323 if ((ErrorCode = MassStore_ReadDeviceBlock(0, CurrBlockAddress, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
324 {
325 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
326 USB_Host_SetDeviceConfiguration(0);
327 return;
328 }
329
330 /* Send the ASCII data in the read in block to the serial port */
331 for (uint16_t Byte = 0; Byte < DiskCapacity.BlockSize; Byte++)
332 {
333 char CurrByte = BlockBuffer[Byte];
334
335 putchar(isprint(CurrByte) ? CurrByte : '.');
336 }
337 }
338
339 /* Indicate device no longer busy */
340 LEDs_SetAllLEDs(LEDMASK_USB_READY);
341 USB_Host_SetDeviceConfiguration(0);
342 }
343
344 /** Indicates that a communication error has occurred with the attached Mass Storage Device,
345 * printing error codes to the serial port and waiting until the device is removed before
346 * continuing.
347 *
348 * \param[in] CommandString ASCII string located in PROGMEM space indicating what operation failed
349 * \param[in] ErrorCode Error code of the function which failed to complete successfully
350 */
351 void ShowDiskReadError(const char* CommandString,
352 const uint8_t ErrorCode)
353 {
354 if (ErrorCode == MASS_STORE_SCSI_COMMAND_FAILED)
355 {
356 /* Display the error code */
357 printf_P(PSTR(ESC_FG_RED "SCSI command error (%S).\r\n"), CommandString);
358 }
359 else
360 {
361 /* Display the error code */
362 printf_P(PSTR(ESC_FG_RED "Command error (%S).\r\n"), CommandString);
363 printf_P(PSTR(" -- Error Code: %d" ESC_FG_WHITE), ErrorCode);
364 }
365
366 Pipe_Freeze();
367
368 /* Indicate device error via the status LEDs */
369 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
370 }
371