简体   繁体   English

Windows 上的串行 (COM) 端口重新连接

[英]Serial (COM)-Port reconnect on Windows

I'm writing a small software connecting to an Arduino or Teensy via Serial.我正在编写一个通过串行连接到 Arduino 或 Teensy 的小软件。 I want the software to realize if the USB-Serial is deconnected and automatically reconnect when its plugged in again.我希望软件能够识别 USB 串口是否断开连接,并在再次插入时自动重新连接。

This is pretty simple under Linux, but I'm not even sure it is possible with Windows, since all the Terminal programs I found can't reconnect to a COM port after it has been disconnected without restarting.这在 Linux 下非常简单,但我什至不确定 Windows 是否可行,因为我发现的所有终端程序在断开连接而不重新启动后都无法重新连接到 COM 端口。

I'm currently using the QT5 QSerialPort implementation, but if someone knows of a C++ class that is able to properly reconnect without restarting the programm, I'd change in a second.我目前正在使用 QT5 QSerialPort 实现,但是如果有人知道可以在不重新启动程序的情况下正确重新连接的 C++ 类,我会立即更改。

Also if someone knows a serial terminal programm that can automatically reconnect, I'd greatly appreciate an answer.另外,如果有人知道可以自动重新连接的串行终端程序,我将不胜感激。

edit I'm using 64-Bit Win7 with usually 32-Bit programs.编辑我使用 64 位 Win7 和通常 32 位程序。

The point is that when the connected device to the serial port gets disconnected, you will receive null in the readline so if it's null, you attempt to reconnect.关键是当连接到串行端口的设备断开连接时,您将在 readline 中收到 null,因此如果它为 null,您将尝试重新连接。 Also, you need to set a timeout, otherwise readline will just wait forever.此外,您需要设置超时,否则 readline 将永远等待。 Python example:蟒蛇示例:

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()

Easier on Powershell:在 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()

This script prints - when not able to connect and + when connected, the speed is fixed at 57600, you may change it.此脚本打印 - 无法连接时 + 连接时,速度固定为 57600,您可以更改它。

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM