pythonpyserial

Python PySerial read-line timeout


I'm using pyserial to communicate with a embedded devise.

ser = serial.Serial(PORT, BAUD, timeout = TOUT)
ser.write(CMD)
z = ser.readline(eol='\n')

So we send CMD to the device and it replies with an string of varing length ending in a '\n'

if the devise cant replay then readline() times-out and z=''

if the devise is interrupted or crashes will it's sending the data then readline() times-out and z will be a string without a '\n' at the end.

Is there a nice way to check if readline() has timed-out other than checking the state of z.


Solution

  • I think what you might like to do is..

    import re
    import time
    import serial
    
    def doRead(ser,term):
        matcher = re.compile(term)    #gives you the ability to search for anything
        tic     = time.time()
        buff    = ser.read(128)
        # you can use if not ('\n' in buff) too if you don't like re
        while ((time.time() - tic) < tout) and (not matcher.search(buff)):
           buff += ser.read(128)
    
        return buff
    
    if __name__ == "__main__":
        ser = serial.Serial(PORT, BAUD, timeout = TOUT)
        ser.write(CMD)
        print doRead(ser,term='\n')