Search code examples
macospython-3.xserial-portpyserialpexpect

Reading serial output from Pyserial doesnt work reliably


I am connecting to device using code blow on MacOS and out of 100 times this code would make connection only 1 or two times and dones't respond(since there is no timeout) rest of the times.

ser = serial.Serial(port="/dev/xyz",timeout = None, baudrate=115200, parity = serial.PARITY_NONE, bytesize = serial.EIGHTBITS, stopbits = serial.STOPBITS_ONE)

def exitSer(ser):
    print("Closing")
    ser.close()

atexit.register(exitSer, ser)

if ser.is_open:
    time.sleep(2)
    while(1):
        print(ser.readline().decode("utf-8"))

Could you please tell me how to use programs like fcntl etc to find if this port is completely free and available for use and how to set tty port's flags to free after making port free forcibly.

Once this works, I have to run this multithreaded where each thread is running different devices expecting output in lines. Any suggestions for that just in case this works.


Solution

  • def startSerial(tty_id):
        ser = serial.Serial(port = tty_id, timeout = None)
        ser.close()
        ser.open()
        if ser.isOpen():
            print(ser.portstr, ":connection successful.")
            return ser
        else:
            return False
    

    Calling ser.close() before .open() fixed it. I tested it about 200 times and i haven't been dissappointed so far. I am testing it now in multithreaded and hopefully that works too.

    Thank you everybody.