Growl notifier for mac’s battery status
Tuesday, February 9th, 2010There have been many times that my macbook’s battery is almost running out and about to die and I don’t pay attention to the icon in my menubar. The warning itself appears only when the battery level is 10% remaining. Recently however, this problem started causing more pain. My battery needs to be replaced, because of which at about 23% the machine will just shutdown. So I wrote a small script that calculates the battery power and along with some launchctl magic and growl, I now get a notification when my batter level is below 30%.
Here is what you need to do. Download growl 1.2 from here and install it. If you are using Adium you will most likely already have growl. To test, run this command in your terminal after you install growl.
growlnotify -m "test message"
The code for getting the battery capacity notification is below
#! /bin/bash
NOTIFICATION_THRESHOLD="30"
#this works only on snow leopard 10.6.
charge=`/usr/sbin/ioreg -l | /usr/bin/grep -i capacity | /usr/bin/tr '\n' ' | ' | /usr/bin/awk '{printf("%.0f",$10/$5 * 100)}'`
if [ $charge -lt $NOTIFICATION_THRESHOLD ]; then
message="Battery power level is $charge%"
/usr/local/bin/growlnotify -t "BatteryNotifier" -s -m "$message"
fi
The full paths are essential for the next step. Save the above in a file, make it executable with ‘chmod +x’ and run. You will not see anything if your battery charge is above 30%. In order to run this as a cronjob or daemon process create a file of type launchd.plist in
~/Library/LaunchAgents/
and give the file a unique name. My file is named com.abuhafsa.BatteryNotifier.plist.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.abuhafsa.BatteryNotifier</string>
<key>ProgramArguments</key>
<array>
<string>/opt/scripts/daemons/battery_notifier.sh</string>
</array>
<key>StartInterval</key>
<integer>300</integer>
</dict>
</plist>
Remember to change the location of the script to where your file is stored. The ‘StartInterval’ is time in seconds. Change it to whatever you desire and the script will run at that interval. Now logout and log back, which will enable launchctl to add this daemon to its list of tasks.
