USB-C Power Metering with the ChargerLAB KM003C: A Google Twinkie Alternative?
API Access on Windows
Custom user programs and scripts to access the data from the KM003C are comparatively easier to create on Windows compared to Linux. One of the primary reasons is that ChargerLAB supplies a HID demo program (ZIP) on its technical support page. It includes a VisualStudio 2019 project with C++ source code to access the data from the device. The KM003C also presents itself as an USB device as well as a serial device to the OS. In the ideal case, we should have seen the latter interface even in Linux as /dev/ttyACM0, but that was not the case in our Ubuntu install.
Powershell is my preferred scripting language on Windows machines, and accessing the KM003C as a serial device is as simple as opening the appropriate COM device output in the above command. As mentioned in the API document, the baud rate and other parameters do not matter.
The command to be sent over the serial port for getting the ADC data (the 32-bit word, 0x0C000200) is prepared. Similar to libusb, the device write function expects a UTF-8 string. Unlike libusb, the read function is not blocking. In order to avoid polling for the data, or waiting for a pre-defined amount of time (by which there is no guarantee that the read might have returned the data from the device or not), a Powershell event is set up to trigger whenever data is received on the opened port.
The read out process is isolated out into a script block, and the logic to compute the instantaneous and averaged power consumption is similar to what was done using Python on Linux. The main difference is that we wait for the event triggered by the data receipt before the call to the read from the port.
The script block is called in a loop every 100ms and generates output that is similar to the one created by the Python script in the previous section - CSV strings with a timestamp, followed by instantaneous voltage, current, and power, and the averaged versions of the same.
The clean-up process involves closing the port and deregistering / removing the event set up to track the data receipt from the port.
Originally published at https://www.anandtech.com/show/18944/usbc-power-metering-with-the-chargerlab-km003c-a-google-twinkie-alternative (Wayback Machine).




