Skip to content

Instantly share code, notes, and snippets.

@kloneets
Created February 18, 2016 13:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kloneets/a6eba5b65f603774bf67 to your computer and use it in GitHub Desktop.
Save kloneets/a6eba5b65f603774bf67 to your computer and use it in GitHub Desktop.
USB Relay switching through HID
import hid
import re
class Relay:
def __init__(self, debug=False):
# USBrelay<relay-count>
self.vendor_id = 0x16c0
self.product_id = 0x05df
self.debug = debug
self.ON = 0xff
self.OFF = 0xfd
self.devices = hid.enumerate(self.vendor_id, self.product_id)
self.device = hid.device()
self.verbose('Opening device')
try:
self.device.open(self.vendor_id, self.product_id)
except IOError as e:
print(e)
def verbose(self, txt):
if self.debug is True:
print(txt)
def close(self):
self.device.close()
def get_channels(self):
match = re.search('(\d+)$', self.device.get_product_string())
self.verbose('Found ' + match.group(0) + ' relay switches')
return match.group(0)
def toggle(self, channel):
if self.is_on(channel):
self.off(channel)
else:
self.on(channel)
def on(self, channel):
buf = (0x0, self.ON, channel, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
self.device.write(buf)
def off(self, channel):
buf = (0x0, self.OFF, channel, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
self.device.write(buf)
def is_on(self, channel):
fr = self.device.get_feature_report(channel, 8)
state = fr[7]
if state == 0:
return False
if channel == 1:
if state == 1 or state == 3:
return True
else:
return False
if channel == 2:
if state == 2 or state == 3:
return True
else:
return False
@staticmethod
def print_all_devices():
for d in hid.enumerate():
keys = list(d.keys())
keys.sort()
for key in keys:
print(repr(key).ljust(25), ':', d[key])
print("---------------------------------------------------------")
def print_relays(self):
for d in hid.enumerate(self.vendor_id, self.product_id):
keys = list(d.keys())
keys.sort()
for key in keys:
print(repr(key).ljust(25), ':', d[key])
print("---------------------------------------------------------")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment