コード例 #1
0
ファイル: HIDDevice.cs プロジェクト: nikkiportas/H109Tools10
 private void Initialise(string strPath)
 {
     this.m_hHandle = Win32Usb.CreateFile(strPath, 0xc0000000, 3, IntPtr.Zero, 3, 0x40000000, IntPtr.Zero);
     if (this.m_hHandle != Win32Usb.InvalidHandleValue)
     {
         IntPtr ptr;
         if (Win32Usb.HidD_GetPreparsedData(this.m_hHandle, out ptr))
         {
             try
             {
                 try
                 {
                     Win32Usb.HidCaps caps;
                     Win32Usb.HidP_GetCaps(ptr, out caps);
                     this.m_nInputReportLength  = caps.InputReportByteLength;
                     this.m_nOutputReportLength = caps.OutputReportByteLength;
                     this.m_oFile = new FileStream(new SafeFileHandle(this.m_hHandle, false), FileAccess.ReadWrite, this.m_nInputReportLength, true);
                     this.BeginAsyncRead();
                 }
                 catch (Exception)
                 {
                     throw HIDDeviceException.GenerateWithWinError("Failed to get the detailed data from the hid.");
                 }
                 return;
             }
             finally
             {
                 Win32Usb.HidD_FreePreparsedData(ref ptr);
             }
         }
         throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
     }
     this.m_hHandle = IntPtr.Zero;
     throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
 }
コード例 #2
0
ファイル: HIDDevice.cs プロジェクト: nikkiportas/H109Tools10
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string str             = $"vid_{nVid:x4}&pid_{nPid:x4}";
            Guid   hIDGuid         = Win32Usb.HIDGuid;
            IntPtr lpDeviceInfoSet = Win32Usb.SetupDiGetClassDevs(ref hIDGuid, null, IntPtr.Zero, 0x12);

            try
            {
                Win32Usb.DeviceInterfaceData structure = new Win32Usb.DeviceInterfaceData();
                structure.Size = Marshal.SizeOf(structure);
                for (int i = 0; Win32Usb.SetupDiEnumDeviceInterfaces(lpDeviceInfoSet, 0, ref hIDGuid, (uint)i, ref structure); i++)
                {
                    string devicePath = GetDevicePath(lpDeviceInfoSet, ref structure);
                    if (devicePath.IndexOf(str) >= 0)
                    {
                        HIDDevice device = (HIDDevice)Activator.CreateInstance(oType);
                        device.Initialise(devicePath);
                        return(device);
                    }
                }
            }
            catch (Exception exception)
            {
                throw HIDDeviceException.GenerateError(exception.ToString());
            }
            finally
            {
                Win32Usb.SetupDiDestroyDeviceInfoList(lpDeviceInfoSet);
            }
            return(null);
        }
コード例 #3
0
        // Token: 0x0600002B RID: 43 RVA: 0x00003FA4 File Offset: 0x000021A4
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string empty   = string.Empty;
            string value   = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);
            Guid   hidguid = Win32Usb.HIDGuid;
            IntPtr intPtr  = Win32Usb.SetupDiGetClassDevs(ref hidguid, null, IntPtr.Zero, 18u);

            try
            {
                Win32Usb.DeviceInterfaceData deviceInterfaceData = default(Win32Usb.DeviceInterfaceData);
                deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);
                int num = 0;
                while (Win32Usb.SetupDiEnumDeviceInterfaces(intPtr, 0u, ref hidguid, (uint)num, ref deviceInterfaceData))
                {
                    string devicePath = HIDDevice.GetDevicePath(intPtr, ref deviceInterfaceData);
                    if (devicePath.IndexOf(value) >= 0)
                    {
                        HIDDevice hiddevice = (HIDDevice)Activator.CreateInstance(oType);
                        hiddevice.Initialise(devicePath);
                        return(hiddevice);
                    }
                    num++;
                }
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
            }
            finally
            {
                Win32Usb.SetupDiDestroyDeviceInfoList(intPtr);
            }
            return(null);
        }
