Python Forum
Python3 - serial port reload
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python3 - serial port reload
#1
Question 
I am having a problem reading/writing to a serial port after the port has been disconnected. I can successfully connect to my device and communicate with it. Then I execute a voluntary disconnect, I reopen the port but I am unable to write/read. Is it possible to reload the port without restarting the script?

The ttyACM* port has an active symlink connection in /etc/udev/rules.d/99-usb-serial.rules:
SUBSYSTEM=="tty", ATTRS{idVendor}=="1234", ATTRS{idProduct}=="5678", SYMLINK+="ttyACM_dev0"
To open the port:
#!/usr/bin/python3 python3
# -*- coding: utf-8 -*-

import serial
global ser0

# open the dev0 serial port
try:
    ser0 = serial.Serial("/dev/ttyACM_dev0")
    ser0.isOpen()
except serial.serialutil.SerialException:
    ser0 = None
else:
    print (ser0.name, 'port opened successfully')
The error usually is like:
Error:
ser1.flushOutput() # Clear output buffer File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 587, in flushOutput self.reset_output_buffer() File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 604, in reset_output_buffer termios.tcflush(self.fd, termios.TCOFLUSH) termios.error: (5, 'Input/output error')
Reply
#2
your symlink points to ttyACM_dev0, therefore, if closed elsewhere, the symlink is also closed.
you need to reissue serial.Serial("/dev/ttyACM_dev0") in order to reopen.

I suggest you create an open, and a close function (def) so it can be called as required.
Reply
#3
(Apr-07-2021, 04:38 PM)Larz60+ Wrote: your symlink points to ttyACM_dev0, therefore, if closed elsewhere, the symlink is also closed.
you need to reissue serial.Serial("/dev/ttyACM_dev0") in order to reopen.
1

Actually in my case the the device is found at ttyACM0 at first. After disconnecting and reconnecting, the device is found at ttyACM1. Regardless of the port number, the symlink is always ttyACM_dev0. Even if I reissue the serial.Serial("/dev/ttyACM_dev0") still there is no communication.

Is it perhaps necessary to delete and re-import all the modules for serial port handling (serial, serialutil and serialposix) and refresh the memory allocation variables?
Reply
#4
I don't know if there's anything useful in the following code, but perhaps.
I wrote it to connect to an Arduino UNO, some of the code (commented) was from a github account, some of my own.
# ArduinoSerial.py
# Author: Larz60+
# Detect available serial ports, open and close same
# License MIT license see MIT_license.txt
#
from ArPaths import ArPaths
import sys
import glob
import serial


class ArduinoSerial:
    def __init__(self, baudrate=9600, serialport=None, serialtimeout=2, sstream=None):
        self.Apath = ArPaths()
        self.baud = baudrate
        self.port = serialport
        self.timeout = serialtimeout
        self.sstream = sstream

    def setport(self):
        if self.port is None:
            ports = glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*")
            print(f"ports: {ports}")
            self.port = ports[0]

    def OpenSerialPort(self):
        self.setport()
        print(f"self.port: {self.port}")
        self.sstream = serial.Serial(self.port, self.baud, timeout=self.timeout)
        print(f"self.sstream: {self.sstream}")
        return self.sstream

    def CloseSerialPort(self):
        self.sstream.close()

    def find_serial_ports(self):
        """
            Source for this code: https://gist.github.com/tekk/5c8d6824108dfb771a1e16aa8bc479f0

            Lists serial port names

            :raises EnvironmentError:
                On unsupported or unknown platforms
            :returns:
                A list of the serial ports available on the system
        """
        if sys.platform.startswith('win'):
            ports = ['COM%s' % (i + 1) for i in range(256)]
        elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
            # this excludes your current terminal "/dev/tty"
            ports = glob.glob('/dev/tty[A-Za-z]*')
        elif sys.platform.startswith('darwin'):
            ports = glob.glob('/dev/tty.*')
        else:
            raise EnvironmentError('Unsupported platform')

        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass

        return result


def main():
    aser = ArduinoSerial()
    ports = aser.find_serial_ports()
    print(f"Ports (find): {ports}")
    aser.OpenSerialPort()
    aser.CloseSerialPort()


if __name__ == '__main__':
    main()
output of internal test:
Output:
Ports (find): ['/dev/ttyACM0'] ports: ['/dev/ttyACM0'] self.port: /dev/ttyACM0 self.sstream: Serial<id=0x7faf12c0b0a0, open=True>(port='/dev/ttyACM0', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2, xonxoff=False, rtscts=False, dsrdtr=False)
Reply
#5
By following the flow I came to the error
Error:
Attempting to use a port that is not open
. I guess this error is related to the fact I use multiple script in separate files that use the same ports. I posted this problem also on StackOverflow.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  MCU reboots after opening Serial port when ran from Raspberry PI zazas321 3 334 Mar-19-2024, 09:02 AM
Last Post: zazas321
  Waiting for input from serial port, then move on KenHorse 2 834 Oct-17-2023, 01:14 AM
Last Post: KenHorse
  pyserial/serial "has no attribute 'Serial' " gowb0w 9 3,331 Aug-24-2023, 07:56 AM
Last Post: gowb0w
  Serial Port As Global Prasanjith 2 1,422 Mar-23-2023, 08:54 PM
Last Post: deanhystad
  python serial port barryjo 2 1,603 Dec-27-2021, 11:09 PM
Last Post: barryjo
  is there a way to mention port range or search for port dynamically with qConnection Creepy 0 1,451 Sep-09-2021, 03:15 PM
Last Post: Creepy
  How to Properly Open a Serial Port in a Function bill_z 2 4,352 Jul-22-2021, 12:54 PM
Last Post: bill_z
  Unable to read from serial port br0kenpixel 1 2,428 Aug-08-2020, 10:03 PM
Last Post: Larz60+
  Read Data from Serial Port PA3040 3 3,130 Feb-16-2020, 04:54 AM
Last Post: PA3040
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 4,823 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020