Example #1
0
        public static IEnumerable<DeviceInterfaceData> SetupDiEnumDeviceInterfaces(
            SafeDeviceInfoSetHandle lpDeviceInfoSet,
            DeviceInfoData deviceInfoData,
            Guid interfaceClassGuid)
        {
            uint index = 0;
            while (true)
            {
                var data = DeviceInterfaceData.Create();

                var result = SetupDiEnumDeviceInterfaces(
                    lpDeviceInfoSet,
                    deviceInfoData,
                    ref interfaceClassGuid,
                    index,
                    ref data);

                if (!result)
                {
                    var lastError = GetLastError();
                    if (lastError != Win32ErrorCode.ERROR_NO_MORE_ITEMS)
                    {
                        throw new Win32Exception(lastError);
                    }

                    yield break;
                }

                yield return data;
                index++;
            }
        }
Example #2
0
            // enable/disable...
            private static void EnableDevice(SafeDeviceInfoSetHandle handle, DeviceInfoData diData, bool enable)
            {
                PropertyChangeParameters @params = new PropertyChangeParameters();

                // The size is just the size of the header, but we've flattened the structure.
                // The header comprises the first two fields, both integer.
                @params.Size       = 8;
                @params.DiFunction = DiFunction.PropertyChange;
                @params.Scope      = Scopes.Global;
                if (enable)
                {
                    @params.StateChange = StateChangeAction.Enable;
                }
                else
                {
                    @params.StateChange = StateChangeAction.Disable;
                }

                bool result = NativeMethods.SetupDiSetClassInstallParams(handle, ref diData, ref @params, Marshal.SizeOf(@params));

                if (result == false)
                {
                    throw new Win32Exception();
                }
                result = NativeMethods.SetupDiCallClassInstaller(DiFunction.PropertyChange, handle, ref diData);
                if (result == false)
                {
                    int err = Marshal.GetLastWin32Error();
                    if (err == (int)SetupApiError.NotDisableable)
                    {
                        throw new ArgumentException("Device can't be disabled (programmatically or in Device Manager).");
                    }
                    else if (err >= (int)SetupApiError.NoAssociatedClass && err <= (int)SetupApiError.OnlyValidateViaAuthenticode)
                    {
                        throw new Win32Exception("SetupAPI error: " + ((SetupApiError)err).ToString());
                    }
                    else
                    {
                        throw new Win32Exception();
                    }
                }
            }
Example #3
0
        static string ReadPropertyString(IntPtr infoSetPtr, ref DeviceInfoData deviceInfo, RegistryProperty property)
        {
            RegistryValueKind valueKind;
            uint requiredSize;

            SetupDiGetDeviceRegistryProperty(infoSetPtr, ref deviceInfo, property, out valueKind, IntPtr.Zero, 0, out requiredSize);
            var lastError = Marshal.GetLastWin32Error();

            if (ERROR_INSUFFICIENT_BUFFER == lastError)
            {
                Contract.Assert(new[]
                {
                    RegistryValueKind.ExpandString,
                    RegistryValueKind.MultiString,
                    RegistryValueKind.String
                }
                                .Contains(valueKind));

                IntPtr buffer = Marshal.AllocHGlobal((int)requiredSize);
                try
                {
                    if (SetupDiGetDeviceRegistryProperty(infoSetPtr, ref deviceInfo, property, out valueKind, buffer, requiredSize, out requiredSize))
                    {
                        return(Marshal.PtrToStringAuto(buffer));
                    }
                    lastError = Marshal.GetLastWin32Error();
                }
                finally
                {
                    Marshal.FreeHGlobal(buffer);
                }
            }
            if (ERROR_INVALID_DATA == lastError)
            {
                return(string.Empty);
            }
            throw new Win32Exception(lastError)
                  {
                      Source = "WinUSB.SetupDiGetDeviceRegistryProperty"
                  };
        }
        public async Task should_return_device_info()
        {
            var serviceData = await GetServiceData();

            var client = new SonoffClient(_httpClient);

            DeviceInfoData deviceInfo = null;
            Exception      exception  = null;

            try
            {
                deviceInfo = await client.GetDeviceInfoAsync(serviceData.ipAddress, serviceData.port, serviceData.deviceId);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.Null(exception);
            Assert.NotNull(deviceInfo);
        }
Example #5
0
        /// <summary>
        /// Ermittelt die Instanzennummer eines Gerätes.
        /// </summary>
        /// <param name="handle">Eine Geräteauflistung.</param>
        /// <param name="info">Eine Information zu dem gewünschten Gerät.</param>
        /// <returns>Die Instanzennummer oder <i>null</i>.</returns>
        private static string GetInstanceId(IntPtr handle, ref DeviceInfoData info)
        {
            // Allocate buffer
            var buffer = new byte[1000];

            // Load the name
            UInt32 charCount;

            if (!SetupDiGetDeviceInstanceId(handle, ref info, buffer, buffer.Length - 1, out charCount))
            {
                return(null);
            }
            else if (charCount-- > 0)
            {
                return(AnsiEncoding.GetString(buffer, 0, (int)charCount));
            }
            else
            {
                return(null);
            }
        }
Example #6
0
        /// <summary>
        /// Ermittelt eine Zeichenketteneigenschaft eines Gerätes.
        /// </summary>
        /// <param name="handle">Die Referenz auf die Liste aller Geräte (einer Art).</param>
        /// <param name="info">Das gewünschte Gerät.</param>
        /// <param name="propertyIndex">Die gewünschte Eigenschaft.</param>
        /// <returns>Der Wert der Eigenschaft oder <i>null</i>.</returns>
        private static string ReadStringProperty(IntPtr handle, ref DeviceInfoData info, int propertyIndex)
        {
            // Allocate buffer
            var buffer = new byte[10000];

            // Load the name
            UInt32 charCount, regType;

            if (!SetupDiGetDeviceRegistryProperty(handle, ref info, propertyIndex, out regType, buffer, buffer.Length - 1, out charCount))
            {
                return(null);
            }
            else if (charCount-- > 0)
            {
                return(AnsiEncoding.GetString(buffer, 0, (int)charCount));
            }
            else
            {
                return(null);
            }
        }
Example #7
0
        private static void EnableDevice(SafeDeviceInfoSetHandle handle, DeviceInfoData diData, bool enable)
        {
            PropertyChangeParameters propertyChangeParameters = new PropertyChangeParameters
            {
                Size        = 8,
                DiFunction  = DiFunction.PropertyChange,
                Scope       = Scopes.Global,
                StateChange =
                    enable
                                                                            ? StateChangeAction.Enable
                                                                            : StateChangeAction.Disable
            };

            // Set the parameters
            bool result = Win32.SetupDiSetClassInstallParams(handle, ref diData, ref propertyChangeParameters,
                                                             Marshal.SizeOf(propertyChangeParameters));

            if (result == false)
            {
                throw new Win32Exception();
            }

            // Apply the parameters
            result = Win32.SetupDiCallClassInstaller(DiFunction.PropertyChange, handle, ref diData);
            if (result == false)
            {
                int err = Marshal.GetLastWin32Error();
                if (err == ( int )SetupApiError.NotDisableable)
                {
                    throw new ArgumentException("Device can't be disabled (programmatically or in Device Manager).");
                }
                if (err <= ( int )SetupApiError.NoAssociatedClass &&
                    err >= ( int )SetupApiError.OnlyValidateViaAuthenticode)
                {
                    throw new Win32Exception("SetupAPI error: " + (( SetupApiError )err));
                }
                throw new Win32Exception();
            }
        }
Example #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string id, HexVer;
            string ret;

            try
            {
                id     = Request.QueryString["ID"];
                HexVer = Request.QueryString["HexVer"];
                //信息|用户id|实验id,实验名,实验室;
                if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(HexVer))//没有这两个变量
                {
                    ret = "no data";
                }
                else
                {
                    byte[] bid = StringsFunction.strToHexByte(id, "");
                    double ver = double.Parse(HexVer);
                    if (DeviceInfoDataDBOption.Get(id) != null)
                    {
                        ret = "reged";
                    }
                    else
                    {
                        DeviceInfoData di = new DeviceInfoData();
                        di.ID     = id;
                        di.HexVer = ver;
                        DeviceInfoDataDBOption.Insert(di);
                        ret = "ok";
                    }
                }
            }
            catch (System.Exception ex)
            {
                ret = "Exception" + ex.Message;
            }
            Response.Write(ret);
        }
        public async Task should_turn_switch_off()
        {
            var serviceData = await GetServiceData();

            var client = new SonoffClient(_httpClient);

            Exception      exception  = null;
            DeviceInfoData deviceInfo = null;

            try
            {
                await client.TurnSwitchOffAsync(serviceData.ipAddress, serviceData.port, serviceData.deviceId);

                deviceInfo = await client.GetDeviceInfoAsync(serviceData.ipAddress, serviceData.port, serviceData.deviceId);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.Null(exception);
            Assert.NotNull(deviceInfo);
            Assert.Equal(State.off, deviceInfo.Switch);
        }
Example #10
0
		public bool SetupDiEnumDeviceInfo(
            SafeDeviceInfoSetHandle deviceInfoSet,
            uint memberIndex,
            DeviceInfoData deviceInfoData)
			=> SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex, deviceInfoData);
