Does Ubuntu 15.04 (or maybe just Linux in general) have any sort of measurable event that fires when a laptop's AC power is disconnected and the unit flips over to battery power?
I would like to write a small program that waits for that event and then makes some adjustments to things like screen brightness, for instance. I know there are some solutions for this, but I'm trying to teach myself at the same time. I'm new(ish) to Linux and have done the majority of my coding in .NET
on Windows systems.
I have seen battery status info in /sys/class/power_supply/
, but I am assuming there must be a better way to determine if the adapter has been unplugged rather than just scanning for changes to files on some sort of timer.
I've tried searching Google and these forums, but haven't yet figured out how to properly phrase the search.
Best Answer
You are looking for
udev
, which detects changes to various system states, including plugging devices in (or unplugging them). You can script udev to take some action when a device is attached or removed.Udev is, frankly, pretty complex, and you will want to do some really basic tests to make sure that you are detecting what you are looking for.
The basic steps are these:
Monitor your system:
sudo udevadm monitor
This tells you what udev "sees".
With this running, plug in the power supply, and see what udevadm tells you. Unplug it, again: see what udevadm tells you. It will probably make no sense yet, but that's ok; you know how to monitor udev now, and that's useful.
Stop that process, and do this:
sudo udevadm info --path=/sys/class/power_supply/ac
or
sudo udevadm info --path=/sys/class/power_supply/battery
which gives you information about the AC and BATTERY systems. Like this:
The
E:
lines are environment attributes you can use to write a udev rule.Write a basic udev rule (I usually just write one to create a log entry somewhere on my drive when the even happens; that way, I know I am triggering something. Then I go back and make the script useful.)
For example:
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_STATUS}=="Charging", RUN+="/path/to/some/script.sh"
or you might use
POWER_SUPPLY_PRESENT=1
... you'll have to experiment based on what values you see on your computer.Place this udev script in
/etc/udev/rules.d
(a name like80.power.rules
would be conventional) and restart your computer. Technically you can just restart udev but I find that unreliable.See if your script gets triggered when your AC is plugged in.
Refine your udev rule and the script it triggers.
There is much more to udev, so dive in!