Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Laptop Battery Status in Float/Double

I have a program that reads battery status in Windows that looks like this (simplified code):

#include <iostream>
#include <windows.h>

using namespace std;

int main(int argc, char *argv[]) {
    SYSTEM_POWER_STATUS spsPwr;
    if( GetSystemPowerStatus(&spsPwr) ) {
        cout << "\nAC Status : " << static_cast<double>(spsPwr.ACLineStatus)
             << "\nBattery Status : " << static_cast<double>(spsPwr.BatteryFlag)
             << "\nBattery Life % : " << static_cast<double>(spsPwr.BatteryLifePercent)
             << endl;
        return 0;
    } else return 1;
}

spsPwr.BatteryLifePercent holds remaining battery charge in percent and is of type BYTE, which means it can only show reading in round numbers (i.e. int). I notice that an application called BatteryBar can show battery percentage in floating point value.

BatteryBar is a .NET application. How can I get battery percentage reading in float/double using pure C/C++ with Windows API? (Solution that can be compiled with MinGW is preferable)

like image 603
BootStrap Avatar asked Oct 16 '11 15:10

BootStrap


2 Answers

You can get this information using the WMI . try using the BatteryFullChargedCapacity and BatteryStatus classes both are part of the root\WMI namespace.

To get the remaining battery charge in percent just must use the RemainingCapacity (BatteryStatus) and FullChargedCapacity (BatteryFullChargedCapacity) properties.

The remaining battery charge in percent is

(RemainingCapacity * 100) / FullChargedCapacity

for example if the FullChargedCapacity property report a 5266 value and the RemainingCapacity reports a 5039, the reuslt will be 95,68932776 %

If you don't know how access the WMI from C++ read these articles

  • WMI C++ Application Examples
  • Making WMI Queries In C++
like image 77
RRUZ Avatar answered Oct 02 '22 22:10

RRUZ


Well, as you said, the Windows API provides only an integral percentage value. And, as you implied, .NET provides a floating-point one.

That means that, to use the floating-point one, you have to use .NET. That said, the .NET value is between 0.0 and 1.0, and it's not clear from the documentation whether you actually gain more precision.

like image 36
Lightness Races in Orbit Avatar answered Oct 02 '22 22:10

Lightness Races in Orbit