Fixed minor issue with the RNDISEthernet demo DHCP protocol decoder routine using...
[pub/USBasp.git] / Demos / Host / 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 /* 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);
44
45 /* Scheduler Task List */
46 TASK_LIST
47 {
48 { Task: USB_USBTask , TaskStatus: TASK_STOP },
49 { Task: USB_MassStore_Host , TaskStatus: TASK_STOP },
50 };
51
52 /* Globals */
53 /** Index of the highest available LUN (Logical Unit) in the attached Mass Storage Device */
54 uint8_t MassStore_MaxLUNIndex;
55
56
57 /** Main program entry point. This routine configures the hardware required by the application, then
58 * starts the scheduler to run the application tasks.
59 */
60 int main(void)
61 {
62 /* Disable watchdog if enabled by bootloader/fuses */
63 MCUSR &= ~(1 << WDRF);
64 wdt_disable();
65
66 /* Disable clock division */
67 clock_prescale_set(clock_div_1);
68
69 /* Hardware Initialization */
70 SerialStream_Init(9600, false);
71 LEDs_Init();
72 HWB_Init();
73
74 /* Indicate USB not ready */
75 UpdateStatus(Status_USBNotReady);
76
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));
80
81 /* Initialize Scheduler so that it can be used */
82 Scheduler_Init();
83
84 /* Initialize USB Subsystem */
85 USB_Init();
86
87 /* Scheduling routine never returns, so put this last in the main function */
88 Scheduler_Start();
89 }
90
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.
93 */
94 EVENT_HANDLER(USB_DeviceAttached)
95 {
96 puts_P(PSTR("Device Attached.\r\n"));
97 UpdateStatus(Status_USBEnumerating);
98
99 /* Start USB management task to enumerate the device */
100 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
101 }
102
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.
105 */
106 EVENT_HANDLER(USB_DeviceUnattached)
107 {
108 /* Stop USB management and Mass Storage tasks */
109 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
110 Scheduler_SetTaskMode(USB_MassStore_Host, TASK_STOP);
111
112 puts_P(PSTR("\r\nDevice Unattached.\r\n"));
113 UpdateStatus(Status_USBNotReady);
114 }
115
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.
118 */
119 EVENT_HANDLER(USB_DeviceEnumerationComplete)
120 {
121 /* Once device is fully enumerated, start the Mass Storage Host task */
122 Scheduler_SetTaskMode(USB_MassStore_Host, TASK_RUN);
123
124 /* Indicate device enumeration complete */
125 UpdateStatus(Status_USBReady);
126 }
127
128 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
129 EVENT_HANDLER(USB_HostError)
130 {
131 USB_ShutDown();
132
133 puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
134 printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
135
136 UpdateStatus(Status_HardwareError);
137 for(;;);
138 }
139
140 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
141 * enumerating an attached USB device.
142 */
143 EVENT_HANDLER(USB_DeviceEnumerationFailed)
144 {
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);
149
150 UpdateStatus(Status_EnumerationError);
151 }
152
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.
155 */
156 TASK(USB_MassStore_Host)
157 {
158 uint8_t ErrorCode;
159
160 switch (USB_HostState)
161 {
162 case HOST_STATE_Addressed:
163 /* Standard request to set the device configuration to configuration 1 */
164 USB_HostRequest = (USB_Host_Request_Header_t)
165 {
166 bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
167 bRequest: REQ_SetConfiguration,
168 wValue: 1,
169 wIndex: 0,
170 wLength: 0,
171 };
172
173 /* Select the control pipe for the request transfer */
174 Pipe_SelectPipe(PIPE_CONTROLPIPE);
175
176 /* Send the request, display error and wait for device detach if request fails */
177 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
178 {
179 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
180 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
181
182 /* Indicate error via status LEDs */
183 UpdateStatus(Status_EnumerationError);
184
185 /* Wait until USB device disconnected */
186 while (USB_IsConnected);
187 break;
188 }
189
190 USB_HostState = HOST_STATE_Configured;
191 break;
192 case HOST_STATE_Configured:
193 puts_P(PSTR("Getting Config Data.\r\n"));
194
195 /* Get and process the configuration descriptor data */
196 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
197 {
198 if (ErrorCode == ControlError)
199 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
200 else
201 puts_P(PSTR("Invalid Device.\r\n"));
202
203 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
204
205 /* Indicate error via status LEDs */
206 UpdateStatus(Status_EnumerationError);
207
208 /* Wait until USB device disconnected */
209 while (USB_IsConnected);
210 break;
211 }
212
213 puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
214
215 USB_HostState = HOST_STATE_Ready;
216 break;
217 case HOST_STATE_Ready:
218 /* Indicate device busy via the status LEDs */
219 UpdateStatus(Status_Busy);
220
221 /* Reset the Mass Storage device interface, ready for use */
222 if ((ErrorCode = MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful)
223 {
224 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode);
225 break;
226 }
227
228 /* Send the request, display error and wait for device detach if request fails */
229 if ((ErrorCode = MassStore_GetMaxLUN(&MassStore_MaxLUNIndex)) != HOST_SENDCONTROL_Successful)
230 {
231 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode);
232 break;
233 }
234
235 /* Print number of LUNs detected in the attached device */
236 printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex + 1));
237
238 /* Set the prevent removal flag for the device, allowing it to be accessed */
239 if ((ErrorCode = MassStore_PreventAllowMediumRemoval(0, true)) != 0)
240 {
241 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode);
242 break;
243 }
244
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)
249 {
250 ShowDiskReadError(PSTR("Request Sense"), ErrorCode);
251 break;
252 }
253
254 puts_P(PSTR("Waiting until ready"));
255
256 /* Wait until disk ready */
257 do
258 {
259 Serial_TxByte('.');
260 MassStore_TestUnitReady(0);
261 }
262 while ((SCSICommandStatus.Status != Command_Pass) && USB_IsConnected);
263
264 /* Abort if device removed */
265 if (!(USB_IsConnected))
266 break;
267
268 puts_P(PSTR("\r\nRetrieving Capacity... "));
269
270 /* Create new structure for the disk's capacity in blocks and block size */
271 SCSI_Capacity_t DiskCapacity;
272
273 /* Retrieve disk capacity */
274 if ((ErrorCode = MassStore_ReadCapacity(0, &DiskCapacity)) != 0)
275 {
276 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode);
277 break;
278 }
279
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);
282
283 /* Create a new buffer capabable of holding a single block from the device */
284 uint8_t BlockBuffer[DiskCapacity.BlockSize];
285
286 /* Read in the first 512 byte block from the device */
287 if ((ErrorCode = MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
288 {
289 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
290 break;
291 }
292
293 /* Show the number of bytes not transferred in the previous command */
294 printf_P(PSTR("Transfer Residue: %lu\r\n"), SCSICommandStatus.DataTransferResidue);
295
296 puts_P(PSTR("\r\nContents of first block:\r\n"));
297
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++)
300 {
301 /* Pointer to the start of the current 16-byte chunk in the read block of data */
302 uint8_t* ChunkPtr = &BlockBuffer[Chunk << 4];
303
304 /* Print out the 16 bytes of the chunk in HEX format */
305 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
306 {
307 char CurrByte = *(ChunkPtr + ByteOffset);
308
309 printf_P(PSTR("%.2X "), CurrByte);
310 }
311
312 puts_P(PSTR(" "));
313
314 /* Print out the 16 bytes of the chunk in ASCII format */
315 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
316 {
317 char CurrByte = *(ChunkPtr + ByteOffset);
318
319 putchar(isprint(CurrByte) ? CurrByte : '.');
320 }
321
322 puts_P(PSTR("\r\n"));
323 }
324
325 puts_P(PSTR("\r\n\r\nPress HWB to read entire ASCII contents of disk...\r\n\r\n"));
326
327 /* Wait for HWB to be pressed */
328 while (!(HWB_GetStatus()))
329 {
330 /* Abort if device removed */
331 if (!(USB_IsConnected))
332 break;
333 }
334
335 /* Print out the entire disk contents in ASCII format */
336 for (uint32_t CurrBlock = 0; CurrBlock < DiskCapacity.Blocks; CurrBlock++)
337 {
338 /* Read in the next block of data from the device */
339 if ((ErrorCode = MassStore_ReadDeviceBlock(0, CurrBlock, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
340 {
341 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
342 break;
343 }
344
345 /* Send the ASCII data in the read in block to the serial port */
346 for (uint16_t Byte = 0; Byte < DiskCapacity.BlockSize; Byte++)
347 {
348 char CurrByte = BlockBuffer[Byte];
349
350 putchar(isprint(CurrByte) ? CurrByte : '.');
351 }
352
353 /* Abort if device removed */
354 if (!(USB_IsConnected))
355 break;
356 }
357
358 /* Indicate device no longer busy */
359 UpdateStatus(Status_USBReady);
360
361 /* Wait until USB device disconnected */
362 while (USB_IsConnected);
363
364 break;
365 }
366 }
367
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.
370 *
371 * \param CurrentStatus Current status of the system, from the MassStorageHost_StatusCodes_t enum
372 */
373 void UpdateStatus(uint8_t CurrentStatus)
374 {
375 uint8_t LEDMask = LEDS_NO_LEDS;
376
377 /* Set the LED mask to the appropriate LED mask based on the given status code */
378 switch (CurrentStatus)
379 {
380 case Status_USBNotReady:
381 LEDMask = (LEDS_LED1);
382 break;
383 case Status_USBEnumerating:
384 LEDMask = (LEDS_LED1 | LEDS_LED2);
385 break;
386 case Status_USBReady:
387 LEDMask = (LEDS_LED2);
388 break;
389 case Status_EnumerationError:
390 case Status_HardwareError:
391 case Status_SCSICommandError:
392 LEDMask = (LEDS_LED1 | LEDS_LED3);
393 break;
394 case Status_Busy:
395 LEDMask = (LEDS_LED1 | LEDS_LED4);
396 break;
397 }
398
399 /* Set the board LEDs to the new LED mask */
400 LEDs_SetAllLEDs(LEDMask);
401 }
402
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
405 * continuing.
406 *
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
409 */
410 void ShowDiskReadError(char* CommandString, uint8_t ErrorCode)
411 {
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);
415
416 Pipe_Freeze();
417
418 /* Indicate device error via the status LEDs */
419 UpdateStatus(Status_SCSICommandError);
420
421 /* Wait until USB device disconnected */
422 while (USB_IsConnected);
423 }