Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #44261

Re: Fixing escaped characters python-xbee

From Peter Otten <__peter__@web.de>
Subject Re: Fixing escaped characters python-xbee
Date 2013-04-24 13:49 +0200
Organization None
References <704e1981-1e13-4030-b4ca-a7305ec98b32@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1018.1366804172.3114.python-list@python.org> (permalink)

Show all headers | View raw


pabloblo85@gmail.com wrote:

> I am using a XBee to receive data from an arduino network.
> 
> But they have AP=2 which means escaped characters are used when a 11 or 13
> appears (and some more...)
> 
> When this occurs, XBee sends 7D and inmediatly XOR operation with char and
> 0x20.
> 
> I am trying to recover the original character in python but I don't know
> ho to do it.
> 
> I tried something like this:
> 
> read = ser.read(4) #Read 4 chars from serial port
> for x in range (0,4):
> if(toHex(read[x]) != '7d'): #toHex converts it to hexadecimal just for
> checking purposes if(x < 3):
> read[x] = logical_xor(read[x+1], 20) #XOR
> for y in range (x+1,3):
> read[y] = read[y+1]
> read[3] = ser.read()
> else:
> read[x] = logical_xor(ser.read(), 20) #XOR
> 
> data = struct.unpack('<f', read)[0]
> 
> logical_xor is:
> 
> def logical_xor(str1, str2):
>     return bool(str1) ^ bool(str2)
> 
> I check if 7D character is in the first 3 chars read, I use the next char
> to convert it, if it is the 4th, I read another one.
> 
> But I read in python strings are inmutables and I can't change their value
> once they have one.
> 
> What would you do in this case? I started some days ago with python and I
> don't know how to solve this kind of things...

As you cannot change the old string you have to compose a new one. I think 
the simplest approach is to always read one byte, and if it's the escape 
marker read another one and decode it. The decoded bytes/chars are then 
stored in a list and finally joined:

# Python 2
# untested
def read_nbytes(ser, n):
    accu = []
    for i in xrange(n):
        b = ser.read(1)
        if b == "\x7d":
            b = chr(ord(ser.read(1)) ^ 0x20)
        accu.append(b)
    return "".join(accu)

b = read_nbytes(ser, 4)
data = struct.unpack('<f', b)[0]

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Fixing escaped characters python-xbee pabloblo85@gmail.com - 2013-04-24 00:33 -0700
  Re: Fixing escaped characters python-xbee MRAB <python@mrabarnett.plus.com> - 2013-04-24 11:53 +0100
  Re: Fixing escaped characters python-xbee Peter Otten <__peter__@web.de> - 2013-04-24 13:49 +0200
  Re: Fixing escaped characters python-xbee Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-04-24 20:29 -0400
    Re: Fixing escaped characters python-xbee pabloblo85@gmail.com - 2013-04-26 01:17 -0700

csiph-web