Error While trying to mount usb host

Hi I am using the following code to mount a usb host and read all files list from the usb memory :

void ProgramStarted()
{
// Subscribe to USBH events.
USBHostController.DeviceConnectedEvent += DeviceConnectedEvent;
USBHostController.DeviceDisconnectedEvent += DeviceDisconnectedEvent;

    }

    static void DeviceConnectedEvent(USBH_Device device)
    {
        Debug.Print("Device connected...");
        Debug.Print("ID: " + device.ID + ", Interface: " +
                 device.INTERFACE_INDEX + ", Type: " + device.TYPE);

        #region List All Files in root directory

        try
        {
            PersistentStorage sdPS = new PersistentStorage(device.ID.ToString());

            // Mount the file system
            sdPS.MountFileSystem();

            // Assume one storage device is available, access it through 
            // Micro Framework and display available files and folders:
            Debug.Print("Getting files and folders:");
            if (VolumeInfo.GetVolumes()[0].IsFormatted)
            {
                string rootDirectory =
                    VolumeInfo.GetVolumes()[0].RootDirectory;
                string[] files = Directory.GetFiles(rootDirectory);
                string[] folders = Directory.GetDirectories(rootDirectory);

                Debug.Print("Files available on " + rootDirectory + ":");
                for (int i = 0; i < files.Length; i++)
                    Debug.Print(files[i]);

                Debug.Print("Folders available on " + rootDirectory + ":");
                for (int i = 0; i < folders.Length; i++)
                    Debug.Print(folders[i]);
            }
            else
            {
                Debug.Print("Storage is not formatted. Format on PC with FAT32/FAT16 first.");
            }

            // Unmount
            sdPS.UnmountFileSystem();
        }
        catch (Exception ex)
        {
            if (ex != null)
            {
                Debug.Print(ex.InnerException.Message);
            }
            else
            {
                Debug.Print(ex.Message);
            }
        }

        #endregion
    }

    static void DeviceDisconnectedEvent(USBH_Device device)
    {
        Debug.Print("Device disconnected...");
        Debug.Print("ID: " + device.ID + ", Interface: " +
                 device.INTERFACE_INDEX + ", Type: " + device.TYPE);
    }

, but at the line :

PersistentStorage sdPS = new PersistentStorage(device.ID.ToString());

I get the following exception :

Device connected…
ID: 2694766804, Interface: 0, Type: 6
#### Exception System.InvalidOperationException - CLR_E_INVALID_OPERATION (4) ####
#### Message:
#### GHI.Premium.IO.PersistentStorage::PersistentStorage_Helper [IP: 0000] ####
#### GHI.Premium.IO.PersistentStorage::.ctor [IP: 0011] ####
#### USBHostExample.Program::DeviceConnectedEvent [IP: 0052] ####
#### GHI.Premium.USBHost.USBH_DeviceConnectionEventHandler::Invoke [IP: 0000] ####
#### GHI.Premium.USBHost.USBHostController::nativeEventDispatcher_OnInterrupt [IP: 0037] ####
#### GHI.Premium.System.InternalEvent::nativeEventDispatcher_OnInterrupt [IP: 0054] ####
A first chance exception of type ‘System.InvalidOperationException’ occurred in GHI.Premium.IO.dll
#### Exception System.NullReferenceException - CLR_E_NULL_REFERENCE (4) ####
#### Message:
#### USBHostExample.Program::DeviceConnectedEvent [IP: 0108] ####
#### GHI.Premium.USBHost.USBH_DeviceConnectionEventHandler::Invoke [IP: 0000] ####
#### GHI.Premium.USBHost.USBHostController::nativeEventDispatcher_OnInterrupt [IP: 0037] ####
#### GHI.Premium.System.InternalEvent::nativeEventDispatcher_OnInterrupt [IP: 0054] ####
A first chance exception of type ‘System.NullReferenceException’ occurred in USBHostExample.exe
An unhandled exception of type ‘System.NullReferenceException’ occurred in USBHostExample.exe

do you get a device id and device type info? Perhaps you need to validate you have what type you expect first?

