Ejemplo n.º 1
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, HIDDevice device)
        {
            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!
                    {
                        device.Initialise(strDevicePath);                                                // initialise it with the device path
                        return(device);                                                                  // 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
        }
Ejemplo n.º 2
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 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
        }
Ejemplo n.º 3
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);
        }