1
0
src/bin/batterymonitor
2022-05-18 17:44:50 -04:00

55 lines
1.4 KiB
Bash
Executable File

#!/bin/sh
POLLING_FREQUENCY=1
# ISO 8601
alias date="date '+%Y-%m-%dT%T'"
emit() {
printf "[%s] " "$(date)"
echo "$@"
}
get_current_level() {
# adapted from other script i wrote, also in the public domain
if [ "$(uname)" = "Linux" ]; then
# this is a dirty hack.
# acpi | awk '{print $4}' will print the battery percentage,
# and s/,$// strips the trailing comma.
# acpi -a will just print the power adapter status.
printf "%b" "$(acpi | awk '{print $4}' | sed 's/,$//')"
return 0
elif [ "$(uname)" = "NetBSD" ]; then
printf "%b" "$(envstat -s acpibat0:charge \
| sed 1,2d \
| cut -d ':' -f 2 \
| awk '{print $1}' \
| cut -d '.' -f 1)"
return 0
else
printf "get_battery_status: unsupported OS" >>/dev/stderr
return 1
fi
}
! get_current_level >/dev/null \
&& printf "Unable to get battery status on this system.\n" >>/dev/stderr \
&& exit 1 \
|| true
current_level=$(get_current_level)
previous_level=$current_level
emit "$(printf "Current level: %d%%" "$current_level")"
while true; do
current_level=$(get_current_level)
if ! [ $current_level -eq $previous_level ]; then
[ $current_level -lt $previous_level ] \
&& emit "$(printf "Discharged: %d%% -> %d%%\n" $previous_level $current_level )" \
|| emit "$(printf " Charged: %d%% -> %d%%\n" $previous_level $current_level )"
previous_level=$current_level
fi
sleep $POLLING_FREQUENCY
done