Copybara bot | ca5ce64 | 2024-11-08 17:38:08 +0100 | [diff] [blame^] | 1 | #!/usr/bin/env perl |
| 2 | # |
| 3 | # Copyright 2014 Pierre Mavro <deimos@deimos.fr> |
| 4 | # Copyright 2014 Vivien Didelot <vivien@didelot.org> |
| 5 | # |
| 6 | # Slightly modified by Adrià Vilanova |
| 7 | # |
| 8 | # Licensed under the terms of the GNU GPL v3, or any later version. |
| 9 | # |
| 10 | # This script is meant to use with i3blocks. It parses the output of the "acpi" |
| 11 | # command (often provided by a package of the same name) to read the status of |
| 12 | # the battery, and eventually its remaining time (to full charge or discharge). |
| 13 | # |
| 14 | # The color will gradually change for a percentage below 85%, and the urgency |
| 15 | # (exit code 33) is set if there is less that 5% remaining. |
| 16 | |
| 17 | use strict; |
| 18 | use warnings; |
| 19 | use utf8; |
| 20 | |
| 21 | my $acpi; |
| 22 | my $status; |
| 23 | my $percent; |
| 24 | my $ac_adapt; |
| 25 | my $full_text; |
| 26 | my $short_text; |
| 27 | my $bat_number = $ENV{BAT_NUMBER} || 0; |
| 28 | my $label = $ENV{LABEL} || ""; |
| 29 | |
| 30 | # read the first line of the "acpi" command output |
| 31 | open (ACPI, "acpi -b 2>/dev/null| grep 'Battery $bat_number' |") or die; |
| 32 | $acpi = <ACPI>; |
| 33 | close(ACPI); |
| 34 | |
| 35 | # fail on unexpected output |
| 36 | if (not defined($acpi)) { |
| 37 | # don't print anything to stderr if there is no battery |
| 38 | exit(0); |
| 39 | } |
| 40 | elsif ($acpi !~ /: ([\w\s]+), (\d+)%/) { |
| 41 | die "$acpi\n"; |
| 42 | } |
| 43 | |
| 44 | $status = $1; |
| 45 | $percent = $2; |
| 46 | $full_text = "$label"; |
| 47 | |
| 48 | if ($status eq 'Discharging') { |
| 49 | $full_text .= '⚡'; |
| 50 | } elsif ($status eq 'Charging') { |
| 51 | $full_text .= '🔌'; |
| 52 | } elsif ($status eq 'Unknown') { |
| 53 | open (AC_ADAPTER, "acpi -a |") or die; |
| 54 | $ac_adapt = <AC_ADAPTER>; |
| 55 | close(AC_ADAPTER); |
| 56 | |
| 57 | if ($ac_adapt =~ /: ([\w-]+)/) { |
| 58 | $ac_adapt = $1; |
| 59 | |
| 60 | if ($ac_adapt eq 'on-line') { |
| 61 | $full_text .= '🔌'; |
| 62 | } elsif ($ac_adapt eq 'off-line') { |
| 63 | $full_text .= '⚡'; |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | $full_text .= "$percent%"; |
| 69 | |
| 70 | $short_text = $full_text; |
| 71 | |
| 72 | if ($acpi =~ /(\d\d:\d\d):/) { |
| 73 | $full_text .= " ($1)"; |
| 74 | } |
| 75 | |
| 76 | # print text |
| 77 | print "$full_text\n"; |
| 78 | print "$short_text\n"; |
| 79 | |
| 80 | # consider color and urgent flag only on discharge |
| 81 | if ($status eq 'Discharging') { |
| 82 | |
| 83 | if ($percent < 20) { |
| 84 | print "#FF0000\n"; |
| 85 | } elsif ($percent < 40) { |
| 86 | print "#FFAE00\n"; |
| 87 | } elsif ($percent < 60) { |
| 88 | print "#FFF600\n"; |
| 89 | } elsif ($percent < 85) { |
| 90 | print "#A8FF00\n"; |
| 91 | } |
| 92 | |
| 93 | if ($percent < 5) { |
| 94 | exit(33); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | exit(0); |