machine_setup/ansible/roles/sway/files/waybar_battery_linux.bash

69 lines
2.0 KiB
Bash

#!/usr/bin/env bash
#
# Read battery status in Linux
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
batteries=$(upower --enumerate | grep BAT)
function generate_battery_update {
local battery_path=$1
local battery_status=$(upower --show-info "$battery_path")
local battery_state=$(grep 'state:' <<<"$battery_status" | awk '{print $2}')
local battery_percentage=$(grep 'percentage:' <<<"$battery_status" | awk '{print $2}')
battery_percentage=${battery_percentage%\%}
local time_remaining=$(grep 'time to empty:' <<<"$battery_status" | sed 's/\W*time to empty:\W*//g')
local tooltip="$time_remaining until empty"
if [ -z "$time_remaining" ]; then
time_remaining=$(grep 'time to full:' <<<"$battery_status" | sed 's/\W*time to full:\W*//g')
tooltip="$time_remaining until full"
fi
local battery_icon=""
local class=""
if [ $battery_state = "charging" ]; then
if [ $battery_percentage -eq 100 ]; then
battery_icon=""
else
battery_icon=""
fi
elif [ $battery_percentage -le 20 ]; then
battery_icon=""
elif [ $battery_percentage -le 40 ]; then
battery_icon=""
elif [ $battery_percentage -le 60 ]; then
battery_icon=""
elif [ $battery_percentage -le 80 ]; then
battery_icon=""
elif [ $battery_percentage -lt 100 ]; then
battery_icon=""
else
battery_icon=""
fi
if [ $battery_percentage -le 15 ]; then
class="critical"
elif [ $battery_percentage -le 30 ]; then
class="warning"
fi
jq --unbuffered --compact-output <<EOF
{
"text":"${battery_percentage}% ${battery_icon}",
"tooltip":"$tooltip",
"percentage":${battery_percentage},
"class":"${class}"
}
EOF
}
while read bat; do
generate_battery_update "$bat"
done<<<"$batteries"
upower --monitor | grep --line-buffered 'device changed:' | while read l; do
while read bat; do
generate_battery_update "$bat"
done<<<"$batteries"
done