Example #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string ret         = webAPIFunc.GetRetString(ErrType.UnkownErr);
            string LinuxServer = ConfigurationManager.AppSettings["LinuxServer"];

            try
            {
                string post = WFHttpWebResponse.PostInput(Request.InputStream);
                if (string.IsNullOrEmpty(post))//没有这两个变量
                {
                    ret = webAPIFunc.GetRetString(ErrType.MissParam);
                    Response.Write(ret);
                    return;
                }
                post = post.Substring(0, post.Length - 1);
                byte[] rx       = StringsFunction.strToHexByte(post, "");
                byte[] DeviceID = new byte[4];
                byte[] SSID     = new byte[4];
                byte[] data     = null;
                if (rx.Length == (0x401 * 0x08))
                {
                    for (int i = 0; i < 4; i++)
                    {
                        DeviceID[i] = rx[i];
                        SSID[i]     = rx[4 + i];
                    }
                    data = new byte[(0x400 * 0x08)];
                    for (int i = 0; i < (0x400 * 0x08); i++)
                    {
                        data[i] = rx[8 + i];
                    }
                }
                else if (rx.Length == (0x801 * 0x08))
                {
                    for (int i = 0; i < 4; i++)
                    {
                        DeviceID[i] = rx[i];
                        SSID[i]     = rx[4 + i];
                    }
                    data = new byte[(0x800 * 0x08)];
                    for (int i = 0; i < (0x800 * 0x08); i++)
                    {
                        data[i] = rx[8 + i];
                    }
                }
                else
                {
                    webAPIFunc.GetRetString(ErrType.ErrFileLen);
                    Response.Write(ret);
                    return;
                }
                byte[]         txData      = GlobalFunc.Encrypt(data, DeviceID, SSID);
                string         strDeviceID = StringsFunction.byteToHexStr(DeviceID, "");
                string         strSSID     = StringsFunction.byteToHexStr(SSID, "");
                DeviceInfoData did         = DeviceInfoDataDBOption.Get(strDeviceID);
                if (did == null)
                {
                    ret = webAPIFunc.GetRetString(ErrType.NoRegDevice);
                    Response.Write(ret);
                    return;
                }
                else
                {
                    int ut = HPassWorkLogDataDBOption.GetUseTimes(strDeviceID);
                    if (ut > did.HPassTimes)
                    {
                        ret = webAPIFunc.GetRetString(ErrType.MaxUseTimes);
                        Response.Write(ret);
                        return;
                    }
                }
                int index = HPassWorkLogDataDBOption.GetIndex(strDeviceID, strSSID);
                index++;
                string            fileName = strDeviceID + strSSID + "_" + index.ToString() + ".txt";
                WFHttpWebResponse web      = new WFHttpWebResponse();
                HttpWebResponse   webRet   = web.CreateGetHttpResponse(LinuxServer);
                if (webRet == null)
                {
                    ret = webAPIFunc.GetRetString(ErrType.MissServer);
                    Response.Write(ret);
                    return;
                }
                webRet = web.CreatePostHttpResponse(LinuxServer + @"/login", "username=root&password=root");
                if (webRet == null)
                {
                    ret = webAPIFunc.GetRetString(ErrType.MissServer);
                    Response.Write(ret);
                    return;
                }
                webRet = web.CreateGetHttpResponse(LinuxServer + @"/search_m1_user");
                if (webRet == null)
                {
                    ret = webAPIFunc.GetRetString(ErrType.MissServer);
                    Response.Write(ret);
                    return;
                }
                HttpWebRequest request = null;
                request        = WebRequest.Create(LinuxServer + @"/m1_user_search_add") as HttpWebRequest;
                request.Method = "POST";
                string boundary = DateTime.Now.Ticks.ToString("x");
                //请求
                request.ContentType = "multipart/form-data; boundary=---------------------------" + boundary;

                request.CookieContainer = new CookieContainer();
                if (web.Cookies != null && web.Cookies.Count != 0)
                {
                    foreach (Cookie c in web.Cookies)
                    {
                        request.CookieContainer.Add(c);
                    }
                }

                //组织表单数据
                StringBuilder sb = new StringBuilder();
                sb.Append("-----------------------------" + boundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"search_source\"; filename=\"" + fileName + "\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: text/plain");
                sb.Append("\r\n\r\n");
                string head      = sb.ToString();
                byte[] form_data = Encoding.ASCII.GetBytes(head);
                //结尾
                byte[] foot_data = Encoding.ASCII.GetBytes("\r\n-----------------------------" + boundary + "--\r\n");
                //数据
                StringBuilder sb1 = new StringBuilder();
                if (rx.Length == (0x401 * 0x08))
                {
                    for (int i = 0; i < 0x400; i++)
                    {
                        sb1.Append(StringsFunction.byteToHexStr(txData, i * 8, 8, " "));
                        sb1.Append("\r\n");
                    }
                }
                else
                {
                    for (int i = 0; i < 0x800; i++)
                    {
                        sb1.Append(StringsFunction.byteToHexStr(txData, i * 8, 8, " "));
                        sb1.Append("\r\n");
                    }
                }
                sb1.Remove(sb1.Length - 2, 2);
                TextLog.AddTextLog(sb1.ToString(), Global.txtLogFolder + "HPassLog\\" + fileName, false);
                byte[] pBuf = Encoding.ASCII.GetBytes(sb1.ToString());
                //post总长度
                long length = form_data.Length + pBuf.Length + foot_data.Length;
                request.ContentLength = length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(form_data, 0, form_data.Length);
                    //文件内容
                    requestStream.Write(pBuf, 0, pBuf.Length);
                    //结尾
                    requestStream.Write(foot_data, 0, foot_data.Length);
                }
                try
                {
                    HttpWebResponse fileResponse = request.GetResponse() as HttpWebResponse;
                    string          Content;
                    if (fileResponse.Headers["ContentEncoding"] != null)
                    {
                        Stream       receiveStream = fileResponse.GetResponseStream();
                        StreamReader sr            = new StreamReader(receiveStream, Encoding.GetEncoding(fileResponse.Headers["ContentEncoding"].ToString()));
                        Content = sr.ReadToEnd();
                    }
                    else
                    {
                        try
                        {
                            Stream       receiveStream = fileResponse.GetResponseStream();
                            StreamReader sr            = new StreamReader(receiveStream);
                            Content = sr.ReadToEnd();
                        }
                        catch
                        {
                        }
                    }
                    if (fileResponse.StatusCode == HttpStatusCode.OK)
                    {
                        ret = webAPIFunc.GetRetString(ErrType.retOK, fileName);
                        HPassWorkLogData hl = new HPassWorkLogData();
                        hl.DeviceID = strDeviceID;
                        hl.SSID     = strSSID;
                        hl.FileName = fileName;
                        hl.IP       = aspNetFunc.getIp();
                        HPassWorkLogDataDBOption.Insert(hl);
                        Response.Write(ret);
                        return;
                    }
                }
                catch (System.Exception ex)
                {
                    ret = webAPIFunc.GetRetString(ErrType.UnkownErr);
                    Response.Write(ret);
                    TextLog.AddTextLog("Add_updatafile:" + ex.Message, Global.txtLogFolder + "HPass.txt", true);
                    return;
                }
            }
            catch (System.Exception ex)
            {
                ret = webAPIFunc.GetRetString(ErrType.UnkownErr);
                TextLog.AddTextLog("Add_Unkown:" + ex.Message, Global.txtLogFolder + "HPass.txt", true);
            }
            Response.Write(ret);
        }
