Skip to content

Commit 1364eef

Browse files
committed
Implement Sensor.bin_data method
See ddemidov/ev3dev-lang-python#4
1 parent 5442a28 commit 1364eef

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

ev3dev.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import platform
3434
import fcntl
3535
import array
36+
from struct import unpack
3637

3738
#------------------------------------------------------------------------------
3839
# Guess platform we are running on
@@ -1222,6 +1223,58 @@ def value(self, n=0):
12221223
else:
12231224
return 0
12241225

1226+
@property
1227+
def bin_data_format(self):
1228+
"""
1229+
Returns the format of the values in `bin_data` for the current mode.
1230+
Possible values are:
1231+
1232+
- `u8`: Unsigned 8-bit integer (byte)
1233+
- `s8`: Signed 8-bit integer (sbyte)
1234+
- `u16`: Unsigned 16-bit integer (ushort)
1235+
- `s16`: Signed 16-bit integer (short)
1236+
- `s16_be`: Signed 16-bit integer, big endian
1237+
- `s32`: Signed 32-bit integer (int)
1238+
- `float`: IEEE 754 32-bit floating point (float)
1239+
"""
1240+
return self.get_attr_string('bin_data_format')
1241+
1242+
1243+
def bin_data(self, fmt=None):
1244+
"""
1245+
Returns the unscaled raw values in the `value<N>` attributes as raw byte
1246+
array. Use `bin_data_format`, `num_values` and the individual sensor
1247+
documentation to determine how to interpret the data.
1248+
1249+
Use `fmt` to unpack the raw bytes into a struct.
1250+
Example:
1251+
>>> from ev3dev import *
1252+
>>> ir = InfraredSensor()
1253+
>>> ir.value()
1254+
28
1255+
>>> ir.bin_data('<b')
1256+
(28,)
1257+
"""
1258+
1259+
if '_bin_data_size' not in self.__dict__:
1260+
self._bin_data_size = {
1261+
"u8": 1,
1262+
"s8": 1,
1263+
"u16": 2,
1264+
"s16": 2,
1265+
"s16_be": 2,
1266+
"s32": 4,
1267+
"float": 4
1268+
}.get(self.bin_data_format, 1) * self.num_values
1269+
1270+
f = self._attribute_file('bin_data', 'rb')
1271+
f.seek(0)
1272+
raw = bytearray(f.read(self._bin_data_size))
1273+
1274+
if fmt is None: return raw
1275+
1276+
return unpack(fmt, raw)
1277+
12251278
#~autogen generic-class classes.i2cSensor>currentClass
12261279

12271280
class I2cSensor(Sensor):

0 commit comments

Comments
 (0)