PMbwmon bandwidth monitor: can specify which interfaces to watch, also supporting...
[hband-tools.git] / admin-tools / check-battery
blobf41998d3ba4691f838b3b34f73a57e3eb61b47d5
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;
31 $batteries_with_sufficient_charge = 0;
34 open my $pipe, '-|', 'acpi', '-ab' or die "$0: $!";
35 while(<$pipe>)
37 chomp;
38 $remaining_sec = undef;
39 $remaining_time = undef;
40 $percent = undef;
41 my $battery_has_sufficient_charge = 1;
43 if(/Adapter.*on-line/)
45 warn "$0: $_: No action.\n";
46 exit 0;
48 if(/(\d\d+):(\d\d):(\d\d) remaining/)
50 my ($hour, $min, $sec) = ($1, $2, $3);
51 $remaining_sec = $hour * 3600 + $min * 60 + $sec;
52 if($remaining_sec > $highest_remaining_sec)
54 $highest_remaining_sec = $remaining_sec;
55 $highest_remaining_time = "$hour:$min:$sec";
58 if(/(\d+)%/)
60 $percent = $1;
61 if($percent > $highest_percent)
63 $highest_percent = $percent;
67 if($ENV{'BATTERY_TIME_THRESHOLD'} and defined $remaining_sec and $remaining_sec <= $ENV{'BATTERY_TIME_THRESHOLD'})
69 $battery_has_sufficient_charge = 0;
71 if($ENV{'BATTERY_PERCENTAGE_THRESHOLD'} and defined $percent and $percent <= $ENV{'BATTERY_PERCENTAGE_THRESHOLD'})
73 $battery_has_sufficient_charge = 0;
75 if($battery_has_sufficient_charge)
77 $batteries_with_sufficient_charge++;
80 close $pipe;
83 $message = sprintf "remaining percentage: %s%%, remaining time: %s, batteries with enough capacity: %d.", $highest_percent // "unknown", $highest_remaining_time // "unknown", $batteries_with_sufficient_charge;
86 if($batteries_with_sufficient_charge < 1)
88 my $command = $ENV{'BATTERY_LOW_ACTION'};
89 warn "$0: $message Running '$command'.\n";
90 system $command;
92 else
94 warn "$0: $message No action.\n";