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