]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - bin/battery.pl
0bdaae04c1d8829a33a0edaf2e8a4fb709ae5289
[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 # New names ...
43 if (defined $battery{ENERGY_NOW}) {
44     $battery{CHARGE_NOW}  = $battery{ENERGY_NOW};
45     $battery{CHARGE_FULL} = $battery{ENERGY_FULL};
46 }
47
48 my $charge = int($battery{CHARGE_NOW} / $battery{CHARGE_FULL} * 100);
49
50 # GNU screen mode with colors: 0-20 red, 20-40 yellow, 40-100 green.
51 if ($screen_mode) {
52     my $color;
53     if ($charge < 20) {
54         $color = 'b r';
55     } elsif ($charge < 40) {
56         $color = 'b y';
57     } else {
58         $color = 'b g';
59     }
60
61     print "\005{+$color}$charge%\005{-}\n";
62
63 # Same in tmux mode.
64 } elsif ($tmux_mode) {
65     my $color;
66     if ($charge < 20) {
67         $color = 'red';
68     } elsif ($charge < 40) {
69         $color = 'yellow';
70     } else {
71         $color = 'green';
72     }
73
74     print "#[fg=$color,bold]$charge%#[default]\n";
75
76 # Plain text output.
77 } else {
78     print "$charge%\n";
79 }