]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - bin/battery.pl
c7e812ea505798b07702cd6e5567be56c58b8991
[config/dotfiles.git] / bin / battery.pl
1 #!/usr/bin/perl
2
3 # Copyright (C) 2011-2013  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 my $charging = '';
61 if ($battery{STATUS} eq 'Charging' or $battery{STATUS} eq 'Full') {
62     $charging = '^';
63 }
64
65 # GNU screen mode with colors: 0-20 red, 20-40 yellow, 40-100 green.
66 if ($screen_mode) {
67     my $color;
68     if ($charge < 20) {
69         $color = 'b r';
70     } elsif ($charge < 40) {
71         $color = 'b y';
72     } else {
73         $color = 'b g';
74     }
75
76     print "\005{+$color}$charge%\005{-}$charging\n";
77
78 # Same in tmux mode.
79 } elsif ($tmux_mode) {
80     my $color;
81     if ($charge < 20) {
82         $color = 'red';
83     } elsif ($charge < 40) {
84         $color = 'yellow';
85     } else {
86         $color = 'green';
87     }
88
89     print "#[fg=$color,bold]$charge%#[default]$charging\n";
90
91 # Plain text output.
92 } else {
93     print "$charge%$charging\n";
94 }