[Tutor] Parsing control characters from serial port

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 26 Apr 2001 12:46:09 +0200


On  0, kromag@nsacom.net wrote:
> I have had some success with grabbing strings from '/dev/ttyS0' by using 
> readline(). It works just like I would expect, i.e. it stops 'listening' when 
> a 'n' is detected.

Actually, a '\n'. That's not an n, but a newline character.

> How can I tell readline() to complete a line when another character is 
> detected? (I am listening for '0x02' FWIW)

Temporarily setting os.linesep *might* work, but then that's a Perl-style
hack that I wouldn't use. It's a global variable that you set to make your
local readline() do something it wasn't intended to do.

It probably doesn't work either. Make your own function!

> Basically the device on the other end of the serial port talks like this:
> 
> 0x02    #Listen up! I have news for you!
> (string of characters)
> 0x03    #I'm Done!
> 
> Since readline() opens the serial port and listens intently without need for a 
>  wake-up call, it won't be any big deal to strip the initial '0x02' off, but 
> ending the message on '0x03' is confusing me. Do I need to somehow tell 
> readlines() 'n'?
> 
> is there a way to tell python that for the purposes of this function '0x03' == 
> 'n'?
> 
> I have tried to come up with some sort of garble that does
> 
> while string contents != 0x03
> read it all in and put it here
> else n
> 
> (Sorry, I am not at my home machine and lunch is short!)

You can read character by character using read(). If there's nothing on the
serial line atm (EOF), it returns '', but you still have to keep reading
until the rest is there, until the 0x03.

Something like 

def read_serial_line(file):
   c = file.read(1)
   if c != '\x02':
       raise IOError, "Input expected to start with 0x02"
   sofar = []
   while 1:
       c = file.read(1)
       if not c:
          continue
       if c == '\x03':
          return "".join(sofar)
       sofar.append(c)

-- 
Remco Gerlich