Example #12
0
 public static extern bool SetupDiEnumDeviceInterfaces(
   IntPtr handle,
   ref DeviceInfoData deviceInfoData,
   ref Guid guidClass,
   int MemberIndex,
   ref DeviceInterfaceData deviceInterfaceData);
Example #13
0
 protected static extern bool SetupDiGetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref DeviceInfoData DeviceInfoData, RegistryProperty Property, out RegistryValueKind PropertyRegDataType, IntPtr PropertyBuffer, uint PropertyBufferSize, out uint RequiredSize);
 internal static extern bool SetupDiEnumDeviceInfo(IntPtr deviceInfoSet, int memberIndex, ref DeviceInfoData deviceInfoData);
Example #15
0
 protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr handle, ref DeviceInfoData deviceInfoData,
                                                          ref Guid guidClass, int MemberIndex,
                                                          ref DeviceInterfaceData deviceInterfaceData);
Example #16
0
 public static extern bool SetupDiEnumDeviceInfo(
     SafeDeviceInfoSetHandle deviceInfoSet,
     uint memberIndex,
     DeviceInfoData deviceInfoData);
Example #17
0
 internal static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, uint MemberIndex, DeviceInfoData deviceInfoData);
Example #18
0
    protected string FindDevice(Guid classGuid)
    {
      if (Transceivers != null)
        _eHomeTransceivers = Transceivers.Select(t => t.DeviceID);

      IntPtr handle = SetupDiGetClassDevs(ref classGuid, 0, 0, 0x12);

      string devicePath = null;

      if (handle.ToInt32() == -1)
      {
        throw new Exception(string.Format("Failed in call to SetupDiGetClassDevs ({0})", GetLastError()));
      }

      for (int deviceIndex = 0;; deviceIndex++)
      {
        DeviceInfoData deviceInfoData = new DeviceInfoData();
        deviceInfoData.Size = Marshal.SizeOf(deviceInfoData);

        if (SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData) == false)
        {
          // out of devices or do we have an error?
          if (GetLastError() != 0x103 && GetLastError() != 0x7E)
          {
            SetupDiDestroyDeviceInfoList(handle);
            throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInfo ({0})", GetLastError()));
          }

          SetupDiDestroyDeviceInfoList(handle);
          break;
        }

        DeviceInterfaceData deviceInterfaceData = new DeviceInterfaceData();
        deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);

        if (SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData) == false)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInterfaces ({0})", GetLastError()));
        }

        uint cbData = 0;

        if (SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, 0, 0, ref cbData, 0) == false &&
            cbData == 0)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
        }

        DeviceInterfaceDetailData deviceInterfaceDetailData = new DeviceInterfaceDetailData();
        deviceInterfaceDetailData.Size = 5;

        if (
          SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData, 0, 0) ==
          false)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
        }

        if (LogVerbose)
        {
          MceRemoteReceiver.LogInfo("Found: {0}", deviceInterfaceDetailData.DevicePath);
        }

        foreach (string deviceId in _eHomeTransceivers)
        {
          if ((deviceInterfaceDetailData.DevicePath.IndexOf(deviceId) != -1) ||
              (deviceInterfaceDetailData.DevicePath.StartsWith(@"\\?\hid#irdevice&col01#2")) ||
              // eHome Infrared Transceiver List XP
              (deviceInterfaceDetailData.DevicePath.StartsWith(@"\\?\hid#irdevicev2&col01#2")))
            // Microsoft/Philips 2005 (Vista)
          {
            SetupDiDestroyDeviceInfoList(handle);
            devicePath = deviceInterfaceDetailData.DevicePath;
          }
        }
        if (devicePath != null)
        {
          break;
        }
      }
      return devicePath;
    }
Example #19
0
 public static extern bool SetupDiEnumDeviceInterfaces(
     SafeDeviceInfoSetHandle deviceInfoSet,
     DeviceInfoData deviceInfoData,
     ref Guid interfaceClassGuid,
     uint memberIndex,
     ref DeviceInterfaceData deviceInterfaceData);
