conky/battery_estimate: add debugging

This commit is contained in:
Colin 2023-12-28 00:35:48 +00:00
parent cb4d73f959
commit 623b2c6611

View File

@ -1,37 +1,63 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash
usage() {
echo "usage: battery_estimate [options...]"
echo
echo "pretty-prints a battery estimate (icon to indicate state, and a duration estimate)"
echo
echo "options:"
echo " --debug: output additional information, to stderr"
}
# these icons come from sxmo; they only render in nerdfonts
bat_dis="󱊢"
bat_chg="󱊥"
log() {
if [ "$BATTERY_ESTIMATE_DEBUG" = "1" ]; then
printf "$@" >&2
echo >&2
fi
}
try_path() {
# returns:
# - perc, perc_left (0-100)
# - full, rate (pos means charging)
if [ -f "$1/capacity" ]; then
log "perc, perc_left from %s" "$1/capacity"
perc=$(cat "$1/capacity")
perc_left=$((100 - $perc))
fi
if [ -f "$1/charge_full_design" ] && [ -f "$1/current_now" ]; then
log "full, rate from %s and %s" "$1/charge_full_design" "$1/current_now"
# current is positive when charging
full=$(cat "$1/charge_full_design")
rate=$(cat "$1/current_now")
fi
if [ -f "$1/energy_full" ] && [ -f "$1/energy_now" ]; then
log "full, rate from %s and %s" "$1/energy_full" "$1/energy_now"
# energy is positive when discharging
full=$(cat "$1/energy_full")
rate=-$(cat "$1/energy_now")
fi
}
try_path "/sys/class/power_supply/axp20x-battery" # Pinephone
try_path "/sys/class/power_supply/BAT0" # Thinkpad
try_all_paths() {
try_path "/sys/class/power_supply/axp20x-battery" # Pinephone
try_path "/sys/class/power_supply/BAT0" # Thinkpad
log "perc: %d, left: %d" "$perc" "$perc_left"
log "full: %f, rate: %f" "$full" "$rate"
log " rate > 0 means charging, else discharging"
}
fmt_minutes() {
log "charge/discharge time: %f min" "$3"
# args: <battery symbol> <text if ludicrous estimate> <estimated minutes to full/empty>
if [[ $3 -gt 1440 ]]; then
log "charge/discharge duration > 1d"
printf "%s %s" "$1" "$2" # more than 1d
else
hr=$(($3 / 60))
@ -41,12 +67,31 @@ fmt_minutes() {
fi
}
if [[ $rate -lt 0 ]]; then
# discharging
fmt_minutes "$bat_dis" '∞' "$(($full * 60 * $perc / (-100 * $rate)))"
elif [[ $rate -gt 0 ]]; then
# charging
fmt_minutes "$bat_chg" '100%' "$(($full * 60 * $perc_left / (100 * $rate)))"
elif [[ "$perc" != "" ]]; then
echo "$bat_dis $perc%"
fi
pretty_output() {
if [[ $rate -lt 0 ]]; then
log "discharging"
fmt_minutes "$bat_dis" '∞' "$(($full * 60 * $perc / (-100 * $rate)))"
elif [[ $rate -gt 0 ]]; then
log "charging"
fmt_minutes "$bat_chg" '100%' "$(($full * 60 * $perc_left / (100 * $rate)))"
elif [[ "$perc" != "" ]]; then
log "neither charging nor discharging"
echo "$bat_dis $perc%"
fi
}
while [ "$#" -gt 0 ]; do
case "$1" in
"--debug")
shift
BATTERY_ESTIMATE_DEBUG=1
;;
*)
usage
exit 1
;;
esac
done
try_all_paths
pretty_output