如何自动检测串行COM端口的连接c# [英] How to autodetect connection of serial COM port c#

查看:48
本文介绍了如何自动检测串行COM端口的连接c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有与设备通信的应用程序.设备通过串行 COM 端口连接.我的应用可以与设备通信.

I have application to communication with device. Device is connected through serial COM port. My app can comunicate with device.

我需要一些方法/事件,可以通过运行应用程序来扫描 COM 端口.当我将设备连接到 PC 时 - 方法/事件将打印带有消息已连接"或类似消息的 MessageBox.

I need some method / event, that can scan COM ports through running app. When I'll connect device to PC - method / event will print MessageBox with message "connected", or something like that.

我发现了这样的东西:

comPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

但它不起作用.

推荐答案

我不确定您是尝试自动检测设备连接到哪个端口,还是自动检测设备是否连接到特定端口.

I'm not sure if you are trying to auto-detect which port a device is connected to, or auto-detect whether a device is connected to a specific port.

不过,在这两种情况下,原理是相同的:

In both cases though, the principle is the same:

  1. 您使用以下方法枚举串行端口:SerialPort.GetPortNames 如果您需要确定端口,或者如果您已经知道端口,则跳到步骤 2
  2. 为集合中的每个端口打开一个连接,方法是为它创建一个新的 SerialPort 对象,并调用 打开
  3. 对于每个打开的连接,您尝试从端口写入/读取确定您的设备是否已连接的数据序列
  4. 对于每个打开的连接,如果数据读取超时,则没有设备连接到端口;否则,如果您得到预期的结果,您就知道您的设备已连接
  5. 对于每个端口,使用 关闭 SerialPort 对象.
  1. you enumerate the the serial ports using: SerialPort.GetPortNames if you need to determine the port, or skip to the Step 2 if you already know the port
  2. for each port in the collection you open a connection by creating a new SerialPort object for it, and by calling Open
  3. for each open connection you attempt to write/read from the port the sequence of data that determines whether your device is attached
  4. for each open connection if the data read times out then there is no device attached to the port; otherwise, if you get back what you expect you know your device is attached
  5. for each port, close the connection using Close on the SerialPort object.

在任何给定点执行上述操作将告诉您您的设备在那个点是否连接,以及它连接到哪个端口.

Performing the above at any given point will tell you whether your device is attached at that point, and which port it is attached to.

如果您需要持续进行存在检测,那么您可能需要创建一个计时器并定期执行此测试(每 30 秒或每 2 分钟 - 取决于您愿意接受的延迟).

If you need to do presence detection continuously, then you will probably want to create a timer and perform this test periodically (every 30 seconds, or every 2 minutes - depending on the latency you are willing to accept).

注意

正如其他人在答案中指出的那样,您需要异步运行串行端口检测代码,以免在扫描端口时阻塞您的主应用程序.由于未连接设​​备的端口超时,扫描肯定需要一段时间.

As others have indicated in the answers, you will want to run the serial port detection code asynchronously so as not to block your main application while scanning the ports. The scanning is guaranteed to take a while because of the time-outs of the ports that have no device attached.

这篇关于如何自动检测串行COM端口的连接c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