Skip to content

Instantly share code, notes, and snippets.

@kobus-v-schoor
Last active May 22, 2024 14:02
Show Gist options
  • Save kobus-v-schoor/fd3b48eebfa40cc29f984a9b69b23ea4 to your computer and use it in GitHub Desktop.
Save kobus-v-schoor/fd3b48eebfa40cc29f984a9b69b23ea4 to your computer and use it in GitHub Desktop.
#! /bin/bash
BAT=$(echo /sys/class/power_supply/BAT*)
BAT_STATUS="$BAT/status"
BAT_CAP="$BAT/capacity"
LOW_BAT_PERCENT=20
AC_PROFILE="performance"
BAT_PROFILE="balanced"
LOW_BAT_PROFILE="power-saver"
# wait a while if needed
[[ -z $STARTUP_WAIT ]] || sleep "$STARTUP_WAIT"
# start the monitor loop
prev=0
while true; do
# read the current state
if [[ $(cat "$BAT_STATUS") == "Discharging" ]]; then
if [[ $(cat "$BAT_CAP") -gt $LOW_BAT_PERCENT ]]; then
profile=$BAT_PROFILE
else
profile=$LOW_BAT_PROFILE
fi
else
profile=$AC_PROFILE
fi
# set the new profile
if [[ $prev != "$profile" ]]; then
echo setting power profile to $profile
powerprofilesctl set $profile
fi
prev=$profile
# wait for the next power change event
inotifywait -qq "$BAT_STATUS" "$BAT_CAP"
done
@gabtremblay
Copy link

gabtremblay commented Nov 20, 2023

Hey, since I can't make a pull request. I modified the script slightly because there was some edge cases when the battery comes from being at 100% full charging to 100% full not charging where some systems will let the battery drain a bit then restart charging, which makes the system switch profiles endlessly. just added a check if there's an AC adapter.

#! /bin/bash

BAT=$(echo /sys/class/power_supply/BAT*)
ACADAPTER="/sys/class/power_supply/ACAD/online"
BAT_STATUS="$BAT/status"
BAT_CAP="$BAT/capacity"
LOW_BAT_PERCENT=20

AC_PROFILE="performance"
BAT_PROFILE="power-saver"
LOW_BAT_PROFILE="power-saver"

# wait a while if needed
[[ -z $STARTUP_WAIT ]] || sleep "$STARTUP_WAIT"

# start the monitor loop
prev=0

while true; do
	# read the current state
	if [[ $(cat "$ACADAPTER") == "1" ]]; then
		profile=$AC_PROFILE
	elif [[ $(cat "$BAT_STATUS") == "Discharging" ]]; then
		if [[ $(cat "$BAT_CAP") -gt $LOW_BAT_PERCENT ]]; then
			profile=$BAT_PROFILE
		else
			profile=$LOW_BAT_PROFILE
		fi
	else
		profile=$AC_PROFILE
	fi

	# set the new profile
	if [[ $prev != "$profile" ]]; then
		echo setting power profile to $profile
		powerprofilesctl set $profile
	fi

	prev=$profile

	# wait for the next power change event
	inotifywait -qq "$BAT_STATUS" "$BAT_CAP"
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment