#!/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() { # assigns output variables: # - 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") elif [ -f "$1/energy_full" ] && [ -f "$1/power_now" ]; then log "full, rate from %s and %s" "$1/energy_full" "$1/power_now" # power_now is positive when discharging full=$(cat "$1/energy_full") rate=-$(cat "$1/power_now") elif [ -f "$1/energy_full" ] && [ -f "$1/energy_now" ]; then log "full, rate from %s and %s" "$1/energy_full" "$1/energy_now" log " this is a compatibility path for legacy Thinkpad batteries which do not populate the 'power_now' field, and incorrectly populate 'energy_now' with power info" # energy_now is positive when discharging full=$(cat "$1/energy_full") rate=-$(cat "$1/energy_now") fi } 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: if [[ $3 -gt 1440 ]]; then log "charge/discharge duration > 1d" printf "%s %s" "$1" "$2" # more than 1d else hr=$(($3 / 60)) hr_in_min=$(($hr * 60)) min=$(($3 - $hr_in_min)) printf "%s %dh%02dm" "$1" "$hr" "$min" 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