Jump to content

Power monitoring/An action at a certain battery level

From postmarketOS Wiki

Battery capacity change doesn't generally trigger udev events, so udev typically can't be used for this purpose. Monitoring is performed periodically, using cron to perform the job.

Example script

Create an executable script for action at various capacity level. The example script below will blink the notification light when the battery is at 25 percent and will blink the notification light again when the battery is at 15 percent and shutdown.

The script below is for Xiaomi Redmi 1S (xiaomi-armani), so modification of sysfs path is needed for use on another devices.

#!/bin/sh
# Replace BATTERY variable with the actual battery device
# found under sysfs
BATTERY="battery"

# Turn off notification leds
# Replace the value of leds according to the sysfs entry
ledsoff() {
	local leds="red green blue"
	for led in $leds; do
		echo 0 > /sys/class/leds/"$led"/brightness
	done
}

# Blink notification leds for 100 times
# Replace the red variable with actual red led device
# found under sysfs
blink() {
	local countdown=100
	local red=red
	until [ "$countdown" -eq 0 ]; do
		countdown="$((countdown-1))" &&
		echo 100 > /sys/class/leds/"$red"/brightness && sleep 1
		echo 0 > /sys/class/leds/"$red"/brightness
	done
}

if [ -d /sys/class/power_supply/"$BATTERY" ]; then
	CAPACITY="$(cat /sys/class/power_supply/${BATTERY}/capacity)"

	if [ "$CAPACITY" -lt 25 ]; then
		logger "Battery capacity is less than 25 percent"
		ledsoff
		blink	
		ledsoff
	fi

	if [ "$CAPACITY" -lt 15 ]; then
		logger "Battery capacity is less than 15 percent"
		ledsoff
		blink	
		logger "Battery low. Powering off"
		poweroff
	fi
fi

Place the above script as check_battery_state.sh inside /etc/periodic/2min directory. Create the directory if needed. Make the script file executable.

Adding a cron entry

A crontab entry is needed to perform the scheduled battery check. Modify root's crontab to do the scheduled task.

$ crontab -u root -e

The command will open root's crontab file /var/spool/crontabs/root inside the vi text editor.

Note that the busybox crontab command doesn't parse $EDITOR environment variable, so if another text editor is preferred, open the root crontab file directly.

$ nano /var/spool/crontabs/root

Add a line to indicate that a new 2 minutes action will be performed.

# min   hour    day     month   weekday command
*/2     *       *       *       *       run-parts /etc/periodic/2min

Enabling the crond service

To enable the crond service so that crontab will be executed, execute the following command.

$ sudo systemctl enable crond.service

The crond service will be started automatically after rebooting.

To start the service immediately, run the following command.

$ /etc/init.d/crond start

The crond will execute this script every 2 minutes and the predefined low battery actions will be performed.

See also