[英]Serial (COM)-Port reconnect on Windows
我正在编写一个通过串行连接到 Arduino 或 Teensy 的小软件。 我希望软件能够识别 USB 串口是否断开连接,并在再次插入时自动重新连接。
这在 Linux 下非常简单,但我什至不确定 Windows 是否可行,因为我发现的所有终端程序在断开连接而不重新启动后都无法重新连接到 COM 端口。
我目前正在使用 QT5 QSerialPort 实现,但是如果有人知道可以在不重新启动程序的情况下正确重新连接的 C++ 类,我会立即更改。
另外,如果有人知道可以自动重新连接的串行终端程序,我将不胜感激。
编辑我使用 64 位 Win7 和通常 32 位程序。
关键是当连接到串行端口的设备断开连接时,您将在 readline 中收到 null,因此如果它为 null,您将尝试重新连接。 此外,您需要设置超时,否则 readline 将永远等待。 蟒蛇示例:
import serial
import threading
import time
class MainTHread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._data = ""
self.ser = None
def run(self):
while(True):
try:
time.sleep(1)
ser = serial.Serial('COM3',9600,timeout=2)
except serial.SerialException as err:
print("Connection failed")
try:
ser.close()
except UnboundLocalError:
print("No Serial")
print(err)
continue
while True:
try:
print("Trying to read")
data_json = ser.readline()
self._data =data_json.decode('UTF-8');
if(not self._data):
break
print("Main Thread " + self._data)
except serial.SerialException as err:
print("Connection failed")
ser.close()
break
def getData(self):
return self._data
thread = MainTHread()
thread.start()
在 Powershell 上更容易:
function triaComPort(){
$selection = [System.IO.Ports.SerialPort]::getportnames()
If($selection.Count -gt 0){
$title = "Serial port selection"
$message = "Which port would you like to use?"
# Build the choices menu
$choices = @()
For($index = 0; $index -lt $selection.Count; $index++){
$choices += New-Object System.Management.Automation.Host.ChoiceDescription $selection[$index]
}
$options = [System.Management.Automation.Host.ChoiceDescription[]]$choices
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
$selection = $selection[$result]
}
return $selection
}
$port = triaComPort
if(!$port){"Must choose";return}
Write-Host $("Port:"+$comport)
$port= new-Object System.IO.Ports.SerialPort $port,57600,None,8,one
while($true){
if(!$port.IsOpen){
try{
$port.Open()
write-host "+"
}catch{
write-host "-" -NoNewline
}
}
if($port.BytesToRead -gt 0){
Write-Host $port.ReadExisting()
}
}
$port.Close()
此脚本打印 - 无法连接时 + 连接时,速度固定为 57600,您可以更改它。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.