PDA

View Full Version : battery percentage




Blarged
Apr 23, 2008, 02:01 PM
Hi, looking for a light-weight method of getting the current battery charge left percentage. To determine whether the computer is running of AC or DC power I use the IOPSGetProvidingPowerSourceType, however, I am struggling with the battery percentage.

I have also considered using pmset -g ps but would prefer a C++ solution... any ideas?

I am not entirely certain how to go about using...
kIOPSCurrentCapacityKey and kIOPSMaxCapacityKey



Blarged
Apr 23, 2008, 05:32 PM
I got it...

thanks to: http://lists.omnipotent.net/pipermail/lcdproc/2006-January/010417.html


#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/ps/IOPowerSources.h>
#include <IOKit/ps/IOPSKeys.h>

int main (int argc, const char * argv[]) {
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);

CFDictionaryRef pSource = NULL;
const void *psValue;

int numOfSources = CFArrayGetCount(sources);
if (numOfSources == 0) return 1;

for (int i = 0 ; i < numOfSources ; i++)
{
pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
if (!pSource) return 2;

psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));

int curCapacity = 0;
int maxCapacity = 0;
int percent;

psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);

psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);

percent = (int)((double)curCapacity/(double)maxCapacity * 100);

printf ("powerSource %d of %d: percent: %d/%d %d\n", i, CFArrayGetCount(sources), curCapacity, maxCapacity, percent);

}

return 0;
}


for my attempt to make it as light-weight as possible, this is the final function:

int BatteryAC::GetBatteryPercent(int *piBatteryPercent)
{

CFTypeRef blob = IOPSCopyPowerSourcesInfo();
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);

CFDictionaryRef pSource = NULL;
const void *psValue;

if (CFArrayGetCount(sources) == 0)
return 0; // Could not retrieve battery information. System may not have a battery.

pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));

int curCapacity = 0;
int maxCapacity = 0;
int percent;

psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);

psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);

*piBatteryPercent = (int)((double)curCapacity/(double)maxCapacity * 100);

if (piBatteryPercent < 0 || piBatteryPercent > 100)
return -1; // Could not retrieve the battery information
else
return 1; // Success
}