コード例 #4
0
        // Token: 0x06000024 RID: 36 RVA: 0x00003CB0 File Offset: 0x00001EB0
        private void Initialise(string strPath)
        {
            this.m_hHandle = Win32Usb.CreateFile(strPath, 3221225472u, 0u, IntPtr.Zero, 3u, 1073741824u, IntPtr.Zero);
            if (!(this.m_hHandle != Win32Usb.InvalidHandleValue))
            {
                this.m_hHandle = IntPtr.Zero;
                throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
            }
            IntPtr lpData;

            if (Win32Usb.HidD_GetPreparsedData(this.m_hHandle, out lpData))
            {
                try
                {
                    Win32Usb.HidCaps hidCaps;
                    Win32Usb.HidP_GetCaps(lpData, out hidCaps);
                    this.m_nInputReportLength  = (int)hidCaps.InputReportByteLength;
                    this.m_nOutputReportLength = (int)hidCaps.OutputReportByteLength;
                    HIDDevice.OutputLength     = this.m_nOutputReportLength;
                    HIDDevice.InputLength      = this.m_nInputReportLength;
                    this.m_oFile = new FileStream(new SafeFileHandle(this.m_hHandle, false), FileAccess.ReadWrite, this.m_nInputReportLength, true);
                    this.BeginAsyncRead();
                }
                catch (Exception ex)
                {
                    throw HIDDeviceException.GenerateWithWinError("Failed to get the detailed data from the hid." + ex.ToString());
                }
                finally
                {
                    Win32Usb.HidD_FreePreparsedData(ref lpData);
                }
                return;
            }
            throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
        }
コード例 #5
0
        /// <summary>
        /// Initialises the device
        /// </summary>
        /// <param name="strPath">Path to the device</param>
        private void Initialise(string strPath)
        {
            // Create the file from the device path
            m_hHandle = CreateFile(strPath,
                                   GENERIC_READ | GENERIC_WRITE,
                                   FILE_SHARE_WRITE | FILE_SHARE_READ,
                                   IntPtr.Zero,
                                   OPEN_EXISTING,
                                   FILE_FLAG_OVERLAPPED,
                                   IntPtr.Zero);

            if (m_hHandle != InvalidHandleValue || m_hHandle == null)                   // if the open worked...
            {
                IntPtr lpData;
                if (HidD_GetPreparsedData(m_hHandle, out lpData))                       // get windows to read the device data into an internal buffer
                {
                    try
                    {
                        HidCaps oCaps;
                        HidP_GetCaps(lpData, out oCaps);                                // extract the device capabilities from the internal buffer
                        m_nInputReportLength  = oCaps.InputReportByteLength;            // get the input...
                        m_nOutputReportLength = oCaps.OutputReportByteLength;           // ... and output report lengths

                        //m_oFile = new FileStream(m_hHandle, FileAccess.Read | FileAccess.Write, true, m_nInputReportLength, true);
                        m_oFile = new FileStream(new SafeFileHandle(m_hHandle, false), FileAccess.Read | FileAccess.Write, m_nInputReportLength, true);

                        BeginAsyncRead();                               // kick off the first asynchronous read
                    }
                    catch (Exception ex)
                    {
                        throw HIDDeviceException.GenerateWithWinError("Failed to get the detailed data from the hid.");
                    }
                    finally
                    {
                        HidD_FreePreparsedData(ref lpData);                             // before we quit the funtion, we must free the internal buffer reserved in GetPreparsedData
                    }
                }
                else                    // GetPreparsedData failed? Chuck an exception
                {
                    throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
                }
            }
            else                // File open failed? Chuck an exception
            {
                m_hHandle = IntPtr.Zero;
                throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
            }
        }
コード例 #6
0
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string strPath   = string.Empty;
            string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid); // first, build the path search string
            Guid   gHid      = HIDGuid;
            //HidD_GetHidGuid(out gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);  // this gets a list of all HID devices currently connected to the computer (InfoSet)


            try
            {
                DeviceInterfaceData oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);                      // get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch) >= 0)                                           // do a string search, if we find the VID/PID string then we found our device!
                    {
                        HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType);               // create an instance of the class for this device
                        oNewDevice.Initialise(strDevicePath);                                            // initialise it with the device path
                        return(oNewDevice);                                                              // and return it
                    }
                    nIndex++;                                                                            // if we get here, we didn't find our device. So move on to the next one.
                }

                //   MessageBox.Show("请检查是否插入设备!");
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
                //Console.WriteLine(ex.ToString());
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            //string a = @"\\?\hid#vid_0483&pid_5750#7&2e4989f7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
            //HIDDevice oNewDevice1 = (HIDDevice)Activator.CreateInstance(oType);
            //oNewDevice1.Initialise(a);	// initialise it with the device path
            //return oNewDevice1;
            return(null);        // oops, didn't find our device
        }
