Pages

Tuesday, July 29, 2014

FTDI device monitor

As usual I want to describe one of the last things I've done. Yeah I have not written anything to the blog for a while but thats not because I have not done anything but because I am planing something new!

Still, for now I want to describe how to get the list of connected USB devices using FTDI drivers. It is quite easy. Everything is done through the FTDI class.
First of all - you can check the number of connected devices with a call:

var monitor = new FTDI();
UInt32 newDeviceCount = 0;
var status = monitor.GetNumberOfDevices(ref newDeviceCount);
if (status != FTDI.FT_STATUS.FT_OK) //something wrong!

The last check is there just for exceptions. Then you can get the actual list of connected devices. As this library follows c++ style - you have to pass an initialized array of FT_DEVICE_INFO_NODE:

var ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[newDeviceCount];
ftStatus = newDevice.GetDeviceList(ftdiDeviceList);
if (ftStatus != FTDI.FT_STATUS.FT_OK) //something wrong!

And finally we can iterate through devices and get some information about them:

for (var i = 0; i < newDeviceCount; i++)
{
    _devices.Add(new DeviceDTO(i, //_devices here is a List of a simple DTO class
    ftdiDeviceList[i].Flags,
    ftdiDeviceList[i].Type,
    ftdiDeviceList[i].ID,
    ftdiDeviceList[i].LocId,
    ftdiDeviceList[i].SerialNumber,
    ftdiDeviceList[i].Description));
}

And thats all! As a side node - for my app I had to implement this as a infinite loop - watching for a new connections. It was something like this:

 var deviceFinder = new BackgroundWorker();
 deviceFinder.DoWork += (ev, sn) =>
 {
    UInt32 prevDeviceCount = 0;
    var monitor = new FTDI();

    while (true)
    {
        UInt32 newDeviceCount = 0;
        var status = monitor.GetNumberOfDevices(ref newDeviceCount);
        if (status != FTDI.FT_STATUS.FT_OK) continue;

        var dDevice = newDeviceCount - prevDeviceCount;
        if (dDevice != 0)
        {
            UpdateList(); //updates that _devices List
        }

        prevDeviceCount = newDeviceCount;

        Thread.Sleep(5000);
    }
};
deviceFinder.RunWorkerAsync();

No comments:

Post a Comment