Endpoint configuration is now refined to give better output when all configurations...
[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 /* 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 HWB_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 EVENT_HANDLER(USB_DeviceAttached)
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 EVENT_HANDLER(USB_DeviceUnattached)
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 EVENT_HANDLER(USB_DeviceEnumerationComplete)
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 EVENT_HANDLER(USB_HostError)
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 EVENT_HANDLER(USB_DeviceEnumerationFailed)
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 /* Reset the Mass Storage device interface, ready for use */
216 if ((ErrorCode = MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful)
217 {
218 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode);
219 break;
220 }
221
222 /* Send the request, display error and wait for device detach if request fails */
223 if ((ErrorCode = MassStore_GetMaxLUN(&MassStore_MaxLUNIndex)) != HOST_SENDCONTROL_Successful)
224 {
225 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode);
226 break;
227 }
228
229 /* Print number of LUNs detected in the attached device */
230 printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex + 1));
231
232 /* Set the prevent removal flag for the device, allowing it to be accessed */
233 if ((ErrorCode = MassStore_PreventAllowMediumRemoval(0, true)) != 0)
234 {
235 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode);
236 break;
237 }
238
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)
243 {
244 ShowDiskReadError(PSTR("Request Sense"), 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 MassStore_TestUnitReady(0);
255 }
256 while ((SCSICommandStatus.Status != Command_Pass) && USB_IsConnected);
257
258 /* Abort if device removed */
259 if (!(USB_IsConnected))
260 break;
261
262 puts_P(PSTR("\r\nRetrieving Capacity... "));
263
264 /* Create new structure for the disk's capacity in blocks and block size */
265 SCSI_Capacity_t DiskCapacity;
266
267 /* Retrieve disk capacity */
268 if ((ErrorCode = MassStore_ReadCapacity(0, &DiskCapacity)) != 0)
269 {
270 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode);
271 break;
272 }
273
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);
276
277 /* Create a new buffer capabable of holding a single block from the device */
278 uint8_t BlockBuffer[DiskCapacity.BlockSize];
279
280 /* Read in the first 512 byte block from the device */
281 if ((ErrorCode = MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
282 {
283 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
284 break;
285 }
286
287 /* Show the number of bytes not transferred in the previous command */
288 printf_P(PSTR("Transfer Residue: %lu\r\n"), SCSICommandStatus.DataTransferResidue);
289
290 puts_P(PSTR("\r\nContents of first block:\r\n"));
291
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++)
294 {
295 /* Pointer to the start of the current 16-byte chunk in the read block of data */
296 uint8_t* ChunkPtr = &BlockBuffer[Chunk << 4];
297
298 /* Print out the 16 bytes of the chunk in HEX format */
299 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
300 {
301 char CurrByte = *(ChunkPtr + ByteOffset);
302
303 printf_P(PSTR("%.2X "), CurrByte);
304 }
305
306 puts_P(PSTR(" "));
307
308 /* Print out the 16 bytes of the chunk in ASCII format */
309 for (uint8_t ByteOffset = 0; ByteOffset < (1 << 4); ByteOffset++)
310 {
311 char CurrByte = *(ChunkPtr + ByteOffset);
312
313 putchar(isprint(CurrByte) ? CurrByte : '.');
314 }
315
316 puts_P(PSTR("\r\n"));
317 }
318
319 puts_P(PSTR("\r\n\r\nPress HWB to read entire ASCII contents of disk...\r\n\r\n"));
320
321 /* Wait for HWB to be pressed */
322 while (!(HWB_GetStatus()))
323 {
324 /* Abort if device removed */
325 if (!(USB_IsConnected))
326 break;
327 }
328
329 /* Print out the entire disk contents in ASCII format */
330 for (uint32_t CurrBlock = 0; CurrBlock < DiskCapacity.Blocks; CurrBlock++)
331 {
332 /* Read in the next block of data from the device */
333 if ((ErrorCode = MassStore_ReadDeviceBlock(0, CurrBlock, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
334 {
335 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
336 break;
337 }
338
339 /* Send the ASCII data in the read in block to the serial port */
340 for (uint16_t Byte = 0; Byte < DiskCapacity.BlockSize; Byte++)
341 {
342 char CurrByte = BlockBuffer[Byte];
343
344 putchar(isprint(CurrByte) ? CurrByte : '.');
345 }
346
347 /* Abort if device removed */
348 if (!(USB_IsConnected))
349 break;
350 }
351
352 /* Indicate device no longer busy */
353 UpdateStatus(Status_USBReady);
354
355 /* Wait until USB device disconnected */
356 while (USB_IsConnected);
357
358 break;
359 }
360 }
361
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.
364 *
365 * \param CurrentStatus Current status of the system, from the MassStorageHost_StatusCodes_t enum
366 */
367 void UpdateStatus(uint8_t CurrentStatus)
368 {
369 uint8_t LEDMask = LEDS_NO_LEDS;
370
371 /* Set the LED mask to the appropriate LED mask based on the given status code */
372 switch (CurrentStatus)
373 {
374 case Status_USBNotReady:
375 LEDMask = (LEDS_LED1);
376 break;
377 case Status_USBEnumerating:
378 LEDMask = (LEDS_LED1 | LEDS_LED2);
379 break;
380 case Status_USBReady:
381 LEDMask = (LEDS_LED2);
382 break;
383 case Status_EnumerationError:
384 case Status_HardwareError:
385 case Status_SCSICommandError:
386 LEDMask = (LEDS_LED1 | LEDS_LED3);
387 break;
388 case Status_Busy:
389 LEDMask = (LEDS_LED1 | LEDS_LED4);
390 break;
391 }
392
393 /* Set the board LEDs to the new LED mask */
394 LEDs_SetAllLEDs(LEDMask);
395 }
396
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
399 * continuing.
400 *
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
403 */
404 void ShowDiskReadError(char* CommandString, uint8_t ErrorCode)
405 {
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);
409
410 Pipe_Freeze();
411
412 /* Indicate device error via the status LEDs */
413 UpdateStatus(Status_SCSICommandError);
414
415 /* Wait until USB device disconnected */
416 while (USB_IsConnected);
417 }