Skip to content

Instantly share code, notes, and snippets.

@nknapp
Last active February 25, 2020 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nknapp/8b4e10788b65ab9e921ef50e1a3ac60f to your computer and use it in GitHub Desktop.
Save nknapp/8b4e10788b65ab9e921ef50e1a3ac60f to your computer and use it in GitHub Desktop.
Set powersave/performance governor based on ac/battery status

This setup switches to "powersave" if the battery is lower than 75% and to "performance" if it is above and charging.

Copy the files to

  • /etc/systemd/system/watch-power-cpufreq.service
  • /usr/local/bin/watch-power-cpufreq.sh

and then run

sudo systemctl daemon-reload
sudo systemctl start watch-power-cpufreq.service
systemctl enable watch-power-cpufreq.service

Update: I added an installation script. Just do

curl -L https://gist.github.com/nknapp/8b4e10788b65ab9e921ef50e1a3ac60f/raw/install.sh | sudo bash
GIST_URL=https://gist.github.com/nknapp/8b4e10788b65ab9e921ef50e1a3ac60f/raw
curl -L -o /usr/local/bin/watch-power-cpufreq.sh $GIST_URL/watch-power-cpufreq.sh
chmod a+x /usr/local/bin/watch-power-cpufreq.sh
systemctl disable watch-power-cpufreq.service || true
systemctl stop watch-power-cpufreq.service || true
curl -L -o /etc/systemd/system/watch-power-cpufreq.service $GIST_URL/watch-power-cpufreq.service
systemctl daemon-reload
systemctl enable watch-power-cpufreq.service
systemctl start watch-power-cpufreq.service
[Unit]
After=local-fs.target
[Service]
ExecStart=/usr/local/bin/watch-power-cpufreq.sh
Restart=on-failure
RestartSec=30
[Install]
WantedBy=multi-user.target
#!/bin/bash
# Set governor to powersave for lower values
CAPACITY_THRESHOLD=75
function setGovernor() {
GOV=$1
echo "Switching to governor: $GOV"
for GOV_FILE in /sys/devices/system/cpu/cpufreq/*/scaling_governor ; do
echo "${GOV}" > $GOV_FILE
done
}
while true; do
BATTERY_STATUS=$( cat /sys/class/power_supply/BAT0/status )
BATTERY_CAPACITY=$( cat /sys/class/power_supply/BAT0/capacity )
case "${BATTERY_STATUS}" in
"Discharging")
echo "Battery discharging at ${BATTERY_CAPACITY}%"
if [ ${BATTERY_CAPACITY} -lt ${CAPACITY_THRESHOLD} ]; then
setGovernor "powersave"
else
setGovernor "performance"
fi
;;
*)
echo "Battery status: ${BATTERY_STATUS}"
setGovernor "performance"
;;
esac
inotifywait /sys/class/power_supply/AC/online /sys/class/power_supply/BAT0/capacity || exit 1
done
@nknapp
Copy link
Author

nknapp commented May 19, 2018

Fixed "WantedBy" to "multi-user.target". Added Restart policy

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