@ Brett - Yes Brett , I get them all as follows :
ID: 2694766300, Interface: 0, Type: 6

…and what is the value from the enum USBH_DeviceType.MassStorage ? (I ask because I can’t find it)

There isn’t a good example here (@ Jeff@ GHI, can we get a Mass Storage example in USBHost https://www.ghielectronics.com/docs/36/usb-host).

I believe but can’t verify that you use “device” not device.ID.ToString() when you create your persistent storage object.


but you really need to wrap that whole section in a validation that the device is a Mass Storage device.

Device Type 6 is MassStorage.

When you use device not ID.ToString() the code you provided works, but on my test it throws an exception when the Device Connected handler exits because you attempt to unmount the file system. Removing that allows the handler to exit successfully.

I assume you have used the Gadgeteer designer to define the USB Host module.

Gadgeteer does things for you. You are unable to mount the USB device because it is has already been mounted by the USB Host Gadgeteer driver.

I suggest you look a the driver code for the UBS Host module to see what Gadgeteer is doing for you.

karamafrooz

Not sure if this is a suitable way to post but…

I had issues with using PersistentStorage but never followed up on finding out why.

I will post code that works on my Raptor that does not use PersistentStorage.

No expert here but the code worked for my use. I did have a issue with debugging but not with reading/writing folders/files to a USB Card reader that contains a 16 Gig SD (formatted using the Windows 8 formatter).

If you want I can send you the application in a zip for your testing.

YES, I realize that this does not answer your question about using PersistentStorage.

NOTE: No pro here so all I can say it works for me.


using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Presentation.Shapes;
using Microsoft.SPOT.Touch;

using Microsoft.SPOT.IO;
using System.IO;    //IO Stream Reader/Writer
using System.Xml;   //XML

using Gadgeteer;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;

using GHI.Premium.USBHost;
using GHI.Premium.System;

/* 
 My Raptor info:
 * 
  Loader (TinyBooter) version information: 
 4.2.11.1 on this computer.
 4.2.11.1 on this device.
 >>> The Loader (TinyBooter) is up to date. <<<
 

 Firmware (TinyCLR) version information: 
 4.2.11.1 on this computer.
 4.2.11.1 on this device.
 >>> The Firmware (TinyCLR) is up to date. <<<
 Please wait for the device to reboot... Done.
 */

// Using Windows 8.1 64-bit with latest updates available at this time.
// Using Microsoft Visual Studio Express 2012 for Desktop with all known updates.

// Using Windows 7 Home Premium 64-bit with all known updates
// Using Microsoft Visual Studio Express 2012 for Desktop with all known updates.

// My results are the same on either system used

/*
Microsoft Visual Studio Express 2012 for Windows Desktop
Version 11.0.60610.01 Update 3
Microsoft .NET Framework
Version 4.5.51641

Installed Version: Desktop Express

Team Explorer for Visual Studio 2012   05695-004-0030004-02248
Microsoft Team Explorer for Visual Studio 2012

Visual Basic 2012   05695-004-0030004-02248
Microsoft Visual Basic 2012

Visual C# 2012   05695-004-0030004-02248
Microsoft Visual C# 2012

Visual C++ 2012   05695-004-0030004-02248
Microsoft Visual C++ 2012

Microsoft .NET Micro Framework v4.3   
Microsoft .NET Micro Framework SDK v4.3
Version 4.3.0.0

NuGet Package Manager   2.7.41101.299
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http: //docs.nuget.org/.

SQL Server Data Tools   11.1.20828.01
Microsoft SQL Server Data Tools
*/


//Some 'borrowed' code use in  here (obtained from codeshare)
namespace USBHostTest
{
    public partial class Program
    {
        static Display_T35 display;

        static Font fontSmall;
        static Font fontLarge;

        static bool usbHostAvailable = false;
        public static string fileText = "This is a test string for reading and writing to media";

        // This method is run when the mainboard is powered up or reset.   
        void ProgramStarted()
        {
            display = display_T35;

            fontSmall = Resources.GetFont(Resources.FontResources.small);
            fontLarge = Resources.GetFont(Resources.FontResources.NinaB);

            //The usbHost.USBDriveConnected event is received if media is inserted
            usbHost.USBDriveConnected += new UsbHost.USBDriveConnectedEventHandler(usbHost_USBDriveConnected);
            usbHost.USBDriveDisconnected += new UsbHost.USBDriveDisconnectedEventHandler(usbHost_USBDriveDisconnected);

            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");

            display_T35.SimpleGraphics.BackgroundColor = Colors.LightGray;
            display_T35.SimpleGraphics.DisplayText("Program is running", fontLarge, Colors.Black, 10, 10);
        }
        //

        #region USBHost events
        //Save for further use
        private static GT.StorageDevice savedUSBDrive = null;
        private static VolumeInfo savedVolInfo = null;
        

        //I am using a USB Card reader that contains a 16 Gig SD (formatted using the Windows 8 formatter)

        //This event is received on application start if media is present (And whenever media is inserted)
        static void usbHost_USBDriveConnected(UsbHost sender, GT.StorageDevice USBDrive)
        {
            //Assuming that it is a Flash device or SD to USB card reader
            usbHostAvailable = true;

            display.SimpleGraphics.DisplayText("USB Host Device Connected - Volume: " + USBDrive.Volume.Name, fontLarge, Colors.Black, 10, 30);
            //Debug.Print("USB Host connect event: Device Is Connected - Volume: " + USBDrive.Volume.Name);
            savedUSBDrive = USBDrive;
            savedVolInfo = USBDrive.Volume;

            //Blue LED on the Raptor mainboard
            //Turn ON to notify that a storage device was found
            Program.Mainboard.SetDebugLED(true);

            //******************************************************************
            //Set a breakpoint on the following bool and use: Restart Ctrl+Shift+F5
            //Debugging will work up to this point
            bool stopHereDebuggingOK = true;
            //******************************************************************

            //From this point on a 'reset' of the Raptor is needed to restart the application

            //Creat some Directories(Folders)
            try
            {
                Thread.Sleep(1000);
                USBDrive.CreateDirectory("\\CalStrings");
                Debug.Print("Created Directory: " + "\\CalStrings");
            }
            catch (Exception err)
            {
                Debug.Print("Failed to create \\CalStrings : " + err.Message);
                return;
            }
            //

            //******************************************************************
            //Set a breakpoint on the following bool and use Restart Ctrl+Shift+F5
            //Debugging fails here (After writing to storage device)
            bool stopHereDebuggingFails = true;
            //******************************************************************

            //All files are made as intended
            try
            {
                Thread.Sleep(1000);
                USBDrive.CreateDirectory("\\CalXML");
                Debug.Print("Created Directory: " + "\\CalXML");
            }
            catch (Exception err)
            {
                Debug.Print("Failed to create \\CalXML : " + err.Message);
                return;
            }
            //

            string[] ListDirectories = USBDrive.ListDirectories("\\");
            string listdirectories = string.Empty;
            foreach (string dir in ListDirectories)
            {
                listdirectories += ("\t" + dir + "\r\n");
            }
            Debug.Print("Root Directories:\r\n" + listdirectories);
            //

            string[] RootDirectoryFiles = USBDrive.ListRootDirectoryFiles();
            string rootfiles = string.Empty;
            foreach (string files in RootDirectoryFiles)
            {
                FileInfo Fileinfo = new FileInfo(USBDrive.RootDirectory + "\\" + files);
                rootfiles += (new string(' ', USBDrive.RootDirectory.Length) +
                    files + " size: " + rootfiles.Length + " bytes\r\n");
            }
            Debug.Print("Root Files:\r\n" + rootfiles);
            //

            if (usbHostAvailable)
            {
                //Want bytes?
                string TextContent = String.Empty;

                //TextContent = "160,32,32,288,288";

                TextContent =
                    "<?xml version=\"1.0\"?>\r\n<calib>\r\n\t<sx>thesxvalue</sx>\r\n\t<sy>thesyvalue</sy>\r\n\t<cx>thecxvalue</cx>\r\n\t<cy>thecyvalue</cy>\r\n</calib>";
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(TextContent);

                try
                {
                    USBDrive.WriteFile(@ "testCalFile.xml", bytes);
                }
                catch (Exception err)
                {
                    Debug.Print(err.ToString());
                    return;
                }
                
                Debug.Print("Wrote: testCalFile.xml to USB");

                try
                {
                    //Use wrong file name
                    byte[] fileHandle = USBDrive.ReadFile(@ "testCalFile.xml");
                    if (!(readXMLVal(fileHandle, "sx") == null))
                    {
                        string valuereturned = readXMLVal(fileHandle, "sx");
                        Debug.Print("Value sx from XML file found: " + valuereturned);
                    }
                    //
                    if (!(readXMLVal(fileHandle, "sy") == null))
                    {
                        string valuereturned = readXMLVal(fileHandle, "sy");
                        Debug.Print("Value sy from XML file found: " + valuereturned);
                    }
                    //
                    if (!(readXMLVal(fileHandle, "cx") == null))
                    {
                        string valuereturned = readXMLVal(fileHandle, "cx");
                        Debug.Print("Value cx from XML file found: " + valuereturned);
                    }
                    //
                    if (!(readXMLVal(fileHandle, "cy") == null))
                    {
                        string valuereturned = readXMLVal(fileHandle, "cy");
                        Debug.Print("Value cy from XML file found: " + valuereturned);
                    }
                    //

                }
                catch (Exception err)
                {
                    Debug.Print(err.ToString());
                    return;
                }
                //
                Debug.Print("Program tasks completed");
                display.SimpleGraphics.DisplayText("Program tasks completed", fontLarge, Colors.Black, 10, 200);
            }
        }
        //

        //This event is not received on application start
        static void usbHost_USBDriveDisconnected(UsbHost sender)
        {
            usbHostAvailable = false;
            Debug.Print("Media was removed");
            Program.Mainboard.SetDebugLED(false); //OFF
        }
        //
        #endregion USBHost events


        static StreamWriter GetFileStream(string filename)
        {
            StreamWriter Stream = null;
            try
            {
                Stream = new StreamWriter(filename);
            }
            catch (Exception err)
            {
                Debug.Print("StreamWriter Failed: " + filename);
                Debug.Print("Msg: " + err.Message);
            }
            return Stream;
        }
        //


        //Uses the string fileText (Contains text to write to FileName)
        static Boolean WriteTextFile(string FileName)
        {
            StreamWriter Stream = GetFileStream(FileName);
            if (null == Stream)
            {
                return false;
            }
            try
            {
                Stream.Write(fileText);
            }
            catch (Exception error)
            {
                Stream.Close();
                Debug.Print("Failed to write " + FileName);
                Debug.Print(error.Message);
                return false;
            }
            Stream.Close();
            Debug.Print("Write sucessful: " + FileName);
            return true;
        }
        //

        //Cycle through XML and find/return string readValue
        static string readXMLVal(byte[] xmlData, string readValue)
        {
            Stream configStream = new MemoryStream(xmlData);

            XmlReader configFileXML = XmlReader.Create(configStream);

            while (!configFileXML.EOF)
            {
                while (configFileXML.NodeType != XmlNodeType.EndElement)
                {
                    //Continue looking
                    configFileXML.Read();

                    //Check if the <Name> is what we are looking for ( <Name>Value</Name> )
                    if (configFileXML.Name.ToLower() == readValue.ToLower())
                    {
                        //Continue if there is no Value
                        while (configFileXML.NodeType != XmlNodeType.EndElement)
                        {
                            //Continue looking
                            configFileXML.Read();

                            //Continue only if there is a Text node
                            if (configFileXML.NodeType == XmlNodeType.Text)
                            {
                                //Value was found so return it
                                return configFileXML.Value;
                            }
                        }
                        //Continue looking
                        configFileXML.Read();
                    }
                }
                //Continue looking
                configFileXML.Read();
            }
            return null; //Return null if nothing found
        }
        //

    }
}


Hope it helps

The image files show the errors with debugging but as I said, it did not cause any problems that I know of except for debug (I posted a issue on this)

Happy Holidays!