Skip to content

Commit

Permalink
Fix writing I2C messages when I2C addr >= 0x80
Browse files Browse the repository at this point in the history
Since strings in python3 are UTF-8, calling chr() on an I2C address
>= 0x80 would create an invalid UTF-8 character (0x80 to 0xFF are
illegal). Then later, when encode() was called in add_string(), a
UnicodeEncodeError exception would be thrown because of this.

This adds a new add_bytes() method to the Telegram class for adding
bytes objects. Then, this new method is used in ls_write() so that
we can pass arbitrary I2C addresses without error.
  • Loading branch information
dlech committed Apr 28, 2018
1 parent 9851bee commit da50b41
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 3 deletions.
2 changes: 1 addition & 1 deletion nxt/direct.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def ls_write(opcode, port, tx_data, rx_bytes):
tgram.add_u8(port)
tgram.add_u8(len(tx_data))
tgram.add_u8(rx_bytes)
tgram.add_string(len(tx_data), tx_data)
tgram.add_bytes(tx_data)
return tgram

def ls_read(opcode, port):
Expand Down
4 changes: 2 additions & 2 deletions nxt/sensor/digital.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def _i2c_command(self, address, value, format):
a tuple of values corresponding to the given format.
"""
value = struct.pack(format, *value)
msg = chr(self.I2C_DEV) + chr(address) + value
msg = bytes((self.I2C_DEV, address)) + value
now = time()
if self.last_poll+self.poll_delay > now:
diff = now - self.last_poll
Expand All @@ -109,7 +109,7 @@ def _i2c_query(self, address, format):
module. See http://docs.python.org/library/struct.html#format-strings
"""
n_bytes = struct.calcsize(format)
msg = chr(self.I2C_DEV) + chr(address)
msg = bytes((self.I2C_DEV, address))
now = time()
if self.last_poll+self.poll_delay > now:
diff = now - self.last_poll
Expand Down
3 changes: 3 additions & 0 deletions nxt/telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ def bytes(self):
def is_reply(self):
return self.typ == Telegram.TYPE_REPLY

def add_bytes(self, b):
self.pkt.write(pack('%ds' % len(b), b))

def add_string(self, n_bytes, v):
self.pkt.write(pack('%ds' % n_bytes, v.encode('windows-1252')))

Expand Down

0 comments on commit da50b41

Please sign in to comment.