我最近一直在使用SerialPort类.目前我正在试图找出检查设备是否连接到我的应用程序使用的comm端口的正确方法.有没有正确的方法来检查设备是否连接到通信端口?我目前的方法如下:
while (isReading == true)
{
try
{
received += serialPort.ReadExisting();
if (received.Contains('>'))
isReading = false;
}
catch (Exception e)
{
}
if (tick == 10000)
if (received == "")
{
Console.WriteLine("No Data Received. Device isn't connected.");
isReading = false;
}
tick++;
}
Console.WriteLine(received);
Run Code Online (Sandbox Code Playgroud)
它有效,但我觉得它有点hacky和不可靠.如果需要,我可以保留它,但是如果有适当的替代方法,我会喜欢它.
编辑:我实际上必须将刻度值设置为大约10,000,以确保它是可靠的.否则我偶尔会收到数据.即使将其设置为1000或5000也是不可靠的.即使这样,也不能保证在多台机器上可靠.
Sim*_*mon 10
我也需要使用串口,相信我他们很痛苦.我检查设备是否连接的方法通常围绕发出轮询命令.虽然你的方法可能有用,但我不能帮助但是当事件足够时不愿意使用while循环.
.NET串口类提供了一些有用的事件:
Serial.DataReceived Serial.ErrorReceived 和 Serial.Write
通常我会以指定的间隔发出轮询命令以确保设备已连接.当设备响应时,它将触发DataReceived事件,您可以相应地处理响应(以及任何其他必要数据).这可以与简单的Timer或递增变量结合使用来为响应计时.请注意,您需要适当地设置ReadTimeout和WriteTimeout值.这ReadExisting与/和/或ReadLine方法一起可能在您的DataReceived事件处理程序中使用.
总而言之,(伪代码)
Send Polling command, Start Timer
Timer to CountDown for a specified time
If Timer fires, then assume no response
If DataRecieved fires (and expected response) assume connection
(of course handle any specific Exceptions (e.g TimeOutException, InvalidOperationException)
Run Code Online (Sandbox Code Playgroud)