Tomasz Kramkowski

battd

battd is a simple battery daemon written for use with a daemontools-style supervisor.

The daemon run script polls the status of a user defined check function interleaved with calls to a interval function. On the transition from a successful check exit status to an unsuccessful check exit status the failed function is called. These functions need to be provided in a conf file located in the same directory as the script.

The following conf file contains an example configuration which reduces the polling interval from 5 minutes to 30 seconds when the battery level is below 16 percent or has fewer than 20 minutes of battery life remain and puts the machine in a hybrid sleep once the battery level is below 8 percent or fewer than 10 minutes of battery life remain.

battery=/sys/class/power_supply/BAT0/uevent
interval() {
    if ./battcheck min_time=1200 min_pct=16 "$battery"; then
        sleep 300
    else
        sleep 30
    fi
}
check() { ./battcheck min_time=600 min_pct=8 "$battery"; }
failed() { zzz -H; }

The provided battcheck awk script takes two optional command line variable assignments for min_pct and min_time specifying the remaining battery percentage and remaining battery time in seconds respectively after which the script will produce an unsuccessful exit code.

These files should be placed inside a service directory making sure that run and battcheck are both executable. The service handles SIGHUP to reload its configuration at runtime.

The battcheck script is quite versatile and may be useful in other contexts, in which case it is recommended to install it to /usr/local/sbin or another appropriate location.

If the script crashes before a success to failure transition of the check function and is re-started after the transition then the script will incorrectly ignore this transition and not call the failed function. This could be fixed by storing the previous status in on a temporary file system but this was not done due to the unlikelihood of the event and in order to keep the code simple.

If you are stuck in a hole and the only thing you have to dig yourself out with is a laptop running Ubuntu then an appropriate systemd service file is provided. The file expects ./install to have been ran with a destination directory of /opt/battd.


Source
https://the-tk.com/cgit/battd/