Last active
February 19, 2023 03:42
-
-
Save lachesis/8de84a7095cb8493053d49e6069862c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# Only requirement: pip install pyusb | |
# Run as root | |
# Might need to detach from the kernel driver? | |
import sys | |
import json | |
import usb.core | |
import usb.util | |
def init(dev): | |
try: | |
dev.detach_kernel_driver(0) | |
except usb.core.USBError as e: | |
if e.errno == 2: | |
pass # might not be attached, no need to throw | |
else: | |
raise | |
# set the active configuration. With no arguments, the first | |
# configuration will be the active one | |
dev.set_configuration() | |
def getCommand(cmd): | |
cmd = cmd.encode('utf-8') + b'\r' | |
while len(cmd)<8: # pad | |
cmd = cmd+b'\0' | |
return cmd | |
def sendCommand(dev, cmd): | |
dev.ctrl_transfer(0x21, 0x9, 0x200, 0, cmd) | |
def getResult(dev, timeout=100): | |
res="" | |
i=0 | |
while '\r' not in res and i<200: | |
try: | |
res+="".join([chr(i) for i in dev.read(0x81, 8, timeout) if i!=0x00]) | |
except usb.core.USBError as e: | |
if e.errno == 110: | |
pass | |
else: | |
raise | |
i+=1 | |
return res | |
def parseQGS(res): | |
lst = res.strip('(').strip().split(' ') | |
labels = ['voltsin', 'hertzin', 'voltsout', 'hertzout', 'loadamps', 'loadpercent', 'unk1', 'unk2', 'voltsbatt', 'unk3', 'temperature', 'flags'] | |
dd = {x: y for (x, y) in zip(labels,lst)} | |
dd = {x: y for (x, y) in dd.items() if y != '---.-'} | |
return dd | |
def main(): | |
# find our device | |
devs = list(usb.core.find(idVendor=0x0665, idProduct=0x5161, find_all=True)) | |
# was it found? | |
if not devs: | |
raise ValueError('Device not found') | |
for dev in devs: | |
init(dev) | |
if len(sys.argv) > 1: | |
# For debugging, run whatever command you want | |
sendCommand(dev, getCommand(sys.argv[1])) | |
print(getResult(dev)) | |
else: | |
# By default, run QGS for basic monitoring | |
sendCommand(dev, getCommand('QGS')) | |
print(json.dumps(parseQGS(getResult(dev)))) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment