Restoring Screen Backlight Brightness in Ubuntu

One of many details available in Windows but not in Ubuntu is automatic backlight change when system switches from AC to battery. And it's not just a dumb change to predefined value either. Every switch from AC to battery and vice versa restores the last value system had. Ubuntu on the other hand just keeps the backlight as is resulting in me manually adjusting it every time. Lookup on Internet for applications providing this functionality gave me no warm fuzzy feeling so I decided to roll my own. I mean, how hard can it be.

Well, actually annoyingly hard if you want to support every interface out there. As I wanted to support only my Dell XPS 15, I had quite a bit easier work.

The main part of the story is in two files: /sys/class/power_supply/AC/online and /sys/class/backlight/intel_backlight/brightness. All what's needed was actually a small script handling tracking and restoring brightness values every once in a while. This is roughly what I ended with:

~/bin/backlight-tracer
#!/bin/bash

STORED_AC=`cat /var/cache/.backlight.ac`
STORED_BAT=`cat /var/cache/.backlight.bat`

while(true); do
BRIGHTNESS=`cat /sys/class/backlight/intel_backlight/brightness`
IS_AC=`cat /sys/class/power_supply/AC/online`
if [[ "$IS_AC" != "$LAST_AC" ]]; then
if [[ "$IS_AC" != "0" ]]; then
if [[ "$STORED_AC" != "" ]]; then
echo -e "Restoring AC backlight to $STORED_AC"
echo $STORED_AC > $FILE_BRIGHTNESS
fi
else
if [[ "$STORED_BAT" != "" ]]; then
echo -e "Restoring battery backlight to $STORED_BAT"
echo $STORED_BAT > $FILE_BRIGHTNESS
fi
fi
LAST_AC=$IS_AC
else
if [[ "$IS_AC" != "0" ]]; then
if [[ "$STORED_AC" != "$BRIGHTNESS" ]]; then
echo $BRIGHTNESS > /var/cache/.backlight.ac
STORED_AC=$BRIGHTNESS
fi
else
if [[ "$STORED_BAT" != "$BRIGHTNESS" ]]; then
echo $BRIGHTNESS > /var/cache/.backlight.bat
STORED_BAT=$BRIGHTNESS
fi
fi
fi

sleep 0.5
done

As you can see, the script is just checking in loop if there was an AC status change. If computer was plugged or unplugged, it simply restores the last saved value for that power state. If power status remained the same, it will track any brightness change so it's possible to restore it later. Really simple and really working.

And yes, the script above contains no error handling. If you want to see the real stuff, it's available on GitHub. Even better, it's available as a Debian package if you want to install it.

Leave a Reply

Your email address will not be published. Required fields are marked *