Saturday, January 10, 2009

OS X: How to detect whether you're on battery from the shell

Sometimes you need to determine programatically whether a computer is on battery or on AC. For example, I have a backup script that takes hourly snapshots of my home directory on my MacBook Pro (which I hopefully will post about at some point). However, I don't want the script to run if I'm on battery. Ideally, launchd, which kicks off the script, could give me this option, but I don't think it can. I'll have to let the script make the decision when it gets executed.

If I were writing the script for Linux, I'd have it look through /proc/acpi/ to check the state of the battery. There's no /proc in OS X. There is, however, a power management command, pmset.

If I run pmset -g while on AC, I get:

Currently drawing from 'AC Power'
-InternalBattery-0 100%; AC attached; not charging

If I run it while on battery, I get:

Currently drawing from 'Battery Power'
-InternalBattery-0 100%; discharging; (no estimate)

I simply have my script grep the output from pmset for "discharging":

checkBattery()
{
local ret=0;
if $PMSET -g batt | $GREP -q discharging;
then
ret=1;
fi
return $ret;
}

See the pmset(1) manpage for more info.