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.
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.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();
}
}
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.
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.
Couple of things you can try