Skip to content

Commit

Permalink
Fix Issue ratcashdev#15 float conversion exception
Browse files Browse the repository at this point in the history
Sometimes data has spurious binary data non properly decoded from utf-8
Example:
ValueError: could not convert string to float: '53.0\x02'

This fix removes not printable characters to reduce the chances of exceptions.
  • Loading branch information
lucagiove committed Jan 6, 2020
1 parent 5ad3a2a commit 3bc08ec
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
5 changes: 4 additions & 1 deletion mitemp_bt/mitemp_bt_poller.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,12 @@ def _parse_data(self):
https://github.com/ratcashdev/mitemp/issues/2#issuecomment-406263635
"""
data = self._cache
# Sanitizing the input sometimes has spurious binary data
data = data.strip('\0')
data = ''.join(filter(lambda i: i.isprintable(), data))

res = dict()
for dataitem in data.strip('\0').split(' '):
for dataitem in data.split(' '):
dataparts = dataitem.split('=')
if dataparts[0] == 'T':
res[MI_TEMPERATURE] = float(dataparts[1])
Expand Down
10 changes: 10 additions & 0 deletions test/unit_tests/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,13 @@ def test_parsing4(self):
poller._last_read = datetime.now()
self.assertEqual(poller._parse_data()[MI_TEMPERATURE], -11.3)
self.assertEqual(poller._parse_data()[MI_HUMIDITY], 37.6)

def test_parsing5(self):
"""Does the Mi TEMP BT data parser works correctly with spurious binary data? Value: T=-11.3 H=53.0\x02"""
poller = MiTempBtPoller(None, MockBackend)
data = bytearray([0x54, 0x3d, 0x2d, 0x31, 0x31, 0x2e, 0x33, 0x20,
0x48, 0x3d, 0x35, 0x33, 0x2e, 0x30, 0x02]).decode("utf-8").strip(' \n\t')
poller._cache = data
poller._last_read = datetime.now()
self.assertEqual(poller._parse_data()[MI_TEMPERATURE], -11.3)
self.assertEqual(poller._parse_data()[MI_HUMIDITY], 53.0)

0 comments on commit 3bc08ec

Please sign in to comment.