コード例 #7
0
ファイル: HIDDevice.cs プロジェクト: wangkkk/HIDWPF
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType)
        {
            string strPath   = string.Empty;
            string strSearch = @"#vid_" + nVid.ToString("x4") + "&pid_" + nPid.ToString("x4") + "#";
            //string strSearch = string.Format("VID_{0:X4}&PID_{1:X4}", nVid, nPid); // first, build the path search string
            Guid gHid = HIDGuid;

            HidD_GetHidGuid(ref gHid);                                                                                        // next, get the GUID from Windows that it uses to represent the HID USB interface
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, IntPtr.Zero, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); // this gets a list of all HID devices currently connected to the computer (InfoSet)

            try
            {
                var oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                //oInterface.Size = (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8;
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, IntPtr.Zero, ref gHid, nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);                          // get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch) >= 0)                                               // do a string search, if we find the VID/PID string then we found our device!
                    {
                        HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType);                   // create an instance of the class for this device
                        oNewDevice.Initialise(strDevicePath);                                                // initialise it with the device path
                        return(oNewDevice);                                                                  // and return it
                    }
                    nIndex++;                                                                                // if we get here, we didn't find our device. So move on to the next one.
                }
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
                //Console.WriteLine(ex.ToString());
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return(null);        // oops, didn't find our device
        }
コード例 #8
0
ファイル: HIDDevice.cs プロジェクト: ko9ma7/c-sharp
        /// <summary>
        /// Finds a device given its PID and VID
        /// </summary>
        /// <param name="nVid">Vendor id for device (VID)</param>
        /// <param name="nPid">Product id for device (PID)</param>
        /// <param name="oType">Type of device class to create</param>
        /// <returns>A new device class of the given type or null</returns>
        public static HIDDevice FindDevice(int nVid, int nPid, Type oType, string nProduct)
        {
            string strPath   = string.Empty;
            string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid);             // first, build the path search string
            Guid   gHid      = HIDGuid;

            // next, get the GUID from Windows that it uses to represent the HID USB interface
            //HidD_GetHidGuid(out gHid);

            // this gets a list of all HID devices currently connected to the computer (InfoSet)
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

            //IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, "USB", IntPtr.Zero, DIGCF_ALLCLASSES | DIGCF_PRESENT);

            try
            {
                DeviceInterfaceData oInterface = new DeviceInterfaceData();     // build up a device interface data block
                oInterface.Size = Marshal.SizeOf(oInterface);
                // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
                // to get device details for each device connected
                int nIndex = 0;

                // this gets the device interface information for a device at index 'nIndex' in the memory block
                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);        // get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch) >= 0)                             // do a string search, if we find the VID/PID string then we found our device!
                    {
                        HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType); // create an instance of the class for this device
                        oNewDevice.Initialise(strDevicePath);                              // initialise it with the device path
                        if (String.IsNullOrEmpty(nProduct))
                        {
                            return(oNewDevice);  // возвращяем первый попавшийся девайс, если нет предпочтения определённому производителю
                        }
                        else
                        {
                            string deviceProduct = null;
                            byte[] arrBuff       = new byte[255];

                            // читаем производителя с девайса
                            HidD_GetProductString(oNewDevice.m_hHandle, arrBuff, arrBuff.Length);

                            // переводим массив в строку
                            foreach (char b in arrBuff)
                            {
                                // нет проверки на спец знаки\символы
                                if (b != 0)
                                {
                                    deviceProduct += b.ToString();
                                }
                            }

                            // от возникновения мелких ошибок написания в разных регистрах
                            nProduct      = nProduct.ToLower();
                            deviceProduct = deviceProduct.ToLower();
                            // ну и проверяем - тот ли производитель
                            if (String.Equals(nProduct, deviceProduct))
                            {
                                return(oNewDevice);
                            }
                            else
                            {
                                oNewDevice.Dispose(); // закрываем девайс, он нам не подходит
                            }
                        }
                    }
                    nIndex++;   // if we get here, we didn't find our device. So move on to the next one.
                }
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
                //Console.WriteLine(ex.ToString());
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return(null);        // oops, didn't find our device
        }
