summaryrefslogtreecommitdiff
path: root/battery
blob: 7b1c3481c9831ac35e7fbb47f22b6d5de37d3237 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/home/dakkar/perl5/perlbrew/perls/perl-5.16.3/bin/perl 
use strict;
use warnings;
use 5.016;
use Gtk2 -init;
 
my $window = Gtk2::Window->new('toplevel');
$window->set_accept_focus(0);
$window->set_decorated(0);
$window->set_has_frame(0);
$window->set_skip_pager_hint(1);
$window->set_skip_taskbar_hint(1);
$window->set_type_hint('utility');
$window->set_default_size(300,25);
$window->set_resizable(1);
$window->set_name('dakkar-battery');
$window->set_wmclass('dakkar-battery','dakkar-battery');
 
my $bar = Gtk2::ProgressBar->new();
$bar->set_orientation('left-to-right');
$bar->set_name('dakkar-battery-bar');
 
$window->add($bar);
 
$window->signal_connect(delete_event => \&quit);
 
Glib::Timeout->add(1000,\&update);
 
sub quit {
    Gtk2->main_quit;
}
 
sub get_battery_stats {
    open my $fh,'<','/sys/class/power_supply/BAT1/uevent';
    my %ret;
    while (my $line=<$fh>) {
        chomp $line;
        my ($name,$value) = $line =~ m{\A POWER_SUPPLY_(.*?) = (.*) \z}x;
        $ret{lc($name)}=$value;
    }
    return \%ret;
}
 
sub _format_time {
    my ($t) = @_;
    my $h=int($t);
    my $m=int(($t-$h)*60);
    return sprintf q{%dh%02d},$h,$m;
}
 
sub update {
    my $bs=get_battery_stats;
    my $e=$bs->{energy_now}/$bs->{energy_full};
    my $txt='';
    my $charging = lc($bs->{status}) eq 'charging';
    my $full = lc($bs->{status}) eq 'full';
    if ($charging) {
        $txt = "\x{1f50c} ";
    }
    elsif (!$full) {
        $txt = "\x{1f50b} ";
    }
    if ($bs->{power_now} && !$charging) {
        my $t=$bs->{energy_now}/$bs->{power_now};
        my $tot=$bs->{energy_full}/$bs->{power_now};
 
        $txt .= sprintf '%s/%s ',
            _format_time($charging ? $tot-$t : $t),
                _format_time($tot);
        $bar->set_fraction($t/$tot);
    }
    else {
        $bar->set_fraction($e);
    }
    $txt .= sprintf '%.0f%%', 100*$e;
 
    $bar->set_text($txt);
 
    return 1;
}
 
$window->show_all;
 
Gtk2->main;