C#串口检查设备是否连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17595992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:58:42  来源:igfitidea点击:

C# Serial Port Check if Device is Connected

c#serial-port

提问by DanteTheEgregore

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:

我最近一直在使用 SerialPort 类。目前,我正在尝试找出检查设备是否连接到我的应用程序使用的通信端口的正确方法。是否有任何正确的方法来检查设备是否连接到通信端口?我目前的方法如下:

            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.

它有效,但我觉得它有点笨拙且不可靠。如果需要,我可以保留它,但如果有合适的替代方法,我会喜欢它。

Edit: 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.

编辑:我实际上必须将刻度值设置为大约 10,000 以确保它可靠。否则我有时无法接收数据。即使将其设置为 1000 或 5000 也不可靠。即便如此,也不能保证它在多台机器上是可靠的。

采纳答案by Simon

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.

我也需要使用串行端口,相信我,它们很痛苦。我检查设备是否已连接的方法通常围绕发出轮询命令。虽然您的方法可能有效,但当事件足够时,我不情愿地使用 while 循环。

The .NET serial port class offers some useful events:

.NET 串行端口类提供了一些有用的事件:

Serial.DataReceivedSerial.ErrorReceivedand Serial.Write

Serial.DataReceivedSerial.ErrorReceivedSerial.Write

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 DataReceivedevent, 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 ReadTimeoutand WriteTimeoutvalue appropriately. This, along with the ReadExistingand/or ReadLinemethod may be of use in your DataReceivedevent handler.

通常我会以指定的时间间隔发出轮询命令以确保设备已连接。当设备响应时,它将触发DataReceived事件,您可以相应地处理响应(以及任何其他必要的数据)。这可以与简单的 Timer 或递增变量结合使用,以对响应进行计时。请注意,您需要适当地设置ReadTimeoutWriteTimeout值。这与ReadExistingand/orReadLine方法一起可能在您的DataReceived事件处理程序中使用。

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)

回答by Kcvin

I would agree that is a hacky because any device could be connected and sending '>'; but that doesn't mean its your device.

我同意这是一个hacky,因为任何设备都可以连接并发送“>”;但这并不意味着它是您的设备。

Instead, be dynamic and use something like SerialPort.GetPortNamesand WMI Queriesto interrogate the devices plugged into the COM ports.

相反,应该是动态的并使用类似SerialPort.GetPortNamesWMI Queries 之类的东西来询问插入 COM 端口的设备。

You could use thisexample as a starting point.

您可以使用示例作为起点。

After reading documentation and examples, you should be able to create a list of all device information that registers drivers on the computer and their connected COM port.

阅读文档和示例后,您应该能够创建所有设备信息的列表,用于在计算机上注册驱动程序及其连接的 COM 端口。

Edit:

编辑:

Since the device doesn't register itself, consider looking at the product driversfor Visual Studio that might make your job a lot easier.

由于设备不会自行注册,请考虑查看Visual Studio的产品驱动程序,这可能会使您的工作更轻松。

回答by Rubixus

Unfortunately with serial ports, there's no proper way to determine if a certain device is connected. You could write a magic message that only your device would respond correctly to, but as described in this answer, this method could cause problems for other connected devices.

不幸的是,对于串行端口,没有正确的方法来确定某个设备是否已连接。您可以编写一条只有您的设备才能正确响应的神奇消息,但如本答案所述,此方法可能会导致其他连接的设备出现问题。

Ultimately, you just have to depend on the user selecting the correct port.

最终,您只需要依靠用户选择正确的端口即可。

Also, if you happen to lose connection to the device, you would only know when you fail to read/write to it. In this case, just throw a LostConnection event.

此外,如果您碰巧失去了与设备的连接,您只会知道何时无法读取/写入它。在这种情况下,只需抛出一个 LostConnection 事件。