Tomasz Kramkowski


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 every long_interval or short_interval seconds. The interval is determined by the status of the interval function. On the transition from a successful check exit status to an unsuccessful check exit status the failed function is called. These functions and optionally the variables long_interval and short_interval 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 increases the polling interval from 5 minutes to 30 seconds when the battery level is below 16 percent or 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.

interval() { ./battcheck min_time=1200 min_pct=16 "$battery"; }
check() { ./battcheck min_time=600 min_pct=8 "$battery"; }
failed() { zzz -H; }

Finally, the 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.