コード例 #9
0
        /// <summary>
        /// Return a list information of connected USB HID devices
        /// </summary>
        public static List <HIDInfoSet> GetInfoSets(int?VendorID, int?ProductID, string SerialNumber)
        {
            string strSearch;


            if ((VendorID != null) && (ProductID != null))
            {
                strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", VendorID, ProductID);                 // first, build the path search string
            }
            else if (VendorID != null)
            {
                strSearch = string.Format("vid_{0:x4}&pid_", VendorID);                 // first, build the path search string
            }
            else
            {
                strSearch = "vid_";
            }

            List <HIDInfoSet> connectedDeviceList = new List <HIDInfoSet>();
            Guid gHid = HIDGuid;     // get the GUID from Windows that it uses to represent the HID USB interface

            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

            if (hInfoSet == InvalidHandleValue)
            {
                throw new Win32Exception();
            }

            try
            {
                var oInterface = new DeviceInterfaceData();
                oInterface.Size = Marshal.SizeOf(oInterface);
                int nIndex = 0;

                while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface))
                {
                    var strDevicePath = GetDevicePath(hInfoSet, ref oInterface);

                    // do a string search, if we find the VID/PID string then we found our device!
                    if (strDevicePath.IndexOf(strSearch) >= 0)
                    {
                        var handle = Open(strDevicePath);
                        if (handle != InvalidHandleValue)
                        {
                            IntPtr ptrToPreParsedData;
                            if (HidD_GetPreparsedData(handle, out ptrToPreParsedData))
                            {
                                HIDD_ATTRIBUTES attributes;
                                HidP_Caps       caps;

                                // check device serial number, if specify
                                if (((SerialNumber != null) && (GetSerialNumber(handle) == SerialNumber)) || (SerialNumber == null))
                                {
                                    // Get founded HID device informations
                                    var manufacturerString = GetManufacturerString(handle);
                                    var productString      = GetProductString(handle);
                                    var serialNumberString = GetSerialNumber(handle);
                                    GetAttr(handle, out attributes);
                                    GetCaps(ptrToPreParsedData, out caps);

                                    // Add founded HID device to connection list
                                    connectedDeviceList.Add(new HIDInfoSet(manufacturerString,
                                                                           productString,
                                                                           serialNumberString,
                                                                           strDevicePath,
                                                                           attributes.VendorID,
                                                                           attributes.ProductID,
                                                                           attributes.VersionNumber,
                                                                           caps.InputReportByteLength,
                                                                           caps.OutputReportByteLength));
                                }

                                if (handle != IntPtr.Zero)
                                {
                                    CloseHandle(handle);
                                }
                            }
                        }
                    }
                    nIndex++;
                }
            }
            catch (Exception ex)
            {
                throw HIDDeviceException.GenerateError(ex.ToString());
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }

            return(connectedDeviceList);
        }
コード例 #10
0
        /// <summary>
        /// Connect to device
        /// </summary>
        public bool Connect(string devicePath, bool useAsyncRead)
        {
            if (m_isConnected)
            {
                return(false);
            }

            // Create the file from the device path
            m_hHandle = CreateFile(devicePath, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);

            if (m_hHandle != InvalidHandleValue || m_hHandle == null)                   // if the open worked...
            {
                IntPtr lpData;
                if (HidD_GetPreparsedData(m_hHandle, out lpData))                       // get windows to read the device data into an internal buffer
                {
                    try
                    {
                        // Get HID device informations
                        m_devicePath         = devicePath;
                        m_manufacturerString = GetManufacturerString(m_hHandle);
                        m_productString      = GetProductString(m_hHandle);
                        m_serialNumberString = GetSerialNumber(m_hHandle);

                        HIDD_ATTRIBUTES attributes;
                        GetAttr(m_hHandle, out attributes);
                        m_version   = attributes.VersionNumber;
                        m_vendorId  = attributes.VendorID;
                        m_productId = attributes.ProductID;

                        HidP_Caps oCaps;
                        HidP_GetCaps(lpData, out oCaps);                                // extract the device capabilities from the internal buffer
                        m_inputReportLength  = oCaps.InputReportByteLength;             // get the input...
                        m_outputReportLength = oCaps.OutputReportByteLength;            // ... and output report lengths


                        //m_oFile = new FileStream(m_hHandle, FileAccess.Read | FileAccess.Write, true, m_nInputReportLength, true);
                        m_oFile = new FileStream(new SafeFileHandle(m_hHandle, false), FileAccess.Read | FileAccess.Write, m_inputReportLength, useAsyncRead);
                    }
                    catch (Exception ex)
                    {
                        throw HIDDeviceException.GenerateWithWinError("Failed to get the detailed data from the hid.");
                    }
                    finally
                    {
                        HidD_FreePreparsedData(ref lpData);                             // before we quit the funtion, we must free the internal buffer reserved in GetPreparsedData
                    }
                }
                else                    // GetPreparsedData failed? Chuck an exception
                {
                    throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
                }
            }
            else                // File open failed? Chuck an exception
            {
                m_hHandle = IntPtr.Zero;
                throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
            }

            m_useAsyncReads = useAsyncRead;
            m_isConnected   = true;

            if (m_useAsyncReads)
            {
                BeginAsyncRead();                               // kick off the first asynchronous read
            }
            return(true);
        }