Example #20
0
        /// <summary>
        /// Find the device path for the supplied Device Class Guid.
        /// </summary>
        /// <param name="classGuid">GUID to locate device with.</param>
        /// <returns>Device path.</returns>
        public static string Find(Guid classGuid)
        {
            IntPtr handle = SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, Digcfs.DeviceInterface | Digcfs.Present);

            if (handle.ToInt32() == -1)
            {
                return(null);
            }

            for (int deviceIndex = 0;; deviceIndex++)
            {
                DeviceInfoData deviceInfoData = new DeviceInfoData();
                deviceInfoData.Size = Marshal.SizeOf(deviceInfoData);

                if (!SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData))
                {
                    int lastError = Marshal.GetLastWin32Error();

                    // out of devices or do we have an error?
                    if (lastError != ErrorNoMoreItems && lastError != ErrorModNotFound)
                    {
                        SetupDiDestroyDeviceInfoList(handle);
                        throw new Win32Exception(lastError);
                    }

                    SetupDiDestroyDeviceInfoList(handle);
                    break;
                }

                DeviceInterfaceData deviceInterfaceData = new DeviceInterfaceData();
                deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);

                if (!SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData))
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                uint cbData = 0;

                if (
                    !SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, IntPtr.Zero, 0, ref cbData, IntPtr.Zero) &&
                    cbData == 0)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                DeviceInterfaceDetailData deviceInterfaceDetailData = new DeviceInterfaceDetailData();
                if (IntPtr.Size == 8)
                {
                    deviceInterfaceDetailData.Size = 8;
                }
                else
                {
                    deviceInterfaceDetailData.Size = 5;
                }


                if (
                    !SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData,
                                                     IntPtr.Zero, IntPtr.Zero))
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!String.IsNullOrEmpty(deviceInterfaceDetailData.DevicePath))
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    return(deviceInterfaceDetailData.DevicePath);
                }
            }

            return(null);
        }
Example #21
0
 private static extern bool SetupDiEnumDeviceInfo(
     IntPtr handle,
     int index,
     ref DeviceInfoData deviceInfoData);
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceInformationElement"/> class.
 /// </summary>
 /// <param name="guid">
 /// The guid.
 /// </param>
 /// <param name="deviceInformationSetHandle">
 /// The device Information Set Handle.
 /// </param>
 /// <param name="deviceInfoData">
 /// The device info data.
 /// </param>
 /// <param name="unsafeNativeMethodsWrapper">
 /// The unsafe Native Methods Wrapper.
 /// </param>
 public DeviceInformationElement(Guid guid, IntPtr deviceInformationSetHandle, DeviceInfoData deviceInfoData, IUnsafeNativeMethodsWrapper unsafeNativeMethodsWrapper)
 {
     DeviceInterfaces = unsafeNativeMethodsWrapper.GetDeviceInterfaces(deviceInformationSetHandle, deviceInfoData, guid);
 }
Example #23
0
 protected static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, UInt32 MemberIndex, ref DeviceInfoData DeviceInfoData);
Example #24
0
        private static string GetDeviceName()
        {
            Guid gHid;
            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
            {
                uint SPDRP_DEVICEDESC = 0x00000000;
                uint SPDRP_DRIVER = 0x00000009;
                int BUFFER_SIZE = 256;
                bool Success = true;
                int i = 0;
                while (Success)
                {
                    // create a Device Interface Data structure
                    DeviceInterfaceData oInterface = new DeviceInterfaceData();	// build up a device interface data block
                    oInterface.Size = Marshal.SizeOf(oInterface);

                    // start the enumeration
                    Success = SetupDiEnumDeviceInterfaces(hInfoSet, IntPtr.Zero, ref gHid, (uint)i, ref oInterface);
                    if (Success)
                    {
                        // build a Device Interface Detail Data structure
                        DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                        oDetail.Size = (IntPtr.Size == 4) ? 5 : 8;	// hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx

                        DeviceInfoData da = new DeviceInfoData();
                        da.Size = (uint)Marshal.SizeOf(da);

                        // now we can get some more detailed information
                        uint nRequiredSize = 0;
                        int nBytes = BUFFER_SIZE;
                        //hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero;
                        if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, (uint)nBytes, ref nRequiredSize, ref da))
                        {
                            // get the Device Description and DriverKeyName
                            uint RequiredSize;
                            uint RegType;
                            byte[] ptrBuf = new byte[BUFFER_SIZE];

                            if (SetupDiGetDeviceRegistryProperty(hInfoSet, ref oInterface, SPDRP_DEVICEDESC, out RegType, ptrBuf, (uint)BUFFER_SIZE, out RequiredSize))
                            {
                                string ControllerDeviceDesc = System.Text.Encoding.UTF8.GetString(ptrBuf);// Marshal.PtrToStringAuto(ptrBuf);
                            }
                            if (SetupDiGetDeviceRegistryProperty(hInfoSet, ref oInterface, SPDRP_DRIVER, out RegType, ptrBuf, (uint)BUFFER_SIZE, out RequiredSize))
                            {
                                string ControllerDriverKeyName = System.Text.Encoding.UTF8.GetString(ptrBuf);
                            }
                        }
                    }
                    i++;
                }
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return "";
        }
Example #25
0
 public static extern bool SetupDiGetDeviceInstanceId(IntPtr DeviceInfoSet, ref DeviceInfoData did, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder DeviceInstanceId, int DeviceInstanceIdSize, out int RequiredSize);
Example #26
0
        /// <summary>
        /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
        /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
        /// </summary>
        /// <param name="hInfoSet">Handle to the InfoSet</param>
        /// <param name="oInterface">DeviceInterfaceData structure</param>
        /// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
        {
            uint nRequiredSize = 0;
            DeviceInfoData da = new DeviceInfoData();
            da.Size = (uint)Marshal.SizeOf(da);
            // Get the device interface details
            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, ref da))
            {
                DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                oDetail.Size = (IntPtr.Size == 4) ? 5 : 8;	// hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx

                if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, ref da))
                {
                    return oDetail.DevicePath;
                }
            }
            return null;
        }
 public static extern bool SetupDiEnumDeviceInfo(SafeDeviceInfoSetHandle deviceInfoSet, int memberIndex,
                                                 ref DeviceInfoData deviceInfoData);
Example #28
0
 protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, ref DeviceInterfaceDetailData oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, ref DeviceInfoData lpDeviceInfoData);
Example #29
0
        protected string FindDevice(Guid classGuid)
        {
            if (Transceivers != null)
            {
                _eHomeTransceivers = Transceivers.Select(t => t.DeviceID);
            }

            IntPtr handle = SetupDiGetClassDevs(ref classGuid, 0, 0, 0x12);

            string devicePath = null;

            if (handle.ToInt32() == -1)
            {
                throw new Exception(string.Format("Failed in call to SetupDiGetClassDevs ({0})", GetLastError()));
            }

            for (int deviceIndex = 0;; deviceIndex++)
            {
                DeviceInfoData deviceInfoData = new DeviceInfoData();
                deviceInfoData.Size = Marshal.SizeOf(deviceInfoData);

                if (SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData) == false)
                {
                    // out of devices or do we have an error?
                    if (GetLastError() != 0x103 && GetLastError() != 0x7E)
                    {
                        SetupDiDestroyDeviceInfoList(handle);
                        throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInfo ({0})", GetLastError()));
                    }

                    SetupDiDestroyDeviceInfoList(handle);
                    break;
                }

                DeviceInterfaceData deviceInterfaceData = new DeviceInterfaceData();
                deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);

                if (SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData) == false)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInterfaces ({0})", GetLastError()));
                }

                uint cbData = 0;

                if (SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, 0, 0, ref cbData, 0) == false &&
                    cbData == 0)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
                }

                DeviceInterfaceDetailData deviceInterfaceDetailData = new DeviceInterfaceDetailData();
                deviceInterfaceDetailData.Size = 5;

                if (
                    SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData, 0, 0) ==
                    false)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
                }

                if (LogVerbose)
                {
                    MceRemoteReceiver.LogInfo("Found: {0}", deviceInterfaceDetailData.DevicePath);
                }

                foreach (string deviceId in _eHomeTransceivers)
                {
                    if ((deviceInterfaceDetailData.DevicePath.IndexOf(deviceId) != -1) ||
                        (deviceInterfaceDetailData.DevicePath.StartsWith(@"\\?\hid#irdevice&col01#2")) ||
                        // eHome Infrared Transceiver List XP
                        (deviceInterfaceDetailData.DevicePath.StartsWith(@"\\?\hid#irdevicev2&col01#2")))
                    // Microsoft/Philips 2005 (Vista)
                    {
                        SetupDiDestroyDeviceInfoList(handle);
                        devicePath = deviceInterfaceDetailData.DevicePath;
                    }
                }
                if (devicePath != null)
                {
                    break;
                }
            }
            return(devicePath);
        }
Example #30
0
    protected static string FindDevice(Guid classGuid)
    {
      IntPtr handle = SetupDiGetClassDevs(ref classGuid, 0, 0, 0x12);
      string devicePath = null;

      if (handle.ToInt32() == -1)
      {
        throw new Exception(string.Format("Failed in call to SetupDiGetClassDevs ({0})", GetLastError()));
      }

      for (int deviceIndex = 0;; deviceIndex++)
      {
        DeviceInfoData deviceInfoData = new DeviceInfoData();
        deviceInfoData.Size = Marshal.SizeOf(deviceInfoData);

        if (SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData) == false)
        {
          // out of devices or do we have an error?
          if (GetLastError() != 0x103 && GetLastError() != 0x7E)
          {
            SetupDiDestroyDeviceInfoList(handle);
            throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInfo ({0})", GetLastError()));
          }

          SetupDiDestroyDeviceInfoList(handle);
          break;
        }

        DeviceInterfaceData deviceInterfaceData = new DeviceInterfaceData();
        deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);

        if (SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData) == false)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInterfaces ({0})", GetLastError()));
        }

        uint cbData = 0;

        if (SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, 0, 0, ref cbData, 0) == false &&
            cbData == 0)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
        }

        DeviceInterfaceDetailData deviceInterfaceDetailData = new DeviceInterfaceDetailData();
        deviceInterfaceDetailData.Size = 5;

        if (
          SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData, 0, 0) ==
          false)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
        }

        if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_0471&pid_0815") != -1)
        {
          SetupDiDestroyDeviceInfoList(handle);
          devicePath = deviceInterfaceDetailData.DevicePath;
          break;
        }

        if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_045e&pid_006d") != -1)
        {
          SetupDiDestroyDeviceInfoList(handle);
          devicePath = deviceInterfaceDetailData.DevicePath;
          break;
        }

        if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_1460&pid_9150") != -1)
        {
          SetupDiDestroyDeviceInfoList(handle);
          devicePath = deviceInterfaceDetailData.DevicePath;
          break;
        }

        if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_0609&pid_031d") != -1)
        {
          SetupDiDestroyDeviceInfoList(handle);
          devicePath = deviceInterfaceDetailData.DevicePath;
          break;
        }
        if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_03ee&pid_2501") != -1)
        {
          SetupDiDestroyDeviceInfoList(handle);
          devicePath = deviceInterfaceDetailData.DevicePath;
          break;
        }
      }

      return devicePath;
    }
Example #31
0
    /// <summary>
    /// Find the device path for the supplied Device Class Guid.
    /// </summary>
    /// <param name="classGuid">GUID to locate device with.</param>
    /// <returns>Device path.</returns>
    public static string Find(Guid classGuid)
    {
      IntPtr handle = SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, Digcfs.DeviceInterface | Digcfs.Present);

      if (handle.ToInt32() == -1)
        return null;

      for (int deviceIndex = 0;; deviceIndex++)
      {
        DeviceInfoData deviceInfoData = new DeviceInfoData();
        deviceInfoData.Size = Marshal.SizeOf(deviceInfoData);

        if (!SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData))
        {
          int lastError = Marshal.GetLastWin32Error();

          // out of devices or do we have an error?
          if (lastError != ErrorNoMoreItems && lastError != ErrorModNotFound)
          {
            SetupDiDestroyDeviceInfoList(handle);
            throw new Win32Exception(lastError);
          }

          SetupDiDestroyDeviceInfoList(handle);
          break;
        }

        DeviceInterfaceData deviceInterfaceData = new DeviceInterfaceData();
        deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);

        if (!SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData))
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        uint cbData = 0;

        if (
          !SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, IntPtr.Zero, 0, ref cbData, IntPtr.Zero) &&
          cbData == 0)
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        DeviceInterfaceDetailData deviceInterfaceDetailData = new DeviceInterfaceDetailData();
        if (IntPtr.Size == 8)
          deviceInterfaceDetailData.Size = 8;
        else
          deviceInterfaceDetailData.Size = 5;


        if (
          !SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData,
                                           IntPtr.Zero, IntPtr.Zero))
        {
          SetupDiDestroyDeviceInfoList(handle);
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        if (!String.IsNullOrEmpty(deviceInterfaceDetailData.DevicePath))
        {
          SetupDiDestroyDeviceInfoList(handle);
          return deviceInterfaceDetailData.DevicePath;
        }
      }

      return null;
    }
Example #32
0
        private static string GetDeviceName()
        {
            Guid gHid;

            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
            {
                uint SPDRP_DEVICEDESC = 0x00000000;
                uint SPDRP_DRIVER     = 0x00000009;
                int  BUFFER_SIZE      = 256;
                bool Success          = true;
                int  i = 0;
                while (Success)
                {
                    // create a Device Interface Data structure
                    DeviceInterfaceData oInterface = new DeviceInterfaceData(); // build up a device interface data block
                    oInterface.Size = Marshal.SizeOf(oInterface);

                    // start the enumeration
                    Success = SetupDiEnumDeviceInterfaces(hInfoSet, IntPtr.Zero, ref gHid, (uint)i, ref oInterface);
                    if (Success)
                    {
                        // build a Device Interface Detail Data structure
                        DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
                        oDetail.Size = (IntPtr.Size == 4) ? 5 : 8;      // hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx

                        DeviceInfoData da = new DeviceInfoData();
                        da.Size = (uint)Marshal.SizeOf(da);

                        // now we can get some more detailed information
                        uint nRequiredSize = 0;
                        int  nBytes        = BUFFER_SIZE;
                        //hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero;
                        if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, (uint)nBytes, ref nRequiredSize, ref da))
                        {
                            // get the Device Description and DriverKeyName
                            uint   RequiredSize;
                            uint   RegType;
                            byte[] ptrBuf = new byte[BUFFER_SIZE];

                            if (SetupDiGetDeviceRegistryProperty(hInfoSet, ref oInterface, SPDRP_DEVICEDESC, out RegType, ptrBuf, (uint)BUFFER_SIZE, out RequiredSize))
                            {
                                string ControllerDeviceDesc = System.Text.Encoding.UTF8.GetString(ptrBuf);// Marshal.PtrToStringAuto(ptrBuf);
                            }
                            if (SetupDiGetDeviceRegistryProperty(hInfoSet, ref oInterface, SPDRP_DRIVER, out RegType, ptrBuf, (uint)BUFFER_SIZE, out RequiredSize))
                            {
                                string ControllerDriverKeyName = System.Text.Encoding.UTF8.GetString(ptrBuf);
                            }
                        }
                    }
                    i++;
                }
            }
            finally
            {
                // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return("");
        }
