FT260学习笔记3-打开设备

以C#为例解释FT260的软件设计流程,参考网上的文章《使用C#使用Windows的HID通信》。

 

可以直接引用hid.cs。

第一步是打开FT260设备。

 

  1. 获取所有连接的hid的设备路径,用的API函数是GetHidDeviceList,将读取到的信息加到一个ComboBox中。

cbDeviceList.Items.Clear();

 

List<string> deviceList = new List<string>();

Hid.GetHidDeviceList(ref deviceList);

if (deviceList.Count == 0)

{

    btDeviceOpen.Enabled = false;

    MessageBox.Show("No HID device found!");

}  

for(int i = 0; i < deviceList.Count; i++)

{

    cbDeviceList.Items.Add(deviceList[i]);

}

获取到的设备路径如下:

对于FT260来说,默认的VID和PID分别为0x0403和0x6030。

 

  1. 打开设备

hid.cs中打开设备的API函数是根据VID,PID和Serial来决定打开哪个HID设备,这里采用选中path的方式打开,所以增加一个OpenDevice的重构函数。

/// <summary>

/// 打开指定信息的设备

/// </summary>

/// <param name="path">设备的路径字符串</param>

/// <returns></returns>

public HID_RETURN OpenDevice(string path)

{

      if (deviceOpened == false)

      {

            IntPtr device = CreateFile(path,

                  DESIREDACCESS.GENERIC_READ | DESIREDACCESS.GENERIC_WRITE,

                  0,

                  0,

                  CREATIONDISPOSITION.OPEN_EXISTING,

                  FLAGSANDATTRIBUTES.FILE_FLAG_OVERLAPPED,

                  0);

            if (device != INVALID_HANDLE_VALUE)

            {           

                  IntPtr preparseData;

                  HIDP_CAPS caps;

                  HidD_GetPreparsedData(device, out preparseData);

                  HidP_GetCaps(preparseData, out caps);

                  HidD_FreePreparsedData(preparseData);

                  outputReportLength = caps.OutputReportByteLength;

                  inputReportLength = caps.InputReportByteLength;

 

                  hidDevice = new FileStream(new SafeFileHandle(device, false), FileAccess.ReadWrite, inputReportLength, true);

                  deviceOpened = true;

                  BeginAsyncRead();

 

                  hHubDevice = device;

                  return HID_RETURN.SUCCESS;

            }

            return HID_RETURN.DEVICE_NOT_FIND;

      }

      else

      {

            return HID_RETURN.DEVICE_OPENED;

      }

}

 

打开设备成功后,程序会开启一个异步读BeginAsyncRead。当接收到一次完整的数据后程序会调用Hid.cs的成员函数DataReceived。

 

注:网上的代码有个bug,注意下面红色部分是增加的代码,CreateFile后没有CloseHandle,导致多次Open/Close会出错。

if (attributes.VendorID == vID && attributes.ProductID == pID && deviceStr.Contains(serial))

{

         …

}

else

{

         CloseHandle(device);

}

 

同样,关闭设备CloseDevice()也需要增加CloseHandle的处理。

hidDevice.Close();

CloseHandle(hHubDevice);

 

猜你喜欢

转载自blog.csdn.net/pq113_6/article/details/89315521