#!/usr/bin/perl -w use strict; my $threshold = $ARGV[0]; #if no value passed to script use default check value of 15% or less #before we start with the whiny applescript warnings if (!$threshold) { $threshold = 15; } my $osascript_name = "/tmp/battery_check.scpt"; my (%plist,$msg); my @cmd_output = `/usr/sbin/ioreg -p IODeviceTree -n "battery" -w 0`; #looking for the following string: #"IOBatteryInfo" = ({"Voltage"=11925,"Flags"=4,"Amperage"=1705,"Capacity"=4149,"Current"=3717}) foreach my $line (@cmd_output) { if ($line =~ /IOBatteryInfo/i) { %plist = &formatBatteryInfo($line); } } #foreach (keys %plist) { print "$_ => $plist{$_} \n"; } #my $voltage = sprintf("%.2f", ($plist{'Voltage'}/1000)); #this calculates the remaining charge left... my $percentage = sprintf("%.1f", ($plist{'Current'}/$plist{'Capacity'})*100); $msg = "\"Voltage : $plist{'Voltage'} Amperage: $plist{'Amperage'}\"" . '& return &'; $msg .= "\"Capacity : $plist{'Capacity'} Current: $plist{'Current'}\"" . '& return & return &'; $msg .= "\"Remaining Charge : [$percentage%] \"" . '& return & return'; # need to create an adapter value - user from macosxhints suggests that this is the number 7 # i have non-standard plug, but it is greater than 7, so i'm going with the theory that anything 7+ means # the laptop is plugged in, so don't give the warning... #convert any funny numbers to a nice round int my $adapter = int($plist{'Flags'}); #print "$adapter\n"; #print "percentage: $percentage ... threshold: $threshold\n"; if (($percentage < $threshold) && ($adapter <= 7)) { #print "i need to create applescript warning\n\n"; (my $osascript = <<"eoj") =~ s/^\t+//gm; tell application "Finder" activate set myAlert to $msg display dialog myAlert buttons {"OK","Sleep"} with icon caution default button 1 if button returned of result = "Sleep" then sleep end if end tell eoj open(OUTFILE,">$osascript_name"); print OUTFILE $osascript; close(OUTFILE); system("osascript $osascript_name"); } #### SUBS ##### sub formatBatteryInfo { my %plist; my $info = shift; $info =~ s/^.+"IOBatteryInfo"([^\{]+)\{([^\}]+)\}.+/$2/i; #sample result from this regex: #"Voltage"=11572,"Flags"=4,"Amperage"=1894,"Capacity"=4149,"Current"=3298 my @name_values = split(/,/,$info); foreach my $pair (@name_values) { if ($pair =~ /"([^"]+)"\s*=\s*(.+)/) { $plist{$1} = $2; } } foreach (keys %plist) { unless($_ =~ /Flags/i) { $plist{$_} = sprintf("%.2f", ($plist{$_}/1000)); } } return %plist; }