Skip to content

Commit 0873f27

Browse files
committed
Retrieve battery charge information on Darwin
1 parent 657f8c7 commit 0873f27

1 file changed

Lines changed: 34 additions & 2 deletions

File tree

darwin/Platform.c

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ in the source distribution for its full text.
4949
#include "SysArchMeter.h"
5050
#include "TasksMeter.h"
5151
#include "UptimeMeter.h"
52+
#include "XUtils.h"
5253
#include "darwin/DarwinMachine.h"
5354
#include "darwin/PlatformHelpers.h"
5455
#include "generic/fdstat_sysctl.h"
@@ -732,8 +733,39 @@ void Platform_getBattery(BatteryInfo* info) {
732733

733734
if (cap_max > 0.0) {
734735
info->percent = 100.0 * cap_current / cap_max;
735-
info->energyCurr = cap_current;
736-
info->energyFull = cap_max;
736+
}
737+
738+
io_service_t batt = IOServiceGetMatchingService(iokit_port, IOServiceMatching("AppleSmartBattery"));
739+
if (batt) {
740+
CFNumberRef voltRef = IORegistryEntryCreateCFProperty(batt, CFSTR("Voltage"), kCFAllocatorDefault, 0);
741+
CFNumberRef currCapRef = IORegistryEntryCreateCFProperty(batt, CFSTR("AppleRawCurrentCapacity"), kCFAllocatorDefault, 0);
742+
CFNumberRef maxCapRef = IORegistryEntryCreateCFProperty(batt, CFSTR("AppleRawMaxCapacity"), kCFAllocatorDefault, 0);
743+
744+
if (currCapRef && maxCapRef && voltRef) {
745+
double currMAh = 0.0;
746+
CFNumberGetValue(currCapRef, kCFNumberDoubleType, &currMAh);
747+
748+
double maxMAh = 0.0;
749+
CFNumberGetValue(maxCapRef, kCFNumberDoubleType, &maxMAh);
750+
751+
double voltMV = 0.0;
752+
CFNumberGetValue(voltRef, kCFNumberDoubleType, &voltMV);
753+
754+
/* Approximate energy from charge and current battery voltage: mAh * mV / 1e6 = Wh. */
755+
if (maxMAh > 0.0 && voltMV > 0.0) {
756+
info->energyCurr = CLAMP(currMAh, 0.0, maxMAh) * voltMV / 1e6;
757+
info->energyFull = maxMAh * voltMV / 1e6;
758+
}
759+
}
760+
761+
if (maxCapRef)
762+
CFRelease(maxCapRef);
763+
if (currCapRef)
764+
CFRelease(currCapRef);
765+
if (voltRef)
766+
CFRelease(voltRef);
767+
768+
IOObjectRelease(batt);
737769
}
738770

739771
cleanup:

0 commit comments

Comments
 (0)