Skip to content

Instantly share code, notes, and snippets.

@terabyte
Created December 26, 2018 21:52
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 terabyte/54a53dd2a75f5abe06165aefbe369716 to your computer and use it in GitHub Desktop.
Save terabyte/54a53dd2a75f5abe06165aefbe369716 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# this script is run whenever the status of the AC adapter changes
# user who is expected to be running the x server (i.e. has Xauthority)
XUSER="cmyers"
# how long a delay between plugging in power and battery status no longer shows discharging
SLEEP_DELAY="0.5s"
# how dim should it be on battery?
BAT_BRIGHTNESS="70%"
# if we run the script directly, display will already be right, but when udev runs it we need to fill this in
export DISPLAY="${DISPLAY:-:0.0}"
# I've seen the following possible values: Unknown, Discharging, Charging, Full.
# you may have to customize this value for your laptop
# You can probably discover the value with: find /sys/devices/ -type d -name 'BAT0'
BAT_FILE="/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/device:1b/PNP0C09:00/PNP0C0A:00/power_supply/BAT0/status"
# Implementation Notes:
# When the AC adaptor is unplugged, the status is updated almost immediately
# However, when the AC adaptor is plugged in, it sometimes takes a second or
# two for it to update. For this reason, instead of having a udev rule for
# plug in and a udev rule for unplug, we instead have a rule that triggers on
# any change and runs this script which will then sleep for a second, then do
# the needful.
# To install the udev rule, as root:
# echo 'KERNEL=="BAT0", RUN+="/bin/bash /home/cmyers/bin/bat-status-changed.sh"' > /etc/udev/rules.d/49-powersave.rules
#
# If your battery has a different name or is weird or whatever, you can replace KERNEL=="BAT0" with SUBSYSTEM="power_supply".
function switch_to_battery {
# Put anything you want to happen when on battery power here
# set screensaver to blank only
sed -i 's/^mode:.*/mode: blank/' /home/cmyers/.xscreensaver;
# dim LCD
sudo -u "$XUSER" /usr/bin/xbacklight -set "$BAT_BRIGHTNESS";
}
function switch_to_ac {
# Put anything you want to happen when on AC power here
# set screensaver to back to the one true screensaver (xmatrix)
sed -i 's/^mode:.*/mode: one/' /home/cmyers/.xscreensaver;
# restore LCD to 100%
sudo -u "$XUSER" /usr/bin/xbacklight -set "100%";
}
sleep "$SLEEP_DELAY"
BAT_STATUS="$(cat "$BAT_FILE")"
if [[ "$BAT_STATUS" == "Discharging" ]]; then
# we are on battery
switch_to_battery
exit 0;
fi
# for all others, assume we are on AC (Charging, Full are almost always AC, Unknown is probably AC too)
switch_to_ac
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment