foxygit / sxbar Log in
commits tags

/scripts/battery.sh · 1.67 KB

raw
#!/bin/sh
# battery module -- everything the module needs, dispatched by subcommand:
#   battery.sh                  -> bar text, "NN%" (from /sys/class/power_supply)
#   battery.sh status           -> detailed status row (popup, needs upower)
#   battery.sh toggle-powersave -> toggle power profile (popup action, needs power-profiles-daemon)
#   battery.sh menu             -> popup definition, read once at startup
#                                  (see README, "Module-declared menus")
mode="${1:-capacity}"

case "$mode" in
menu)
	self="$0"
	echo 'popup : hover : buttons'
	echo "popup_info : \"$self status\""
	echo "popup_item : \"Toggle power saver\" : \"$self toggle-powersave\""
	;;
capacity)
	# BAT0 on some machines, BAT1 on others -- glob for whichever exists
	cat /sys/class/power_supply/BAT*/capacity 2>/dev/null | head -n1 | sed 's/$/%/'
	;;
status)
	dev=$(upower -e 2>/dev/null | grep -m1 'BAT')
	if [ -z "$dev" ]; then
		echo "Battery: no info"
		exit 0
	fi

	upower -i "$dev" 2>/dev/null | awk '
		/state:/          { state = $2 }
		/percentage:/     { pct = $2 }
		/time to empty:/  { tte = $0; sub(/.*time to empty:[ \t]*/, "", tte) }
		/time to full:/   { ttf = $0; sub(/.*time to full:[ \t]*/, "", ttf) }
		/capacity:/       { health = $2 }
		END {
			out = state " " pct
			if (state == "discharging" && tte != "") out = out " (" tte " left)"
			if (state == "charging" && ttf != "")     out = out " (" ttf " to full)"
			if (health != "") out = out " -- health " health
			print out
		}'
	;;
toggle-powersave)
	current=$(powerprofilesctl get 2>/dev/null)
	if [ "$current" = "power-saver" ]; then
		powerprofilesctl set balanced
	else
		powerprofilesctl set power-saver
	fi
	;;
esac