]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - bin/battery.pl
bin/*.pl: Add missing die to close.
[config/dotfiles.git] / bin / battery.pl
1 #!/usr/bin/perl
2
3 # Copyright (C) 2011-2012  Simon Ruderich
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18
19 use strict;
20 use warnings;
21
22
23 my $path = '/sys/class/power_supply/BAT0/uevent';
24
25 # No battery available.
26 if (! -e $path) {
27     exit 1;
28 }
29
30 my $screen_mode = (defined $ARGV[0] and $ARGV[0] eq '-s');
31 my $tmux_mode   = (defined $ARGV[0] and $ARGV[0] eq '-t');
32
33 my %battery;
34
35 open my $file, '<', $path or die $!;
36 while (<$file>) {
37     /^POWER_SUPPLY_([A-Z_]+)=(.+)$/;
38     $battery{$1} = $2;
39 }
40 close $file or die $!;
41
42 my $charge = int($battery{CHARGE_NOW} / $battery{CHARGE_FULL} * 100);
43
44 # GNU screen mode with colors: 0-20 red, 20-40 yellow, 40-100 green.
45 if ($screen_mode) {
46     my $color;
47     if ($charge < 20) {
48         $color = 'b r';
49     } elsif ($charge < 40) {
50         $color = 'b y';
51     } else {
52         $color = 'b g';
53     }
54
55     print "\005{+$color}$charge%\005{-}\n";
56
57 # Same in tmux mode.
58 } elsif ($tmux_mode) {
59     my $color;
60     if ($charge < 20) {
61         $color = 'red';
62     } elsif ($charge < 40) {
63         $color = 'yellow';
64     } else {
65         $color = 'green';
66     }
67
68     print "#[fg=$color,bold]$charge%#[default]\n";
69
70 # Plain text output.
71 } else {
72     print "$charge%\n";
73 }