|
33 | 33 | import platform |
34 | 34 | import fcntl |
35 | 35 | import array |
| 36 | +from struct import unpack |
36 | 37 |
|
37 | 38 | #------------------------------------------------------------------------------ |
38 | 39 | # Guess platform we are running on |
@@ -1222,6 +1223,58 @@ def value(self, n=0): |
1222 | 1223 | else: |
1223 | 1224 | return 0 |
1224 | 1225 |
|
| 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 | + |
1225 | 1278 | #~autogen generic-class classes.i2cSensor>currentClass |
1226 | 1279 |
|
1227 | 1280 | class I2cSensor(Sensor): |
|
0 commit comments