Example #33
0
 static private extern bool SetupDiGetDeviceInstanceId(IntPtr deviceInfoSet, ref DeviceInfoData deviceInfoData, byte[] buffer, int bufferSize, out UInt32 requiredSize);
Example #34
0
 protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, ref DeviceInterfaceDetailData oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, ref DeviceInfoData lpDeviceInfoData);
Example #35
0
		public bool SetupDiGetDeviceInterfaceDetail(
            SafeDeviceInfoSetHandle deviceInfoSet,
            ref DeviceInterfaceData deviceInterfaceData,
            IntPtr deviceInterfaceDetailData,
            uint deviceInterfaceDetailDataSize,
            NullableUInt32 requiredSize,
            DeviceInfoData deviceInfoData)
			=> SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, deviceInterfaceDetailData, deviceInterfaceDetailDataSize, requiredSize, deviceInfoData);
Example #36
0
 protected void Page_Load(object sender, EventArgs e)
 {
     strid = Request.QueryString["id"];
     if (!IsPostBack)
     {
         DropDownList1.Items.Clear();
         DropDownList2.Items.Clear();
         for (int i = 1; i < 20; i++)
         {
             DropDownList1.Items.Add(i.ToString());
             DropDownList2.Items.Add(i.ToString());
         }
         DropDownList3.Items.Clear();
         DropDownList3.Items.Add("所有");
         DropDownList3.Items.Add("国内");
         DropDownList3.Items.Add("国外");
         if (strid != null && strid != "")//修改
         {
             ed = DeviceInfoDataDBOption.Get(strid);
             if (ed.bHPass)
             {
                 CheckBox1.Checked = true;
             }
             else
             {
                 CheckBox1.Checked = false;
             }
             if (ed.bDPass)
             {
                 CheckBox2.Checked = true;
             }
             else
             {
                 CheckBox2.Checked = false;
             }
             if (ed.bESLPass)
             {
                 CheckBox3.Checked = true;
             }
             else
             {
                 CheckBox3.Checked = false;
             }
             if (ed.bKeyData)
             {
                 CheckBox4.Checked = true;
             }
             else
             {
                 CheckBox4.Checked = false;
             }
             DropDownList1.SelectedIndex = ed.HPassTimes - 1;
             DropDownList2.SelectedIndex = ed.DPassTimes - 1;
             if (ed.bak1 == "所有")
             {
                 DropDownList3.SelectedIndex = 0;
             }
             else if (ed.bak1 == "国内")
             {
                 DropDownList3.SelectedIndex = 1;
             }
             else if (ed.bak1 == "国外")
             {
                 DropDownList3.SelectedIndex = 2;
             }
             else
             {
                 DropDownList3.SelectedIndex = 1;
             }
         }
         else
         {
             Page.ClientScript.RegisterStartupScript(this.GetType(), "", " <script lanuage=javascript>alert('缺少数据');GetDataAndClose(); </script>");
         }
     }
 }
Example #37
0
		public bool SetupDiEnumDeviceInterfaces(
            SafeDeviceInfoSetHandle deviceInfoSet,
            DeviceInfoData deviceInfoData,
            ref Guid interfaceClassGuid,
            uint memberIndex,
            ref DeviceInterfaceData deviceInterfaceData)
			=> SetupDiEnumDeviceInterfaces(deviceInfoSet, deviceInfoData, ref interfaceClassGuid, memberIndex, ref deviceInterfaceData);
Example #38
0
        /// <summary>
        /// Find the related device and change the operating state.
        /// </summary>
        /// <param name="stateCode">The code for the state corresponding to
        /// the <i>DICS_</i> constants of Windows.</param>
        /// <returns></returns>
        private void ChangeState( int stateCode )
        {
            // Open device
            var hInfoList = SetupDiGetClassDevs( ref m_Class, IntPtr.Zero, IntPtr.Zero, 2 );

            // Validate
            if ((int) hInfoList == -1)
                throw new DeviceException( "Could not create Device Set" );

            // With cleanup
            try
            {
                // Create the device information data block
                var pData = new DeviceInfoData();

                // Initialize
                pData.cbSize = Marshal.SizeOf( pData );

                // Find them all
                for (uint ix = 0; SetupDiEnumDeviceInfo( hInfoList, ix++, ref pData );)
                {
                    // Load the name
                    string name;

                    // Check mode
                    if (m_FilterIndex == uint.MaxValue)
                        name = GetInstanceId( hInfoList, ref pData );
                    else
                        name = ReadStringProperty( hInfoList, ref pData, (int) m_FilterIndex );

                    // Skip
                    if (string.IsNullOrEmpty( name ))
                        continue;

                    // Compare
                    if (!m_Adaptor.Equals( name ))
                        continue;

                    // Create update helper
                    var pParams =
                        new PropChangeParams
                        {
                            ClassInstallHeader = { cbSize = ClassInstallHeader.SizeOf, InstallFunction = 0x12 },
                            Scope = (uint) ((stateCode < 4) ? 1 : 2),
                            StateChange = (uint) stateCode,
                        };

                    // Prepare
                    if (!SetupDiSetClassInstallParams( hInfoList, ref pData, ref pParams, PropChangeParams.SizeOf ))
                        throw new DeviceException( "Could not update Class Install Parameters" );

                    // Change mode
                    if (!SetupDiCallClassInstaller( pParams.ClassInstallHeader.InstallFunction, hInfoList, ref pData ))
                        throw new DeviceException( "Unable to finish Change Request" );

                    // Did it 
                    return;
                }

                // Not found
                throw new DeviceException( "No Device " + m_Adaptor + " found" );
            }
            finally
            {
                // Clean it
                SetupDiDestroyDeviceInfoList( hInfoList );
            }
        }
Example #39
0
 protected static extern bool SetupDiGetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref DeviceInfoData DeviceInfoData, RegistryProperty Property, out RegistryValueKind PropertyRegDataType, IntPtr PropertyBuffer, uint PropertyBufferSize, out uint RequiredSize);
