Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 398
Ketil Avatar asked Aug 09 '10 04:08

Ketil


People also ask

What does timeout mean in PySerial?

timeout = None : wait forever / until requested number of bytes are received. timeout = 0 : non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes.

Is PySerial the same as serial?

PySerial is a library which provides support for serial connections ("RS-232") over a variety of different devices: old-style serial ports, Bluetooth dongles, infra-red ports, and so on.

How do you exit a serial in Python?

You can use the with statement. The with statement will automatically close ser and text_file when execution leaves the with statement.


1 Answers

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')
like image 181
pyInTheSky Avatar answered Sep 19 '22 14:09

pyInTheSky