Finished basic documentation of all device mode class drivers.
[pub/USBasp.git] / Demos / Host / ClassDriver / MassStorageHost / MassStorageHost.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
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 /* Scheduler Task List */
40 TASK_LIST
41 {
42 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
43 { .Task = USB_MassStore_Host , .TaskStatus = TASK_STOP },
44 };
45
46 /* Globals */
47 /** Index of the highest available LUN (Logical Unit) in the attached Mass Storage Device */
48 uint8_t MassStore_MaxLUNIndex;
49
50
51 /** Main program entry point. This routine configures the hardware required by the application, then
52 * starts the scheduler to run the application tasks.
53 */
54 int main(void)
55 {
56 /* Disable watchdog if enabled by bootloader/fuses */
57 MCUSR &= ~(1 << WDRF);
58 wdt_disable();
59
60 /* Disable clock division */
61 clock_prescale_set(clock_div_1);
62
63 /* Hardware Initialization */
64 SerialStream_Init(9600, false);
65 LEDs_Init();
66 Buttons_Init();
67
68 /* Indicate USB not ready */
69 UpdateStatus(Status_USBNotReady);
70
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));
74
75 /* Initialize Scheduler so that it can be used */
76 Scheduler_Init();
77
78 /* Initialize USB Subsystem */
79 USB_Init();
80
81 /* Scheduling routine never returns, so put this last in the main function */
82 Scheduler_Start();
83 }
84
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.
87 */
88 void EVENT_USB_DeviceAttached(void)
89 {
90 puts_P(PSTR("Device Attached.\r\n"));
91 UpdateStatus(Status_USBEnumerating);
92
93 /* Start USB management task to enumerate the device */
94 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
95 }
96
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.
99 */
100 void EVENT_USB_DeviceUnattached(void)
101 {
102 /* Stop USB management and Mass Storage tasks */
103 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
104 Scheduler_SetTaskMode(USB_MassStore_Host, TASK_STOP);
105
106 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
107 UpdateStatus(Status_USBNotReady);
108 }
109
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.
112 */
113 void EVENT_USB_DeviceEnumerationComplete(void)
114 {
115 /* Once device is fully enumerated, start the Mass Storage Host task */
116 Scheduler_SetTaskMode(USB_MassStore_Host, TASK_RUN);
117
118 /* Indicate device enumeration complete */
119 UpdateStatus(Status_USBReady);
120 }
121
122 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
123 void EVENT_USB_HostError(const uint8_t ErrorCode)
124 {
125 USB_ShutDown();
126
127 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
128 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
129
130 UpdateStatus(Status_HardwareError);
131 for(;;);
132 }
133
134 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
135 * enumerating an attached USB device.
136 */
137 void EVENT_USB_DeviceEnumerationFailed(const uint8_t ErrorCode, const uint8_t SubErrorCode)
138 {
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);
143
144 UpdateStatus(Status_EnumerationError);
145 }
146
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.
149 */
150 TASK(USB_MassStore_Host)
151 {
152 uint8_t ErrorCode;
153
154 switch (USB_HostState)
155 {
156 case HOST_STATE_Addressed:
157 /* Standard request to set the device configuration to configuration 1 */
158 USB_ControlRequest = (USB_Request_Header_t)
159 {
160 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
161 .bRequest = REQ_SetConfiguration,
162 .wValue = 1,
163 .wIndex = 0,
164 .wLength = 0,
165 };
166
167 /* Select the control pipe for the request transfer */
168 Pipe_SelectPipe(PIPE_CONTROLPIPE);
169
170 /* Send the request, display error and wait for device detach if request fails */
171 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
172 {
173 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
174 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
175
176 /* Indicate error via status LEDs */
177 UpdateStatus(Status_EnumerationError);
178
179 /* Wait until USB device disconnected */
180 while (USB_IsConnected);
181 break;
182 }
183
184 USB_HostState = HOST_STATE_Configured;
185 break;
186 case HOST_STATE_Configured:
187 puts_P(PSTR("Getting Config Data.\r\n"));
188
189 /* Get and process the configuration descriptor data */
190 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
191 {
192 if (ErrorCode == ControlError)
193 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
194 else
195 puts_P(PSTR("Invalid Device.\r\n"));
196
197 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
198
199 /* Indicate error via status LEDs */
200 UpdateStatus(Status_EnumerationError);
201
202 /* Wait until USB device disconnected */
203 while (USB_IsConnected);
204 break;
205 }
206
207 puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
208
209 USB_HostState = HOST_STATE_Ready;
210 break;
211 case HOST_STATE_Ready:
212 /* Indicate device busy via the status LEDs */
213 UpdateStatus(Status_Busy);
214
215 /* Send the request, display error and wait for device detach if request fails */
216 if ((ErrorCode = MassStore_GetMaxLUN(&MassStore_MaxLUNIndex)) != HOST_SENDCONTROL_Successful)
217 {
218 ShowDiskReadError(PSTR("Get Max LUN"), false, ErrorCode);
219 break;
220 }
221
222 /* Print number of LUNs detected in the attached device */
223 printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex + 1));
224
225 /* Reset the Mass Storage device interface, ready for use */
226 if ((ErrorCode = MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful)
227 {
228 ShowDiskReadError(PSTR("Mass Storage Reset"), false, ErrorCode);
229 break;
230 }
231
232 /* Get sense data from the device - many devices will not accept any other commands until the sense data
233 * is read - both on start-up and after a failed command */
234 SCSI_Request_Sense_Response_t SenseData;
235 if (((ErrorCode = MassStore_RequestSense(0, &SenseData)) != 0) || (SCSICommandStatus.Status != Command_Pass))
236 {
237 ShowDiskReadError(PSTR("Request Sense"), (SCSICommandStatus.Status != Command_Pass), ErrorCode);
238 break;
239 }
240
241 /* Set the prevent removal flag for the device, allowing it to be accessed */
242 if (((ErrorCode = MassStore_PreventAllowMediumRemoval(0, true)) != 0) || (SCSICommandStatus.Status != Command_Pass))
243 {
244 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), (SCSICommandStatus.Status != Command_Pass), ErrorCode);
245 break;
246 }
247
248 puts_P(PSTR("Waiting until ready.."));
249
250 /* Wait until disk ready */
251 do
252 {
253 Serial_TxByte('.');
254
255 if ((ErrorCode = MassStore_TestUnitReady(0)) != 0)
256 {
257 ShowDiskReadError(PSTR("Test Unit Ready"), false, ErrorCode);
258 break;
259 }
260 }
261 while ((SCSICommandStatus.Status != Command_Pass) && USB_IsConnected);
262
263 /* Abort if device removed */
264 if (!(USB_IsConnected))
265 break;
266
267 puts_P(PSTR("\r\nRetrieving Capacity... "));
268
269 /* Create new structure for the disk's capacity in blocks and block size */
270 SCSI_Capacity_t DiskCapacity;
271
272 /* Retrieve disk capacity */
273 if (((ErrorCode = MassStore_ReadCapacity(0, &DiskCapacity)) != 0) || (SCSICommandStatus.Status != Command_Pass))
274 {
275 ShowDiskReadError(PSTR("Read Capacity"), (SCSICommandStatus.Status != Command_Pass), ErrorCode);
276 break;
277 }
278
279 /* Display the disk capacity in blocks * block size bytes */
280 printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity.Blocks, DiskCapacity.BlockSize);
281
282 /* Create a new buffer capabable of holding a single block from the device */
283 uint8_t BlockBuffer[DiskCapacity.BlockSize];
284
285 /* Read in the first 512 byte block from the device */
286 if (((ErrorCode = MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0) ||
287 (SCSICommandStatus.Status != Command_Pass))
288 {
289 ShowDiskReadError(PSTR("Read Device Block"), (SCSICommandStatus.Status != Command_Pass), ErrorCode);
290 break;
291 }
292
293 puts_P(PSTR("\r\nContents of first block:\r\n"));
294
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++)
297 {
298 /* Pointer to the start of the current 16-byte chunk in the read block of data */
299 uint8_t* ChunkPtr = &BlockBuffer[Chunk << 4];
300
301 /* Print out the 16 bytes of the chunk in HEX format */
302 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
303 {
304 char CurrByte = *(ChunkPtr + ByteOffset);
305
306 printf_P(PSTR("%.2X "), CurrByte);
307 }
308
309 puts_P(PSTR(" "));
310
311 /* Print out the 16 bytes of the chunk in ASCII format */
312 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
313 {
314 char CurrByte = *(ChunkPtr + ByteOffset);
315
316 putchar(isprint(CurrByte) ? CurrByte : '.');
317 }
318
319 puts_P(PSTR("\r\n"));
320 }
321
322 puts_P(PSTR("\r\n\r\nPress board button to read entire ASCII contents of disk...\r\n\r\n"));
323
324 /* Wait for the board button to be pressed */
325 while (!(Buttons_GetStatus() & BUTTONS_BUTTON1))
326 {
327 /* Abort if device removed */
328 if (!(USB_IsConnected))
329 break;
330 }
331
332 /* Print out the entire disk contents in ASCII format */
333 for (uint32_t CurrBlock = 0; CurrBlock < DiskCapacity.Blocks; CurrBlock++)
334 {
335 /* Read in the next block of data from the device */
336 if (((ErrorCode = MassStore_ReadDeviceBlock(0, CurrBlock, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0) ||
337 (SCSICommandStatus.Status != Command_Pass))
338 {
339 ShowDiskReadError(PSTR("Read Device Block"), (SCSICommandStatus.Status != Command_Pass), ErrorCode);
340 break;
341 }
342
343 /* Send the ASCII data in the read in block to the serial port */
344 for (uint16_t Byte = 0; Byte < DiskCapacity.BlockSize; Byte++)
345 {
346 char CurrByte = BlockBuffer[Byte];
347
348 putchar(isprint(CurrByte) ? CurrByte : '.');
349 }
350
351 /* Abort if device removed */
352 if (!(USB_IsConnected))
353 break;
354 }
355
356 /* Indicate device no longer busy */
357 UpdateStatus(Status_USBReady);
358
359 /* Wait until USB device disconnected */
360 while (USB_IsConnected);
361
362 break;
363 }
364 }
365
366 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
367 * log to a serial port, or anything else that is suitable for status updates.
368 *
369 * \param CurrentStatus Current status of the system, from the MassStorageHost_StatusCodes_t enum
370 */
371 void UpdateStatus(uint8_t CurrentStatus)
372 {
373 uint8_t LEDMask = LEDS_NO_LEDS;
374
375 /* Set the LED mask to the appropriate LED mask based on the given status code */
376 switch (CurrentStatus)
377 {
378 case Status_USBNotReady:
379 LEDMask = (LEDS_LED1);
380 break;
381 case Status_USBEnumerating:
382 LEDMask = (LEDS_LED1 | LEDS_LED2);
383 break;
384 case Status_USBReady:
385 LEDMask = (LEDS_LED2);
386 break;
387 case Status_EnumerationError:
388 case Status_HardwareError:
389 case Status_SCSICommandError:
390 LEDMask = (LEDS_LED1 | LEDS_LED3);
391 break;
392 case Status_Busy:
393 LEDMask = (LEDS_LED1 | LEDS_LED4);
394 break;
395 }
396
397 /* Set the board LEDs to the new LED mask */
398 LEDs_SetAllLEDs(LEDMask);
399 }
400
401 /** Indicates that a communication error has occurred with the attached Mass Storage Device,
402 * printing error codes to the serial port and waiting until the device is removed before
403 * continuing.
404 *
405 * \param CommandString ASCII string located in PROGMEM space indicating what operation failed
406 * \param FailedAtSCSILayer Indicates if the command failed at the (logical) SCSI layer or at the physical USB layer
407 * \param ErrorCode Error code of the function which failed to complete successfully
408 */
409 void ShowDiskReadError(char* CommandString, bool FailedAtSCSILayer, uint8_t ErrorCode)
410 {
411 if (FailedAtSCSILayer)
412 {
413 /* Display the error code */
414 printf_P(PSTR(ESC_BG_RED "SCSI command error (%S).\r\n"), CommandString);
415 printf_P(PSTR(" -- Status Code: %d"), ErrorCode);
416 }
417 else
418 {
419 /* Display the error code */
420 printf_P(PSTR(ESC_BG_RED "Command error (%S).\r\n"), CommandString);
421 printf_P(PSTR(" -- Error Code: %d"), ErrorCode);
422 }
423
424 Pipe_Freeze();
425
426 /* Indicate device error via the status LEDs */
427 UpdateStatus(Status_SCSICommandError);
428
429 /* Wait until USB device disconnected */
430 while (USB_IsConnected);
431 }