Example #40
0
 static private extern bool SetupDiGetDeviceRegistryProperty( IntPtr DeviceInfoSet, ref DeviceInfoData DeviceInfoData, Int32 Property, out UInt32 PropertyRegDataType, byte[] PropertyBuffer, Int32 PropertyBufferSize, out UInt32 RequiredSize );
        protected static string FindDevice(Guid classGuid)
        {
            IntPtr handle     = SetupDiGetClassDevs(ref classGuid, 0, 0, 0x12);
            string devicePath = null;

            if (handle.ToInt32() == -1)
            {
                throw new Exception(string.Format("Failed in call to SetupDiGetClassDevs ({0})", GetLastError()));
            }

            for (int deviceIndex = 0;; deviceIndex++)
            {
                DeviceInfoData deviceInfoData = new DeviceInfoData();
                deviceInfoData.Size = Marshal.SizeOf(deviceInfoData);

                if (SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData) == false)
                {
                    // out of devices or do we have an error?
                    if (GetLastError() != 0x103 && GetLastError() != 0x7E)
                    {
                        SetupDiDestroyDeviceInfoList(handle);
                        throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInfo ({0})", GetLastError()));
                    }

                    SetupDiDestroyDeviceInfoList(handle);
                    break;
                }

                DeviceInterfaceData deviceInterfaceData = new DeviceInterfaceData();
                deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData);

                if (SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData) == false)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Exception(string.Format("Failed in call to SetupDiEnumDeviceInterfaces ({0})", GetLastError()));
                }

                uint cbData = 0;

                if (SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, 0, 0, ref cbData, 0) == false &&
                    cbData == 0)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
                }

                DeviceInterfaceDetailData deviceInterfaceDetailData = new DeviceInterfaceDetailData();
                deviceInterfaceDetailData.Size = 5;

                if (
                    SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData, 0, 0) ==
                    false)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    throw new Exception(string.Format("Failed in call to SetupDiGetDeviceInterfaceDetail ({0})", GetLastError()));
                }

                if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_0471&pid_0815") != -1)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    devicePath = deviceInterfaceDetailData.DevicePath;
                    break;
                }

                if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_045e&pid_006d") != -1)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    devicePath = deviceInterfaceDetailData.DevicePath;
                    break;
                }

                if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_1460&pid_9150") != -1)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    devicePath = deviceInterfaceDetailData.DevicePath;
                    break;
                }

                if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_0609&pid_031d") != -1)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    devicePath = deviceInterfaceDetailData.DevicePath;
                    break;
                }
                if (deviceInterfaceDetailData.DevicePath.IndexOf("#vid_03ee&pid_2501") != -1)
                {
                    SetupDiDestroyDeviceInfoList(handle);
                    devicePath = deviceInterfaceDetailData.DevicePath;
                    break;
                }
            }

            return(devicePath);
        }
Example #42
0
        /// <summary>
        /// Ermittelt die Anzeigenamen aller Geräte einer bestimmten Art.
        /// </summary>
        /// <param name="deviceClass">Die Art des Gerätes.</param>
        /// <returns>Eine Liste aller Anzeigenamen.</returns>
        public static List<DeviceInformation> GetDeviceInformations( string deviceClass )
        {
            // Result
            var names = new List<DeviceInformation>();

            // Open enumerator
            var @class = new Guid( deviceClass );
            var hInfoList = SetupDiGetClassDevs( ref @class, IntPtr.Zero, IntPtr.Zero, 2 );
            if (hInfoList.ToInt64() == -1)
                throw new DeviceException( "Could not create Device Set" );

            // With cleanup
            try
            {
                // Create the device information data block
                var pData = new DeviceInfoData { cbSize = Marshal.SizeOf( typeof( DeviceInfoData ) ) };

                // Find them all
                for (uint ix = 0; SetupDiEnumDeviceInfo( hInfoList, ix++, ref pData );)
                {
                    // Friendly name
                    var friendly = ReadStringProperty( hInfoList, ref pData, 0 );
                    if (string.IsNullOrEmpty( friendly ))
                        continue;

                    // Hardware identifiers
                    var instance = GetInstanceId( hInfoList, ref pData );
                    if (string.IsNullOrEmpty( instance ))
                        continue;

                    // Identification
                    var idList = ReadStringListProperty( hInfoList, ref pData, 1 );

                    // Remember
                    names.Add( new DeviceInformation( friendly, instance, idList ) );
                }
            }
            finally
            {
                // Clean it
                SetupDiDestroyDeviceInfoList( hInfoList );
            }

            // Sort
            names.Sort( ( l, r ) =>
                {
                    // Friendly names
                    int delta = l.DisplayName.CompareTo( r.DisplayName );

                    // Check mode
                    if (0 == delta)
                        return l.DevicePath.CompareTo( r.DevicePath );
                    else
                        return delta;
                } );

            // Report
            return names;
        }
Example #43
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string DeviceID, PocketIndex;
            string ret = "";

            try
            {
                DeviceID    = Request.QueryString["DeviceID"];
                PocketIndex = Request.QueryString["PocketIndex"];
                //信息|用户id|实验id,实验名,实验室;
                if (string.IsNullOrEmpty(DeviceID) || string.IsNullOrEmpty(PocketIndex))//没有这两个变量
                {
                    ret = webAPIFunc.GetRetString(ErrType.MissParam);
                    Response.Write(ret);
                    return;
                }
                int index;
                if (!int.TryParse(PocketIndex, out index))
                {
                    ret = webAPIFunc.GetRetString(ErrType.ErrParam);
                    Response.Write(ret);
                    return;
                }
                if (index == 1)
                {
                    DeviceInfoData did = DeviceInfoDataDBOption.Get(DeviceID);
                    if (did == null)
                    {
                        ret = webAPIFunc.GetRetString(ErrType.NoRegDevice);
                        Response.Write(ret);
                        return;
                    }
                }
                string fileName = Global.hexBINFolder + DeviceID + ".bin";
                if (!FileOP.IsExist(fileName, FileOPMethod.File))
                {
                    ret = webAPIFunc.GetRetString(ErrType.NoHexBin);
                    Response.Write(ret);
                    return;
                }
                FileInfo f;
                f = new FileInfo(fileName);
                Stream stream = File.OpenRead(f.FullName);
                byte[] pBuf   = new byte[stream.Length];
                stream.Read(pBuf, 0, (int)stream.Length);
                stream.Close();
                if (index == 0)
                {
                    ret = webAPIFunc.GetRetString(ErrType.retOK, pBuf.Length.ToString());
                    Response.Write(ret);
                    return;
                }
                else
                {
                    int    size  = 1024 * 5; // 0480;
                    int    count = pBuf.Length / size;
                    int    left  = pBuf.Length % size;
                    int    x     = size * (index - 1);
                    string str;
                    if (index > count)//最后一包
                    {
                        //ret = ((int)ErrType.retOK).ToString() + ",";
                        str = StringsFunction.byteToHexStr(pBuf, x, left, "");
                        Response.Write(webAPIFunc.GetRetString(ErrType.retOK, str));
                        return;
                    }
                    else
                    {
                        //ret = ((int)ErrType.retOK).ToString() + ",";
                        str = StringsFunction.byteToHexStr(pBuf, x, size, "");
                        ret = ret + str;
                        //Debug.WriteLine(ret);
                        Response.Write(webAPIFunc.GetRetString(ErrType.retOK, str));
                        return;
                    }
                }
            }
            catch (System.Exception ex)
            {
                ret = webAPIFunc.GetRetString(ErrType.UnkownErr);
                TextLog.AddTextLog("GetHexData_Unkown:" + ex.Message, Global.txtLogFolder + "Update.txt", true);
            }
            Response.Write(ret);
        }
Example #44
0
 static private extern bool SetupDiSetClassInstallParams( IntPtr DeviceInfoSet, ref DeviceInfoData rData, ref PropChangeParams ClassInstallParams, UInt32 ClassInstallParamsSize );
 public static extern bool SetupDiCallClassInstaller(DiFunction installFunction,
                                                     SafeDeviceInfoSetHandle deviceInfoSet, [In()] ref DeviceInfoData deviceInfoData);
Example #46
0
 static private extern bool SetupDiCallClassInstaller( UInt32 InstallFunction, IntPtr DeviceInfoSet, ref DeviceInfoData rData );
 public static extern bool SetupDiSetClassInstallParams(SafeDeviceInfoSetHandle deviceInfoSet,
                                                        [In()] ref DeviceInfoData deviceInfoData, [In()] ref PropertyChangeParameters classInstallParams,
                                                        int classInstallParamsSize);
Example #48
0
        /// <summary>
        /// Ermittelt eine Zeichenketteneigenschaft eines Gerätes.
        /// </summary>
        /// <param name="handle">Die Referenz auf die Liste aller Geräte (einer Art).</param>
        /// <param name="info">Das gewünschte Gerät.</param>
        /// <param name="propertyIndex">Die gewünschte Eigenschaft.</param>
        /// <returns>Der Wert der Eigenschaft oder <i>null</i>.</returns>
        private static string ReadStringProperty( IntPtr handle, ref DeviceInfoData info, int propertyIndex )
        {
            // Allocate buffer
            var buffer = new byte[10000];

            // Load the name
            UInt32 charCount, regType;
            if (!SetupDiGetDeviceRegistryProperty( handle, ref info, propertyIndex, out regType, buffer, buffer.Length - 1, out charCount ))
                return null;
            else if (charCount-- > 0)
                return AnsiEncoding.GetString( buffer, 0, (int) charCount );
            else
                return null;
        }
 internal static extern bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, ref DeviceInfoData deviceInfoData, ref Guid interfaceClassGuid, int memberIndex, ref DeviceInterfaceData deviceInterfaceData);
Example #50
0
 static private extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, UInt32 MemberIndex, ref DeviceInfoData rData);
Example #51
0
 protected static extern bool SetupDiEnumDeviceInfo(IntPtr handle, int Index, ref DeviceInfoData deviceInfoData);
Example #52
0
        /// <summary>
        /// Ermittelt die Instanzennummer eines Gerätes.
        /// </summary>
        /// <param name="handle">Eine Geräteauflistung.</param>
        /// <param name="info">Eine Information zu dem gewünschten Gerät.</param>
        /// <returns>Die Instanzennummer oder <i>null</i>.</returns>
        private static string GetInstanceId( IntPtr handle, ref DeviceInfoData info )
        {
            // Allocate buffer
            var buffer = new byte[1000];

            // Load the name
            UInt32 charCount;
            if (!SetupDiGetDeviceInstanceId( handle, ref info, buffer, buffer.Length - 1, out charCount ))
                return null;
            else if (charCount-- > 0)
                return AnsiEncoding.GetString( buffer, 0, (int) charCount );
            else
                return null;
        }
Example #53
0
 private static extern bool SetupDiEnumDeviceInfo(
   IntPtr handle,
   int index,
   ref DeviceInfoData deviceInfoData);
Example #54
0
 static private extern bool SetupDiEnumDeviceInfo( IntPtr DeviceInfoSet, UInt32 MemberIndex, ref DeviceInfoData rData );
Example #55
0
 public static extern bool SetupDiEnumDeviceInfo(
   IntPtr handle,
   int Index,
   ref DeviceInfoData deviceInfoData);
Example #56
0
 static private extern bool SetupDiGetDeviceInstanceId( IntPtr deviceInfoSet, ref DeviceInfoData deviceInfoData, byte[] buffer, int bufferSize, out UInt32 requiredSize );
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceInformationElement"/> class.
 /// </summary>
 /// <param name="guid">
 /// The guid.
 /// </param>
 /// <param name="deviceInformationSetHandle">
 /// The device Information Set Handle.
 /// </param>
 /// <param name="deviceInfoData">
 /// The device info data.
 /// </param>
 /// <param name="unsafeNativeMethodsWrapper">
 /// The unsafe Native Methods Wrapper.
 /// </param>
 public DeviceInformationElement(Guid guid, IntPtr deviceInformationSetHandle, DeviceInfoData deviceInfoData, IUnsafeNativeMethodsWrapper unsafeNativeMethodsWrapper)
 {
     DeviceInterfaces = unsafeNativeMethodsWrapper.GetDeviceInterfaces(deviceInformationSetHandle, deviceInfoData, guid);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            string DeviceID, PocketIndex;
            string ret = webAPIFunc.GetRetString(ErrType.UnkownErr);

            try
            {
                DeviceID    = Request.QueryString["DeviceID"];
                PocketIndex = Request.QueryString["PocketIndex"];
                //信息|用户id|实验id,实验名,实验室;
                if (string.IsNullOrEmpty(DeviceID) || string.IsNullOrEmpty(PocketIndex))//没有这两个变量
                {
                    ret = webAPIFunc.GetRetString(ErrType.MissParam);
                    Response.Write(ret);
                    return;
                }
                int index;
                if (!int.TryParse(PocketIndex, out index))
                {
                    ret = webAPIFunc.GetRetString(ErrType.ErrParam);
                    Response.Write(ret);
                    return;
                }
                if (index == 1)
                {
                    DeviceInfoData did = DeviceInfoDataDBOption.Get(DeviceID);
                    if (did == null)
                    {
                        ret = webAPIFunc.GetRetString(ErrType.NoRegDevice);
                        Response.Write(ret);
                        return;
                    }
                }
                DataTable dt   = UpdateDataDBOption.SoftDataTableSelect();
                byte[]    data = (byte [])dt.Rows[0][1];
                if (index == 0)
                {
                    ret = "1," + data.Length.ToString();
                    Response.Write(ret);
                    return;
                }
                else
                {
                    int    size  = 2048 * 5; // 0480;
                    int    count = data.Length / size;
                    int    left  = data.Length % size;
                    int    x     = size * (index - 1);
                    string str;
                    if (index > count)//最后一包
                    {
                        ret = "1,";
                        str = StringsFunction.byteToHexStr(data, x, left, "");
                        Response.Write(ret + str);
                        return;
                    }
                    else
                    {
                        ret = "1,";
                        str = StringsFunction.byteToHexStr(data, x, size, "");
                        ret = ret + str;
                        Debug.WriteLine(ret);
                        Response.Write(ret);
                        return;
                    }
                }
            }
            catch (System.Exception ex)
            {
                ret = webAPIFunc.GetRetString(ErrType.UnkownErr);
                TextLog.AddTextLog("GetSoftData_Unkown:" + ex.Message, Global.txtLogFolder + "Update.txt", true);
            }
            Response.Write(ret);
        }
Example #59
0
 /// <summary>
 /// Ermittelt eine Zeichenkettenlisteneigenschaft eines Gerätes.
 /// </summary>
 /// <param name="handle">Die Referenz auf die Liste aller Geräte (einer Art).</param>
 /// <param name="info">Das gewünschte Gerät.</param>
 /// <param name="propertyIndex">Die gewünschte Eigenschaft.</param>
 /// <returns>Der Wert der Eigenschaft oder <i>null</i>.</returns>
 private static string[] ReadStringListProperty( IntPtr handle, ref DeviceInfoData info, int propertyIndex )
 {
     // Load as string
     var separatedString = ReadStringProperty( handle, ref info, propertyIndex );
     if (string.IsNullOrEmpty( separatedString ))
         return null;
     else
         return separatedString.Split( '\0' );
 }
Example #60
0
 protected static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, UInt32 MemberIndex, ref DeviceInfoData DeviceInfoData);