How can I discover if a device is connected to a specific serial (COM) port?

↘锁芯ラ 提交于 2019-12-13 01:30:28

问题


How can I discover, using C#'s SerialPort class, whether a device is connected to a specific serial (COM) port?

Note: that class's Open method opens the port even if there is no device connected to the port.


回答1:


The answer depends on the device and the cable.

In some cases, DSR (SerialPort.DsrHolding) or even CTS (SerialPort.CtsHolding) will be raised when the device is connected.

But in some cases you may only have Tx / Rx connected, and the only way to tell is to attempt to communicate with the device.

You need to look at the documentation for your device and its cable.

There's no general solution that works for any device.




回答2:


1.WMI: SELECT * FROM Win32_SerialPort:

ManagementObjectSearcher manObjSearch = new ManagementObjectSearcher("Select * from Win32_SerialPort");
ManagementObjectCollection manObjReturn = manObjSearch.Get();

foreach (ManagementObject manObj in manObjReturn)
{
    //int s = manObj.Properties.Count;
    //foreach (PropertyData d in manObj.Properties)
    //{
    //    Console.WriteLine(d.Name);
    //}
    Console.WriteLine(manObj["DeviceID"].ToString());
    Console.WriteLine(manObj["Name"].ToString());
    Console.WriteLine(manObj["Caption"].ToString());
}

2. If device send response back: System.IO.Ports.SerialPort.GetPortNames() and sending basic command:

foreach (string portname in SerialPort.GetPortNames())
{
    var sp = new SerialPort(portname, 4800, Parity.Odd, 8, StopBits.One);
    try
    {
        sp.Open();
        sp.Write("Your known command to device");
        Thread.Sleep(500);
        string received = sp.ReadLine();

        if (received == "expected response")
        {
            Console.WriteLine("device connected to: " + portname);
            break;
        }
    }
    catch (Exception)
    {
        Console.WriteLine("device NOT connected to: " + portname);
    }
    finally
    {
        sp.Close();
    }
}



回答3:


Couple of things you can try

  1. Create Serial port object and open a port, now when a device is connected, OS should send CDChanged event.
  2. You ping the serial port, and if you receive a response back, assume it is connected.



回答4:


You can do it by opening serial port and sending most basic command your device support and check the response. For example for GSM modem you open port and sent at command and receive ok in response.



来源:https://stackoverflow.com/questions/12813151/how-can-i-discover-if-a-device-is-connected-to-a-specific-serial-com-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!