Mathias
Mathias

Reputation: 1500

Serial (COM)-Port reconnect on Windows

I'm writing a small software connecting to an Arduino or Teensy via Serial. I want the software to realize if the USB-Serial is deconnected and automatically reconnect when its plugged in again.

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.

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.

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.

Upvotes: 0

Views: 3131

Answers (2)

Garfius
Garfius

Reputation: 57

Easier on 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.

Hope it helps.

Upvotes: 1

Dreo
Dreo

Reputation: 229

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. Also, you need to set a timeout, otherwise readline will just wait forever. 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()

Upvotes: 1

Related Questions