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.
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.
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.
You can use the with statement. The with statement will automatically close ser and text_file when execution leaves the with statement.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With