]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - bin/battery.pl
bin/battery.pl: Add checks and correct exit code.
[config/dotfiles.git] / bin / battery.pl
1 #!/usr/bin/perl
2
3
4 use strict;
5 use warnings;
6
7
8 my $path = '/sys/class/power_supply/BAT0/uevent';
9
10 # No battery available.
11 if (! -e $path) {
12     exit 1;
13 }
14
15 my $screen_mode = (defined $ARGV[0] and $ARGV[0] eq '-s');
16 my $tmux_mode   = (defined $ARGV[0] and $ARGV[0] eq '-t');
17
18 my %battery;
19
20 open my $file, '<', $path or die $!;
21 while (<$file>) {
22     /^POWER_SUPPLY_([A-Z_]+)=(.+)$/;
23     $battery{$1} = $2;
24 }
25 close $file;
26
27 my $charge = int($battery{CHARGE_NOW} / $battery{CHARGE_FULL} * 100);
28
29 # GNU screen mode with colors: 0-20 red, 20-40 yellow, 40-100 green.
30 if ($screen_mode) {
31     my $color;
32     if ($charge < 20) {
33         $color = 'b r';
34     } elsif ($charge < 40) {
35         $color = 'b y';
36     } else {
37         $color = 'b g';
38     }
39
40     print "\005{+$color}$charge%\005{-}\n";
41 # Same in tmux mode.
42 } elsif ($tmux_mode) {
43     my $color;
44     if ($charge < 20) {
45         $color = 'red';
46     } elsif ($charge < 40) {
47         $color = 'yellow';
48     } else {
49         $color = 'green';
50     }
51
52     print "#[fg=$color,bold]$charge%#[default]\n";
53
54 # Just text output.
55 } else {
56     print "$charge%\n";
57 }