Alnitak
Alnitak

Reputation: 340055

Battery status API in macOS?

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.

Upvotes: 34

Views: 18272

Answers (5)

hd1
hd1

Reputation: 34677

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];

Upvotes: -2

Bruno
Bruno

Reputation: 7221

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

Upvotes: 0

Ben Gottlieb
Ben Gottlieb

Reputation: 85542

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).

Upvotes: 27

Gary Chambers
Gary Chambers

Reputation: 1267

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

Upvotes: 78

Terry Wilcox
Terry Wilcox

Reputation: 9040

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

Upvotes: -3

Related Questions