WIP: uniproc
[hband-tools.git] / admin-tools / check-battery
blob88cd8107f74bdc5a3170ff07bcf36c034cc803c4
1 #!/usr/bin/env perl
3 $0 =~ s/^.*\/([^\/]+)$/$1/;
5 if(not $ENV{'BATTERY_LOW_ACTION'})
7 die "$0: Set BATTERY_LOW_ACTION environment to a command.\n";
9 if(not $ENV{'BATTERY_TIME_THRESHOLD'} and not $ENV{'BATTERY_PERCENTAGE_THRESHOLD'})
11 die "$0: Set BATTERY_TIME_THRESHOLD and/or BATTERY_PERCENTAGE_THRESHOLD environment to at most how many remaining sec or percentage will trigger the action.\n";
13 if(not $ENV{'MIN_UPTIME'})
15 die "$0: Set MIN_UPTIME environment to prevent firing action shortly after reboot.\n";
19 open my $fh, '/proc/uptime' or die "$0: $!";
20 ($uptime) = <$fh> =~ /(\d+)/;
21 close $fh;
23 if($uptime <= $ENV{'MIN_UPTIME'})
25 exit 0;
29 $highest_remaining_sec = undef;
30 $highest_percent = undef;
33 open my $pipe, '-|', 'acpi', '-b' or die "$0: $!";
34 while(<$pipe>)
36 if(/(\d\d+):(\d\d):(\d\d) remaining/)
38 my ($hour, $min, $sec) = ($1, $2, $3);
39 my $remaining_sec = $hour * 3600 + $min * 60 + $sec;
40 if($remaining_sec > $highest_remaining_sec)
42 $highest_remaining_sec = $remaining_sec;
43 $highest_remaining_time = "$hour:$min:$sec";
46 if(/(\d+)%/)
48 my $percent = $1;
49 if($percent > $highest_percent)
51 $highest_percent = $percent;
55 close $pipe;
58 $message = sprintf "remaining percentage: %s%%, remaining time: %s.", $highest_percent // "unknown", $highest_remaining_time // "unknown";
59 $fire_action = 0;
61 if($ENV{'BATTERY_TIME_THRESHOLD'} and defined $highest_remaining_sec and $highest_remaining_sec <= $ENV{'BATTERY_TIME_THRESHOLD'})
63 $message .= " Remaining time less than $ENV{'BATTERY_TIME_THRESHOLD'} sec.";
64 $fire_action = 1;
66 if($ENV{'BATTERY_PERCENTAGE_THRESHOLD'} and defined $highest_percent and $highest_percent <= $ENV{'BATTERY_PERCENTAGE_THRESHOLD'})
68 $message .= " Less than $ENV{'BATTERY_PERCENTAGE_THRESHOLD'}% left.";
69 $fire_action = 1;
72 if($fire_action)
74 my $command = $ENV{'BATTERY_LOW_ACTION'};
75 warn "$0: $message Running '$command'.\n";
76 system $command;
78 else
80 warn "$0: $message No action.\n";