Skip to content

Commit

Permalink
Sort out some problems with hidapi USB modules
Browse files Browse the repository at this point in the history
Signed-off-by: Jim Easterbrook <jim@jim-easterbrook.me.uk>
  • Loading branch information
jim-easterbrook committed Nov 29, 2021
1 parent 87168bf commit 31519ad
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 15 deletions.
6 changes: 3 additions & 3 deletions src/pywws/__init__.py
@@ -1,3 +1,3 @@
__version__ = '21.4.0'
_release = '1690'
_commit = 'dbede59'
__version__ = '21.11.0'
_release = '1691'
_commit = '87168bf'
2 changes: 1 addition & 1 deletion src/pywws/device_ctypes_hidapi.py
Expand Up @@ -141,7 +141,7 @@ def write_data(self, buf):
:rtype: bool
"""
data = ''.join(map(chr, buf))
data = bytes(buf)
size = len(data)
if hidapi.hid_write(self.device, ctypes.c_char_p(data), size) != size:
raise IOError(
Expand Down
36 changes: 25 additions & 11 deletions src/pywws/device_cython_hidapi.py
Expand Up @@ -51,6 +51,8 @@

__docformat__ = "restructuredtext en"

from contextlib import contextmanager

import hid

class USBDevice(object):
Expand All @@ -69,8 +71,18 @@ class USBDevice(object):
def __init__(self, idVendor, idProduct):
if not hid.enumerate(idVendor, idProduct):
raise IOError("No weather station connected")
self.idVendor = idVendor
self.idProduct = idProduct
self.hid = hid.device(idVendor, idProduct)

@contextmanager
def open(self):
try:
self.hid.open(self.idVendor, self.idProduct)
yield
finally:
self.hid.close()

def read_data(self, size):
"""Receive data from the device.
Expand All @@ -87,14 +99,15 @@ def read_data(self, size):
"""
result = list()
while size > 0:
count = min(size, 8)
buf = self.hid.read(count)
if len(buf) < count:
raise IOError(
'pywws.device_cython_hidapi.USBDevice.read_data failed')
result += buf
size -= count
with self.open():
while size > 0:
count = min(size, 8)
buf = self.hid.read(count)
if len(buf) < count:
raise IOError(
'pywws.device_cython_hidapi.USBDevice.read_data failed')
result += buf
size -= count
return result

def write_data(self, buf):
Expand All @@ -109,7 +122,8 @@ def write_data(self, buf):
:rtype: bool
"""
if self.hid.write(buf) != len(buf):
raise IOError(
'pywws.device_cython_hidapi.USBDevice.write_data failed')
with self.open():
if self.hid.write(buf) != len(buf):
raise IOError(
'pywws.device_cython_hidapi.USBDevice.write_data failed')
return True

0 comments on commit 31519ad

Please sign in to comment.