Handle ACPI events in Linux
Thu 25 December 2008 by Thejaswi PuthrayaHandle ACPI Events in Linux
Off late, I have been working totally in runlevel 3 to replicate the setup and feel at work. The only grudge I have with runlevel 3 is that there is no easy way to figure out the battery level of the laptop.
So I googled around and realized that ACPI was the answer to my question.
To figure out all the statistics that are related to ACPI, /proc/acpi is the place to head.
So to check the battery power level all one has to do is read the /proc/acpi/battery/BAT0/state file and it gives all the necessary statistics.
Later I realized that it would be wonderful if I was able to handle events like battery fully charged, battery level low, laptop lid closed etc. This too is handled by ACPI.
I dug around this topic deeper and could not come up with a decent solution. Some suggested looking around the ACPI kernel module. I tried this but could not get it to work.
Then I read about the acpid daemon that runs in userspace and listens to various ACPI events and runs user-defined scripts when a particular ACPI event is triggered. The man page for acpid is really helpful and gives all the required info on events and how to handle them.
Here is an example script that I use to trigger events when the battery is fully charged and when the battery level reaches the pre-defined alarm level.
In /etc/acpi/actions/
#!/bin/sh
# /etc/acpi/actions/battery.sh
PATH=/sbin:/bin:/usr/bin:/usr/local/bin
alarm_level=`cat /proc/acpi/battery/BAT0/alarm |awk '/^alarm/ { print $2 }'`
remaining_capacity=`cat /proc/acpi/battery/BAT0/state|awk '/^remaining/ { print $3 }'`
last_full_capacity=`cat /proc/acpi/battery/BAT0/info|awk '/^last/ { print $4 }'`
if [ $remaining_capacity -eq $alarm_level ]
then
# Send an email
# or play a tone or do whatever
mplayer /home/theju/tones/battery_low.ogg
fi
if [ $remaining_capacity -eq $last_full_capacity ]
then
mplayer /home/theju/fully_charged.ogg
fi
In /etc/acpi/events/battery.conf
event=battery/*
action=/etc/acpi/actions/battery.sh
For Thinkpad owners, there is a very good wiki article on Thinkwiki that also gives various other things you could do with ACPI.