[英]How can I discover if a device is connected to a specific serial (COM) port?
如何使用C#的SerialPort
類發現設備是否連接到特定的串行(COM)端口?
注意:即使沒有設備連接到該端口,該類的Open
方法也會打開該端口。
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.如果設備將響應發送回: System.IO.Ports.SerialPort.GetPortNames()
並發送基本命令:
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();
}
}
答案取決於設備和電纜。
在某些情況下,連接設備時,將引發DSR( SerialPort.DsrHolding
)甚至CTS( SerialPort.CtsHolding
)。
但是在某些情況下,您可能只連接了Tx / Rx,並且唯一的告訴方法是嘗試與設備進行通信。
您需要查看設備及其電纜的文檔。
沒有適用於任何設備的通用解決方案。
您可以通過打開串行端口並發送設備支持的最基本命令並檢查響應來完成。 例如,對於GSM調制解調器,您打開端口並在命令處發送,然后收到ok作為響應。
您可以嘗試的幾件事
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.