且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查设备是否已连接

更新时间:2023-11-26 09:40:34

大多数答案提出2种方法:

Most of the answers propose 2 approaches:

  1. 在代码的某些地方,通过串行发送某种消息,以检查您的设备是否仍然有效
  2. 启动一个单独的线程,并通过打开通信来连续检查设备是否处于活动状态

第一个解决方案的问题是不是总是检查连接,而是仅检查某些特定点:此解决方案不是很好,如果写得不好甚至可能无法正常工作

The problem with the first solution is that you are not always checking the connection, but only checking in some specific points: this solution isn't very elegant and if badly written could even be not working.

第二种解决方案解决了第一种解决方案的问题,但引入了一个新问题:在线程循环中检查连接或最差的发送消息会导致问题,甚至可能中断其他功能与设备的连接.

The second solution solves the problem of the first solution, but introduces a new problem: checking the connection, or worst sending a message, in a threaded loop will cause problem or may even interrupt the connection to the device from other functions.

一种解决方案,允许您不断检查连接而不会独占通信,这涉及读取现有的COM:

A solution that allows you to constantly check the connection without monopolizing the communication involves the reading of the existing COM:

import serial.tools.list_ports
myports = [tuple(p) for p in list(serial.tools.list_ports.comports())]
print myports

输出:

[(u'COM3', u'Arduino Due Programming Port (COM3)', u'some more data...'),
(u'COM6', u'USB Serial Port (COM6)', u'some more data...'),
(u'COM100', u'com0com - serial port emulator (COM100)', u'some more data...')]

然后我们保存包含端口的元组:

then we save the tuple that contains our port:

arduino_port = [port for port in myports if 'COM3' in port ][0]

然后我们创建一个函数来检查该端口是否仍然存在:

then we create a function that checks if this port is still present:

import time

def check_presence(correct_port, interval=0.1):
    while True:
    myports = [tuple(p) for p in list(serial.tools.list_ports.comports())]
    if arduino_port not in myports:
        print "Arduino has been disconnected!"
        break
    time.sleep(interval)

最后,我们将此功能作为守护线程运行:

At last, we run this function as a daemon thread:

import threading
port_controller = threading.Thread(target=check_presence, args=(arduino_port, 0.1,))
port_controller.setDaemon(True)
port_controller.start()

通过这种方式,您将每隔0.1秒检查arduino是否仍处于连接状态,并且当arduino断开连接或所有其他活动均已结束时,线程将结束

in this way, you'll check each 0.1 secs if the arduino is still connected, and the thread will end when arduino is disconnected or all other activities have ended