Battery status API in macOS?
Asked Answered
C

5

34

How can I read the status of the battery on my MacBookPro from my own application?

Googling has so far only revealed APIs for device drivers to handle power events - there's nothing about user-land processes accessing this information.

thanks.

Chasteen answered 7/11, 2008 at 16:4 Comment(0)
S
27

You'll want to use IOKit for this, specifically the IOPowerSources functions. You can use IOPSCopyPowerSourcesInfo() to get a blob, and IOPSCopyPowerSourcesList() to then extract a CFArray out of that, listing the power sources. Then use IOPSGetPowerSourceDescription() to pull out a dictionary (see IOPSKeys.h for the contents of the dictionary).

Stauder answered 7/11, 2008 at 17:9 Comment(0)
S
78

If you're looking for a quick way to query it from the command line, you'll find the pmset command helpful. To query the battery status, specifically, use:

$ pmset -g batt
Stud answered 22/6, 2009 at 3:14 Comment(3)
And this is particularly useful when using your Mac remotely via SSH. It's good to know if you need to sprint over to it to connect to the AC!Byrle
curious that this got so many upvotes, when it's explicitly an API call I was looking for (per the answer I accept)Chasteen
Plausibly because the question title/tags doesn't distinguish between scripts/CLI and compiled contexts, so many (like myself) find a trivially wrappable answer more useful than an answer that requires me to drop into a specific compiled lang.Alchemy
S
27

You'll want to use IOKit for this, specifically the IOPowerSources functions. You can use IOPSCopyPowerSourcesInfo() to get a blob, and IOPSCopyPowerSourcesList() to then extract a CFArray out of that, listing the power sources. Then use IOPSGetPowerSourceDescription() to pull out a dictionary (see IOPSKeys.h for the contents of the dictionary).

Stauder answered 7/11, 2008 at 17:9 Comment(0)
A
0

Maybe help extracted text into script app

pmset -g batt | head -n 1 | cut -c19- | rev | cut -c 2- | rev

output

Battery Power
AC Power
Agustinaah answered 19/9, 2019 at 21:28 Comment(0)
M
-2

For Objective-C, this works to get the current percentage:

NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/pmset -g batt |  perl -ne ' print \"$1\n\" if /([0-9]+%)/'";
NSPipe *pipe = [NSPipe pipe];
task.standardOutput = pipe;
[task launch];
NSData *data = [pipe availableData];
Muzz answered 4/5, 2022 at 0:15 Comment(0)
G
-3

Look at the System Management Controller. I don't have my MBP handy, but I believe you need to look at smc.h

Giana answered 7/11, 2008 at 17:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.