Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retry firmware query if payload seems implausibly small #16

Merged
merged 2 commits into from
Feb 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 33 additions & 15 deletions temper.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,38 @@ def _parse_bytes(self, name, offset, divisor, bytes, info):
except:
return

def _read_hidraw_firmware(self, fd, verbose = False):
''' Get firmware identifier'''
query = struct.pack('8B', 0x01, 0x86, 0xff, 0x01, 0, 0, 0, 0)
if verbose:
print('Firmware query: %s' % binascii.b2a_hex(query))

# Sometimes we don't get all of the expected information from the
# device. We'll retry a few times and hope for the best.
# See: https://github.com/urwen/temper/issues/9
for i in range(0, 10):
os.write(fd, query)

firmware = b''
while True:
r, _, _ = select.select([fd], [], [], 0.2)
if fd not in r:
break
data = os.read(fd, 8)
firmware += data

if not len(firmware):
os.close(fd)
raise RuntimeError('Cannot read device firmware identifier')

if len(firmware) > 8:
break

if verbose:
print('Firmware value: %s %s' %(binascii.b2a_hex(firmware), firmware.decode()))

return firmware

def _read_hidraw(self, device):
'''Using the Linux hidraw device, send the special commands and receive the
raw data. Then call '_parse_bytes' based on the firmware version to provide
Expand All @@ -142,21 +174,7 @@ def _read_hidraw(self, device):
path = os.path.join('/dev', device)
fd = os.open(path, os.O_RDWR)

# Get firmware identifier
os.write(fd, struct.pack('8B', 0x01, 0x86, 0xff, 0x01, 0, 0, 0, 0))
firmware = b''
while True:
r, _, _ = select.select([fd], [], [], 0.1)
if fd not in r:
break
data = os.read(fd, 8)
firmware += data

if firmware == b'':
os.close(fd)
return { 'error' : 'Cannot read firmware identifier from device' }
if self.verbose:
print('Firmware value: %s' % binascii.b2a_hex(firmware))
firmware = self._read_hidraw_firmware(fd, self.verbose)

# Get temperature/humidity
os.write(fd, struct.pack('8B', 0x01, 0x80, 0x33, 0x01, 0, 0, 0, 0))
Expand Down