]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - bin/battery.pl
bin/battery.pl,setup.sh: Support different battery devices names.
[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 if (scalar @ARGV != 1 and (scalar @ARGV != 2 or not $ARGV[0] =~ /-[st]/)) {
24     print STDERR "Usage: $0 [-s | -t] <path/to/device>\n";
25     print STDERR "\n";
26     print STDERR "Normally this is /sys/class/power_supply/BAT*.\n";
27     exit 1;
28 }
29 if (scalar @ARGV == 1) {
30     @ARGV = ('', $ARGV[0]);
31 }
32
33 my $path = "$ARGV[1]/uevent";
34
35 # No battery available.
36 if (not -e $path) {
37     print STDERR "'$path' not found.\n";
38     exit 1;
39 }
40
41 my $screen_mode = ($ARGV[0] eq '-s');
42 my $tmux_mode   = ($ARGV[0] eq '-t');
43
44 my %battery;
45
46 open my $file, '<', $path or die $!;
47 while (<$file>) {
48     /^POWER_SUPPLY_([A-Z_]+)=(.+)$/;
49     $battery{$1} = $2;
50 }
51 close $file or die $!;
52
53 # New names ...
54 if (defined $battery{ENERGY_NOW}) {
55     $battery{CHARGE_NOW}  = $battery{ENERGY_NOW};
56     $battery{CHARGE_FULL} = $battery{ENERGY_FULL};
57 }
58
59 my $charge = int($battery{CHARGE_NOW} / $battery{CHARGE_FULL} * 100);
60
61 # GNU screen mode with colors: 0-20 red, 20-40 yellow, 40-100 green.
62 if ($screen_mode) {
63     my $color;
64     if ($charge < 20) {
65         $color = 'b r';
66     } elsif ($charge < 40) {
67         $color = 'b y';
68     } else {
69         $color = 'b g';
70     }
71
72     print "\005{+$color}$charge%\005{-}\n";
73
74 # Same in tmux mode.
75 } elsif ($tmux_mode) {
76     my $color;
77     if ($charge < 20) {
78         $color = 'red';
79     } elsif ($charge < 40) {
80         $color = 'yellow';
81     } else {
82         $color = 'green';
83     }
84
85     print "#[fg=$color,bold]$charge%#[default]\n";
86
87 # Plain text output.
88 } else {
89     print "$charge%\n";
90 }