summaryrefslogtreecommitdiff
path: root/battery
blob: ea1b384a1dbd9d1e64e07127fba4049d7d69b9b2 (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
85
86
87
88
89
90
91
#!/home/dakkar/perl5/perlbrew/perls/perl-5.40.0/bin/perl 
use v5.40;
use lib '/home/dakkar/.perlbrew/libs/perl-5.40.0/lib/perl5';
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;
        next unless $name;
        $ret{lc($name)}= $ENV{"POWER_SUPPLY_$name"} || $value;
    }
    return \%ret;
}
 
sub _format_time($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 $now = $bs->{energy_now// $bs->{charge_now};
    my $full = $bs->{energy_full// $bs->{charge_full};
    my $deriv = $bs->{power_now// $bs->{current_now};
 
    my $fraction = $now/$full;
    my $charging = lc($bs->{status}) eq 'charging';
    my $is_full = lc($bs->{status}) eq 'full';
    my @symbols;
    my $time_estimate='';
    my $percentage=sprintf '%.0f%%', 100*$fraction;
 
    if ($deriv && !$charging) {
        my $t=$now/$deriv;
        my $tot=$full/$deriv;
 
        $time_estimate = sprintf "%s/%s",
            _format_time($t),
            _format_time($tot);
    }
 
    if ($charging) {
        push @symbols"\x{1f50c}";
    }
 
    if (!$is_full && $fraction > 0.2) {
        push @symbols"\x{1f50b}";
    }
    elsif (!$is_full) {
        push @symbols"\x{1faab}";
    }
 
    $bar->set_fraction($fraction);
    $bar->set_text(join "\x{2009}"grep { length @symbols$time_estimate$percentage);
 
    return 1;
}
 
$window->show_all;
 
Gtk2->main;