Fixed interrupt driven HID device demos not clearing the interrupt flags in all circu...
[pub/USBasp.git] / Demos / 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 SetSystemClockPrescaler(0);
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 /* Startup 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 occured 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 /* Send the request, display error and wait for device detatch if request fails */
174 if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
175 {
176 puts_P(PSTR("Control Error (Set Configuration).\r\n"));
177 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
178
179 /* Indicate error via status LEDs */
180 UpdateStatus(Status_EnumerationError);
181
182 /* Wait until USB device disconnected */
183 while (USB_IsConnected);
184 break;
185 }
186
187 USB_HostState = HOST_STATE_Configured;
188 break;
189 case HOST_STATE_Configured:
190 puts_P(PSTR("Getting Config Data.\r\n"));
191
192 /* Get and process the configuration descriptor data */
193 if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
194 {
195 if (ErrorCode == ControlError)
196 puts_P(PSTR("Control Error (Get Configuration).\r\n"));
197 else
198 puts_P(PSTR("Invalid Device.\r\n"));
199
200 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
201
202 /* Indicate error via status LEDs */
203 UpdateStatus(Status_EnumerationError);
204
205 /* Wait until USB device disconnected */
206 while (USB_IsConnected);
207 break;
208 }
209
210 puts_P(PSTR("Mass Storage Disk Enumerated.\r\n"));
211
212 USB_HostState = HOST_STATE_Ready;
213 break;
214 case HOST_STATE_Ready:
215 /* Indicate device busy via the status LEDs */
216 UpdateStatus(Status_Busy);
217
218 /* Reset the Mass Storage device interface, ready for use */
219 if ((ErrorCode = MassStore_MassStorageReset()) != HOST_SENDCONTROL_Successful)
220 {
221 ShowDiskReadError(PSTR("Mass Storage Reset"), ErrorCode);
222 break;
223 }
224
225 /* Send the request, display error and wait for device detatch if request fails */
226 if ((ErrorCode = MassStore_GetMaxLUN(&MassStore_MaxLUNIndex)) != HOST_SENDCONTROL_Successful)
227 {
228 ShowDiskReadError(PSTR("Get Max LUN"), ErrorCode);
229 break;
230 }
231
232 /* Print number of LUNs detected in the attached device */
233 printf_P(PSTR("Total LUNs: %d.\r\n"), (MassStore_MaxLUNIndex + 1));
234
235 /* Set the prevent removal flag for the device, allowing it to be accessed */
236 if ((ErrorCode = MassStore_PreventAllowMediumRemoval(0, true)) != 0)
237 {
238 ShowDiskReadError(PSTR("Prevent/Allow Medium Removal"), ErrorCode);
239 break;
240 }
241
242 /* Get sense data from the device - many devices will not accept any other commands until the sense data
243 * is read - both on startup and after a failed command */
244 SCSI_Request_Sense_Response_t SenseData;
245 if ((ErrorCode = MassStore_RequestSense(0, &SenseData)) != 0)
246 {
247 ShowDiskReadError(PSTR("Request Sense"), ErrorCode);
248 break;
249 }
250
251 puts_P(PSTR("Waiting until ready"));
252
253 /* Wait until disk ready */
254 do
255 {
256 Serial_TxByte('.');
257 MassStore_TestUnitReady(0);
258 }
259 while ((SCSICommandStatus.Status != Command_Pass) && USB_IsConnected);
260
261 /* Abort if device removed */
262 if (!(USB_IsConnected))
263 break;
264
265 puts_P(PSTR("\r\nRetrieving Capacity... "));
266
267 /* Create new structure for the disk's capacity in blocks and block size */
268 SCSI_Capacity_t DiskCapacity;
269
270 /* Retrieve disk capacity */
271 if ((ErrorCode = MassStore_ReadCapacity(0, &DiskCapacity)) != 0)
272 {
273 ShowDiskReadError(PSTR("Read Capacity"), ErrorCode);
274 break;
275 }
276
277 /* Display the disk capacity in blocks * block size bytes */
278 printf_P(PSTR("%lu blocks of %lu bytes.\r\n"), DiskCapacity.Blocks, DiskCapacity.BlockSize);
279
280 /* Create a new buffer capabable of holding a single block from the device */
281 uint8_t BlockBuffer[DiskCapacity.BlockSize];
282
283 /* Read in the first 512 byte block from the device */
284 if ((ErrorCode = MassStore_ReadDeviceBlock(0, 0x00000000, 1, DiskCapacity.BlockSize, BlockBuffer)) != 0)
285 {
286 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
287 break;
288 }
289
290 /* Show the number of bytes not transferred in the previous command */
291 printf_P(PSTR("Transfer Residue: %lu\r\n"), SCSICommandStatus.DataTransferResidue);
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 HWB to read entire ASCII contents of disk...\r\n\r\n"));
323
324 /* Wait for HWB to be pressed */
325 while (!(HWB_GetStatus()))
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 {
338 ShowDiskReadError(PSTR("Read Device Block"), ErrorCode);
339 break;
340 }
341
342 /* Send the ASCII data in the read in block to the serial port */
343 for (uint16_t Byte = 0; Byte < DiskCapacity.BlockSize; Byte++)
344 {
345 char CurrByte = BlockBuffer[Byte];
346
347 putchar(isprint(CurrByte) ? CurrByte : '.');
348 }
349
350 /* Abort if device removed */
351 if (!(USB_IsConnected))
352 break;
353 }
354
355 /* Indicate device no longer busy */
356 UpdateStatus(Status_USBReady);
357
358 /* Wait until USB device disconnected */
359 while (USB_IsConnected);
360
361 break;
362 }
363 }
364
365 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
366 * log to a serial port, or anything else that is suitable for status updates.
367 *
368 * \param CurrentStatus Current status of the system, from the MassStorageHost_StatusCodes_t enum
369 */
370 void UpdateStatus(uint8_t CurrentStatus)
371 {
372 uint8_t LEDMask = LEDS_NO_LEDS;
373
374 /* Set the LED mask to the appropriate LED mask based on the given status code */
375 switch (CurrentStatus)
376 {
377 case Status_USBNotReady:
378 LEDMask = (LEDS_LED1);
379 break;
380 case Status_USBEnumerating:
381 LEDMask = (LEDS_LED1 | LEDS_LED2);
382 break;
383 case Status_USBReady:
384 LEDMask = (LEDS_LED2);
385 break;
386 case Status_EnumerationError:
387 case Status_HardwareError:
388 case Status_SCSICommandError:
389 LEDMask = (LEDS_LED1 | LEDS_LED3);
390 break;
391 case Status_Busy:
392 LEDMask = (LEDS_LED1 | LEDS_LED4);
393 break;
394 }
395
396 /* Set the board LEDs to the new LED mask */
397 LEDs_SetAllLEDs(LEDMask);
398 }
399
400 /** Indicates that a communication error has ocurred with the attached Mass Storage Device,
401 * printing error codes to the serial port and waiting until the device is removed before
402 * continuing.
403 *
404 * \param CommandString ASCII string located in PROGMEM space indicating what operation failed
405 * \param ErrorCode Error code of the function which failed to complete successfully
406 */
407 void ShowDiskReadError(char* CommandString, uint8_t ErrorCode)
408 {
409 /* Display the error code */
410 printf_P(PSTR(ESC_BG_RED "Command error (%S).\r\n"), CommandString);
411 printf_P(PSTR(" -- Error Code: %d"), ErrorCode);
412
413 Pipe_Freeze();
414
415 /* Indicate device error via the status LEDs */
416 UpdateStatus(Status_SCSICommandError);
417
418 /* Wait until USB device disconnected */
419 while (USB_IsConnected);
420 }