问题描述
我最近一直在使用 SerialPort 类.目前我正在尝试找出检查设备是否连接到我的应用程序使用的通信端口的正确方法.是否有任何正确的方法来检查设备是否连接到通信端口?我目前的方法如下:
I've been working with the SerialPort class a lot lately. Currently I'm trying to figure out the proper way to check if a device is connected to the comm port my application uses. Is there any proper way to check if a device is connected to the comm port? My current method is as follows:
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);
它有效,但我觉得它有点老套和不可靠.如果需要,我可以保留它,但如果有合适的替代方法,我会喜欢它.
It works but I feel it's a little hacky and unreliable. I can keep it if need be but I'd like it if there's a proper alternative to doing this.
我实际上必须将刻度值设置为大约 10,000 以确保它是可靠的.否则我有时无法接收数据.即使将其设置为 1000 或 5000 也不可靠.即使这样,也不能保证在多台机器上可靠.
I actually have to set the tick value to about 10,000 to ensure it's reliable. Otherwise I fail to receive data on occasion. Even setting it to 1000 or 5000 is unreliable. Even then, it's not guaranteed to be reliable across multiple machines.
推荐答案
我也需要使用串口,相信我他们很痛苦.我检查设备是否连接的方法通常围绕发出轮询命令.虽然您的方法可能有效,但当事件足够时,我不情愿使用 while 循环.
I too need to work with serial ports, and believe me they are a pain. My method to check if a device is connected usually revolves around issuing a polling command. While you method may work, I cant help but be reluctant to use a while loop when an event will suffice.
.NET 串行端口类提供了一些有用的事件:
The .NET serial port class offers some useful events:
Serial.DataReceived
Serial.ErrorReceived
和 Serial.Write
通常我会在指定的时间间隔发出轮询命令以确保设备已连接.当设备响应时,它将触发 DataReceived
事件,您可以相应地处理响应(以及任何其他必要的数据).这可以与简单的 Timer 或递增变量结合使用,以对响应进行计时.请注意,您需要适当地设置 ReadTimeout
和 WriteTimeout
值.这与 ReadExisting
和/或 ReadLine
方法一起可能在您的 DataReceived
事件处理程序中使用.
Usually I would issue a polling command at a specified interval to ensure the device is connected.
When the device responds it will fire the DataReceived
event, and you can deal with the response accordingly (along with any other neccessary data). This can be used in conjunction with a simple Timer or incremented variable to time the response. Note you will need to set the ReadTimeout
and WriteTimeout
value appropriately. This, along with the ReadExisting
and/or ReadLine
method may be of use in your DataReceived
event handler.
总而言之,(在伪代码中)
So, to summarize, (in pseudo code)
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)
这篇关于C#串口检查设备是否已连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!