Created
December 7, 2012 06:00
-
-
Save non/4231094 to your computer and use it in GitHub Desktop.
cute little battery script in perl (gasp)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| use warnings FATAL => 'all'; | |
| use strict; | |
| sub bool { return $_[0] eq "Yes" } | |
| sub num { return int($_[0]) } | |
| sub stime { | |
| my ($n) = @_; | |
| my $h = $n / 60; | |
| my $m = $n % 60; | |
| return sprintf("%02d:%02d", $h, $m); | |
| } | |
| sub perc { | |
| my ($n, $d) = @_; | |
| return sprintf("%.1f%%", $n * 100 / $d); | |
| } | |
| sub charge_time { | |
| my ($data) = @_; | |
| return $data->{full} ? "--:--" : stime($data->{tcharge}); | |
| } | |
| sub drain_time { | |
| my ($data) = @_; | |
| return $data->{full} ? "--:--" : stime($data->{tdrain}); | |
| } | |
| sub debug { | |
| my ($data) = @_; | |
| use Data::Dumper; | |
| print Dumper($data) . "\n"; | |
| } | |
| sub main { | |
| my $data = init(); | |
| display1($data, 5); | |
| #debug($data); | |
| } | |
| my @meta = ( | |
| ["ExternalConnected", "connected", \&bool], | |
| ["AvgTimeToEmpty", "tdrain", \&num], | |
| ["AvgTimeToFull", "tcharge", \&num], | |
| ["MaxCapacity", "max", \&num], | |
| ["CurrentCapacity", "cur", \&num], | |
| ["FullyCharged", "full", \&bool], | |
| ["IsCharging", "charging", \&bool], | |
| ); | |
| sub init { | |
| my $data = {}; | |
| open(my $fh, "-|", "ioreg -rc AppleSmartBattery"); | |
| while (my $line = <$fh>) { | |
| my ($key, $val) = $line =~ m/^ *"(\w+)" = (.+)$/; | |
| next unless $key && $val; | |
| for (@meta) { | |
| next unless $key eq $_->[0]; | |
| $data->{$_->[1]} = $_->[2]->($val); | |
| last; | |
| } | |
| } | |
| return $data; | |
| } | |
| sub icon { | |
| my ($data) = @_; | |
| return "☀" if $data->{full}; | |
| return "⚡" if $data->{connected}; | |
| return "⚠"; | |
| } | |
| sub display1 { | |
| my ($data, $n) = @_; | |
| my $c = $data->{connected}; | |
| my $p = perc($data->{cur}, $data->{max}); | |
| #my $icon = $c ? "⚡" : "⚠"; | |
| my $icon = icon($data); | |
| my $f = $c ? \&charge_time : \&drain_time; | |
| my $t = $f->($data); | |
| printf("%s (%s) $icon\n", $t, $p); | |
| } | |
| main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment