Win32/Python serial port event character problem

Peter Hansen peter at engcorp.com
Sat Jun 29 20:17:35 EDT 2002


Derek Basch wrote:
> 
> If anyone reads this and can show me a better way to
> work with serial event characters in win32 please feel
> free to :)

I second Chris' comments about using something like PySerial
and just handling this in a thread.  Event characters are
probably non-portable, while you could easily write code
with PySerial that runs under Linux or Windows.

But give it time... you definitely didn't give it enough time
before you reposted. :)

By the way, here's some typical (?) code for handling a termination 
sequence on incoming data for something like this (while inside of
some kind of serial port object):

def read(self, timeout=None):
    buf = self.leftover
    self.leftover = ''

    while true:
        data = FUNCTION_TO_READ_A_RAW_BLOB_OF_DATA()

        # if new data received, add to the buffer and check for
        # a contained input termination sequence
        if data:

            buf = buf + data

            termIndex = string.find(buf, self.inputTerminator)
            if termIndex >= 0:
                # move past the terminator
                termIndex = termIndex + len(termIndex)

                # preserve anything lying after input termination 
                # sequence in the leftover buffer for next time
                buf, self.leftover = buf[:termIndex], buf[termIndex:]

                break

    return buf

Each time you call it, it reads raw data and adds it to a buffer
which it then rescans for the termination sequence.  If the buffer
contains the sequence, it splits it on that and returns everything
up to and including the sequence, preserving everything after it 
for the next call.

-Peter



More information about the Python-list mailing list