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