Hi, maybe you can help me out here.
I am simply trying to write some data to a usb stick connected to the usb host port on my g80. I am using NETMF v 4.3.8.1. As a matter of fact, data gets only written to my device, when I unmount the drive. I came up with the following code, which unmounts my drive after writing my data and re-mounts it to recycle th whole process. Is this realy the way to do it as is seems a bit akward to permanently remount a drive when simply wanting to provide permanent write access throughout the the whole application lifecycle?
Thanks and best regards!
using GHI.Usb.Host;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;
using System.IO;
using System.Text;
using System.Threading;
namespace Altbrot.MPX2FRSKY.Manager
{
/// <summary>
/// Used to detect and write telemtrie to mass storage device
/// </summary>
public class MassStorageManager
{
private static MassStorage _usbStorage;
private static bool _shouldStop = false;
private static AutoResetEvent _evt = new AutoResetEvent(false);
/// <summary>
/// Initializes this instance.
/// </summary>
public static void Init()
{
RemovableMedia.Insert += new InsertEventHandler(RemovableMedia_Insert);
// Unlike SD Card detection, the USB Host Controller sends an
// event when a Mass Storage device is plugged-in.
Controller.MassStorageConnected += (sender, massStorage) =>
{
_usbStorage = massStorage;
Thread remountThread = new Thread(RemountThread);
remountThread.Start();
};
Controller.Start();
}
/// <summary>
/// Remounts the device.
/// </summary>
private static void RemountThread()
{
try
{
while (!_shouldStop)
{
_usbStorage.Mount();
_evt.Reset();
_evt.WaitOne();
Thread.Sleep(ConfigurationManager.AppSettings.Data.TelemtryWriteInterval);
}
}
catch { }
}
/// <summary>
/// Handles the Insert event of the RemovableMedia control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MediaEventArgs"/> instance containing the event data.</param>
static void RemovableMedia_Insert(object sender, MediaEventArgs e)
{
try
{
if (e.Volume.IsFormatted)
{
// write header first
if (!File.Exists(e.Volume.RootDirectory + @"\telemetrie.csv"))
{
using (var FileHandle = new FileStream(e.Volume.RootDirectory + @"\telemetrie.csv", FileMode.OpenOrCreate))
{
byte[] data = Encoding.UTF8.GetBytes("A1;A2;RssiUp;RssiDown");
FileHandle.Write(data, 0, data.Length);
FileHandle.Flush();
}
}
else
{
using (var FileHandle = new FileStream(e.Volume.RootDirectory + @"\telemetrie.csv", FileMode.Append))
{
byte[] data = Encoding.UTF8.GetBytes("\n" + FrskyManager.A1.ToString() + ";" + FrskyManager.A2.ToString() + ";" + FrskyManager.RssiUp.ToString() + ";" + FrskyManager.RssiDown.ToString() + ";");
FileHandle.Write(data, 0, data.Length);
FileHandle.Flush();
}
}
_usbStorage.Unmount();
_evt.Set();
}
}
catch { }
}
}
}