win32file serial port madness...

Chris Liechti cliechti at gmx.net
Mon Oct 7 20:21:25 EDT 2002


blipoh at mail.com (Jason) wrote in 
news:be72b3c0.0210071241.2f9a6f31 at posting.google.com:

> I have been using pySerial for a while (a great package I might add),

thanks

> and I was wondering if somebody could help me with something that it
> doesn't seem to do. I was wondering if it is possible to read data
> from the comm port "file" and then either put it back in the buffer or
> reset the file pointer so that the next thing read will be the same as
> what was just read.

put it back in the read buffer of the OS might be a bit tricky, but you can 
wrap the Serial class and do buffered read on your own.

something like that untested bit of code below. it reads only one character 
at first, that is for blocking IO (without timeout). as soon as there is 
one character, the rest of the OS read buffer is read out too, which should 
make the reading a bit more efficient that reading single bytes.
if you want to use it with timeout, then the code below needs a little 
modification (inspecting what read gives back and bail out on empty 
string).

the data (buffer) is stored in a list, which makes appending a bit more 
efficient than working with strings.

###
import serial

class BufferedReader(serial.Serial):
    def __init__(self, *args, **kwargs):
        self.buffer = []
        serial.Serial.__init__(self, *args, **kwargs)
    
    def read(self, size):
        while len(self.buffer) < size:
            #block
            self.buffer.append(serial.Serial.read(self, 1))    	    	 
            #and get what's there
            self.buffer.extend(list(
                 serial.Serial.read(self, self.inWaiting())))  
        #take the requested amount from the buffer
        a, self.buffer = self.buffer[:size], self.buffer[size:] 
        return ''.join(a)
    
    def pushback(self, what):
        #append
    	   self.buffer = list(what) + self.buffer

###
this implementation is not thread save. but real thread safety with 
pushback operation is (almost?) impossible anyway.

chris

> What I need to do is detect the "No carrier" message from a modem. So
> if anyone has an easier way to do that than just reading in the data
> on a set interval and checking it, that information would be greatly
> appreciated.

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list