The following is part of a procedure I have written which sends a command to an ECU and expects to read back 107 raw bytes which are not terminated with \n or similar.
def send_packet(data):
ser = serial.Serial(serial_port, 10400, timeout=0.1)
ser.write(data)
time.sleep(0.11) #wait 110ms until all data is received
read_val = ser.read(107)
return read_val
read_val correctly gets me all the bytes so long as I wait at least 110ms before reading the buffer.
However other commands may return widely varying number of bytes for which the above method is inelegant, may not work or rather wasteful.
How can I write a general purpose procedure which is capable of handling varying lengths with no terminating string but with a reasonable gap until the next read?