Skip to content

Instantly share code, notes, and snippets.

@holgr
Last active August 8, 2023 13:08
Show Gist options
  • Save holgr/b2bf98eb0dac081068a4e19295583f78 to your computer and use it in GitHub Desktop.
Save holgr/b2bf98eb0dac081068a4e19295583f78 to your computer and use it in GitHub Desktop.
Reading the API via Python3 and pyusb on macOS from a Power-Z KM002C
##
## As taken from AnandTech (just modified the idProduct for the older KM002C) at:
## https://www.anandtech.com/show/18944/usbc-power-metering-with-the-chargerlab-km003c-a-google-twinkie-alternative/3
##
## You might have to sudo python3 to make this work
##
import usb.core, usb.util, usb.control, timeit, time
dev = usb.core.find(idVendor=0x5fc9, idProduct=0x0061) # Power-Z KM002C
dev
##
## Didn't use this:
##
# for itf_num in range(4):
# if dev.is_kernel_driver_active(itf_num):
# dev.detach_kernel_driver(itf_num)
# usb.util.claim_interface(dev, itf_num)
cmdlist = [ 0x0c, 0x00, 0x02, 0x00 ] ;
for tctr in range(20):
t1=timeit.default_timer() * 1000;
nbytes_sent = dev.write (0x1, bytes(cmdlist).decode('utf-8'));
data = dev.read(0x81, 64);
tcurrv, tcurri, tavosv, tavosi = data[8:11], data[12:15], data[16:19], data[20:23];
currv = int.from_bytes(tcurrv, 'little') / 1000000.00;
curri = int.from_bytes(tcurri, 'little') / 1000000.00;
avosv = int.from_bytes(tavosv, 'little') / 1000000.00;
avosi = int.from_bytes(tavosi, 'little') / 1000000.00;
currp = currv * curri ; avosp = avosv * avosi;
print_tstamp = (int(t1) / 1000) ;
print_str = '{:.2f}, {:.6f}, {:.6f}, {:.6f}, {:.6f}, {:.6f}, {:.6f}'.format(
print_tstamp, currv, curri, currp, avosv, avosi, avosp)
print ('{}'.format(print_str))
t2 = timeit.default_timer()*1000;
time.sleep((100 - (t2 - t1)) / 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment