Change serial timeout per read

rowan at sylvester-bradley.org rowan at sylvester-bradley.org
Thu May 10 08:16:45 EDT 2007


> you will probably have to make the port non blocking, and roll your own
> using different time.sleep(n) values between invocations to port.read(1) calls

What I actually want to do is to respond immediately if the expected
string comes in, but not raise a timeout unless it takes longer than
the maximum time. So if the device I'm communicating with usually
responds in a second, but _can_ take up to 20 seconds, I don't want to
do a sleep(20) then read the port since this will slow everything down
a lot in an average world. I want to keep checking for the expected
string, and act upon it as soon as I've got it, only raising a timeout
if I haven't got it after 20 seconds. I guess to do this using non-
blocking calls I have to do something like:
    timesofar = 0
    returnstring = port.read(1)
    while len(returnstring)<expectedlength:
        if timesofar >= timeout:
            raise SerialException('Timeout')
        time.sleep(checkportinterval)
        timesofar += checkpointinterval
        returnstring += port.read(1)

This seems rather messy. What I've tried this morning is to produce a
modified version of uspp with a second optional timeout parameter in
its read() function. If this is present, the timeout given is sent to
the port using SetCommTimeouts(). If it's not present, the timeouts
specified when the port was opened are sent. At first sight, with
minimal testing on Windows, this seems to be working, and will leave
my application code a lot cleaner than the non-blocking plus sleep
approach. Of course I don't know whether my method will work on Linux,
and there may be problems I haven't found yet.

Rowan




More information about the Python-list mailing list