Skip to content

Commit d74cd58

Browse files
author
marcusw
committed
Added a bit of code to elimenate random DirProtErrors when polling digital sensors. Also did a couple cosmetic things.
1 parent ea549d8 commit d74cd58

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

nxt/sensor/digital.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1414
# GNU General Public License for more details.
1515

16-
from nxt.error import I2CError, I2CPendingError
16+
from nxt.error import I2CError, I2CPendingError, DirProtError
1717

1818
from common import *
1919
from time import sleep, time
@@ -114,11 +114,14 @@ def _i2c_query(self, address, format):
114114
sleep(self.poll_delay - diff)
115115
self.brick.ls_write(self.port, msg, n_bytes)
116116
self.last_poll = time()
117-
self._ls_get_status(n_bytes)
118-
data = self.brick.ls_read(self.port)
117+
try:
118+
self._ls_get_status(n_bytes)
119+
finally:
120+
#we should clear the buffer no matter what happens
121+
data = self.brick.ls_read(self.port)
119122
if len(data) < n_bytes:
120-
raise I2CError, 'Read failure'
121-
return struct.unpack(format, data[-n_bytes:]) # TODO: why could there be more than n_bytes?
123+
raise I2CError, 'Read failure: Not enough bytes'
124+
return struct.unpack(format, data[-n_bytes:])
122125

123126
def read_value(self, name):
124127
"""Reads a value from the sensor. Name must be a string found in
@@ -128,7 +131,12 @@ def read_value(self, name):
128131
tuples containing only one element.
129132
"""
130133
address, fmt = self.I2C_ADDRESS[name]
131-
return self._i2c_query(address, fmt)
134+
for n in range(3):
135+
try:
136+
return self._i2c_query(address, fmt)
137+
except DirProtError:
138+
pass
139+
raise I2CError, "read_value timeout"
132140

133141
def write_value(self, name, value):
134142
"""Writes value to the sensor. Name must be a string found in

0 commit comments

Comments
 (0)