device-hid: Incorrect remaining capacity if UP_DEVICE_HID_REMAINING_CAPACITY is not in percentage

Handling of the UP_DEVICE_HID_REMAINING_CAPACITY seem to assume that the value is always in percentage. This is unfortunately not always the case, since other units like mAh and mWh are also supported.

This leads to problems where Ubuntu reports "fully charged" batteries, even if the actual charge level is much lower. Example with 3 batteries with RemainingCapacity=100 mAh and FullChargeCapacity=1000 mAh that implies 10% charge are incorrectly reported as 100%:
image

HID power specification

According to the HID Power Device spec the RemainingCapacity parameter (UsagePage=0x85 and UsageID=0x66) as well as other capacity parameters are given in the unit specificed by the CapacityMode parameter (UsagePage=0x85 and UsageID=0x2c). CapacityMode "0" means milli-Ampere-hour (mAh), "1" means milli-Watt-hour (mWh) and "2" means percentage.

Suggestion

The simplest way to fix this problem would probably be change the logic into returning the fraction between RemainingCapacity and FullChargeCapacity (UsagePage=0x85 and UsageID=0x67). That way, the capacity would still be reported in percentage by upower, so that client code don't need to be updated. You can probably assume FullChargeCapacity=100 if not set, so that percentage is still the default unit.

Example figure to illustrate how to compute battery percentage (retrieved from the somewhat related ACPI speficication):
image

Example project to reproduce

Arduino battery emulator: https://github.com/forderud/HidBattery

Edited by Fredrik Orderud