2013-02-20 2 views
2

이 프로그램에서는 먼저 availalbe 포트에 연결하려고합니다. 발견 및 연결되면 연결된 USB 장치 ID 및 공급 업체 ID를 읽고 싶습니다. 어떻게합니까?직렬 포트 장치 ID를 얻으려면 어떻게해야합니까?

친절 감사는

Program() 
    { 

     // Get a list of serial port names. 
     string[] ports = SerialPort.GetPortNames(); 

     // Search for the right port. 
     foreach (string port in ports) 
     { 
      _serialPort = new SerialPort(port, 250000, Parity.None, 8, StopBits.One); 
      _serialPort.Handshake = Handshake.None; 
      _serialPort.ReadTimeout = 300; 
      _serialPort.WriteTimeout = 300; 

      try 
      { 
       _serialPort.Open(); 
       break; 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Serial port " + port + ": " + e.Message); 
      } 
     } 
     /* ENTER CODE TO GET ID HERE */ 

     Console.WriteLine("Using: " + _serialPort.PortName); 
     Console.WriteLine("Device ID: " + _serialPort.DeviceID); 
+3

직렬 포트로부터 수집 하였다. –

+0

가능한 [장치가 직렬 또는 블루투스에 연결되어 있는지를 알아야 함] (http://stackoverflow.com/questions/3659939/need-to-know-whether-a-device-is-wired-serial-or-) 블루투스) –

+0

몇 가지 추가 정보를 추가하려면 다음과 같이하십시오.이 게시물을 작성할 때 공급 업체 ID 또는 장치 ID를 수신하려면 포트/연결을 열어 두어야합니다. 나는이 코드를 Windows 용으로 작성하고 있으므로 이렇게하면 Windows 등록 정보를 수집해야합니다. 나는 올바른 장치를 찾아서 실행할 수있는 코드를 acompilsh하려고합니다. – Christian

답변

4

나는 마침내 자신 며칠 전에 정리되었다. 두 부분으로 하나는 레지스트리를 확인하고 다른 하나는 장치의 vid/pid를 확인합니다.

com0com과 같은 널 모뎀 에뮬레이터를 캡처하지 않도록하기 위해 사용하는 레지스트리 방법입니다.

/// <summary> 
    /// Removes any comm ports that are not explicitly defined as allowed in ALLOWED_TYPES 
    /// </summary> 
    /// <param name="allPorts">reference to List that will be checked</param> 
    /// <returns></returns> 
    private static void nullModemCheck(ref List<string> allPorts) 
    { 
     // Open registry to get the COM Ports available with the system 
     RegistryKey regKey = Registry.LocalMachine; 

     // Defined as: private const string REG_COM_STRING ="HARDWARE\DEVICEMAP\SERIALCOMM"; 
     regKey = regKey.OpenSubKey(REG_COM_STRING); 

     Dictionary<string, string> tempDict = new Dictionary<string, string>(); 
     foreach (string p in allPorts) 
      tempDict.Add(p, p); 

     // This holds any matches we may find 
     string match = ""; 
     foreach (string subKey in regKey.GetValueNames()) 
     { 
      // Name must contain either VCP or Seial to be valid. Process any entries NOT matching 
      // Compare to subKey (name of RegKey entry) 
      if (!(subKey.Contains("Serial") || subKey.Contains("VCP"))) 
      { 
       // Okay, this might be an illegal port. 
       // Peek in the dictionary, do we have this key? Compare to regKey.GetValue(subKey) 
       if(tempDict.TryGetValue(regKey.GetValue(subKey).ToString(), out match))   
       { 
        // Kill it! 
        allPorts.Remove(match); 

        // Reset our output string 
        match = ""; 
       } 

      } 

     } 

     regKey.Close(); 
    } 

VID를은/PID 부는 단지 COM 포트 USB 포트 아니다 techinpro

/// <summary> 
    /// Compile an array of COM port names associated with given VID and PID 
    /// </summary> 
    /// <param name="VID">string representing the vendor id of the USB/Serial convertor</param> 
    /// <param name="PID">string representing the product id of the USB/Serial convertor</param> 
    /// <returns></returns> 
    private static List<string> getPortByVPid(String VID, String PID) 
    { 
     String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID); 
     Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase); 
     List<string> comports = new List<string>(); 
     RegistryKey rk1 = Registry.LocalMachine; 
     RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum"); 
     foreach (String s3 in rk2.GetSubKeyNames()) 
     { 
      RegistryKey rk3 = rk2.OpenSubKey(s3); 
      foreach (String s in rk3.GetSubKeyNames()) 
      { 
       if (_rx.Match(s).Success) 
       { 
        RegistryKey rk4 = rk3.OpenSubKey(s); 
        foreach (String s2 in rk4.GetSubKeyNames()) 
        { 
         RegistryKey rk5 = rk4.OpenSubKey(s2); 
         RegistryKey rk6 = rk5.OpenSubKey("Device Parameters"); 
         comports.Add((string)rk6.GetValue("PortName")); 
        } 
       } 
      } 
     } 
     return comports; 
    } 
+0

굉장합니다. 고마워. – ppumkin

+0

이것은 실제 포트의 PID/VID가 아닌 PID/VID와 연결된 포트 목록을 생성합니다. 즉, 장치가 분리 된 경우에도 결과를 생성합니다. USB CDC/ACM 장치를 제조 할 때 장치와 관련된 포트가 여러 개 있지만, 연결된 장치의 PID/VID를 기록한 다음 장치와 연관시켜야합니다. 나는 Qt에서'QextPortInfo'를 사용했으나 이상적으로 .Net 메서드가 필요합니다. – Clifford

+0

정확합니다. 그 정보를 얻는 유일한 방법은 libusb/winusb를 사용하는 것입니다. 같은 효과를 내기 위해서는 훨씬 더 많은 노력이 필요합니다. OS가 열리기 전에 포트에 대해 알아야하기 때문에 이것이 충분하다고 생각합니다. 따라서 검색된 pid/vid는 실제로 연결할 수있는 경우 가장 최근의 것입니다. –

관련 문제