From 5b0230806bc31d53c04aa66ad7fd5eb3f8e142fa Mon Sep 17 00:00:00 2001 From: DTB Date: Sun, 19 Nov 2023 20:49:46 -0700 Subject: [PATCH] clean up battery code --- niceties/battery.linux | 6 +++--- niceties/battery.netbsd | 11 +++++++---- niceties/batterymonitor | 34 ++++++++++++++++------------------ 3 files changed, 26 insertions(+), 25 deletions(-) diff --git a/niceties/battery.linux b/niceties/battery.linux index adc49d7..22fa29e 100755 --- a/niceties/battery.linux +++ b/niceties/battery.linux @@ -1,6 +1,6 @@ #!/bin/sh # this is a dirty hack. -# acpi | awk '{print $4}' will print the battery percentage, -# and s/,$// strips the trailing comma. -acpi | awk '{print $4}' | sed 's/,$//' +# acpi | awk '{print $4}' will print the battery percentage, stripping the +# trailing comma +acpi | awk '{sub(",$", "", $4); print $4}' diff --git a/niceties/battery.netbsd b/niceties/battery.netbsd index 7e32eff..d7e4e18 100755 --- a/niceties/battery.netbsd +++ b/niceties/battery.netbsd @@ -1,7 +1,10 @@ #!/bin/sh envstat -s acpibat0:charge \ - | sed 1,2d \ - | cut -d ':' -f 2 \ - | awk '{print $1}' \ - | cut -d '.' -f 1 + | awk ' +NR == 3 { + sub("^[^:]*:", "", $1); + sub(":.*", "", $1); + sub("\\..*", "", $1); + print $1; +}' diff --git a/niceties/batterymonitor b/niceties/batterymonitor index e621e19..85e15e9 100755 --- a/niceties/batterymonitor +++ b/niceties/batterymonitor @@ -1,33 +1,31 @@ #!/bin/sh +set -e + POLLING_FREQUENCY=1 -# ISO 8601 -alias date="date '+%Y-%m-%dT%T'" -emit() { - printf "[%s] " "$(date)" - echo "$@" -} +alias date='printf "[%s] " "$(date +%Y-%m-%dT%T)"' # ISO 8601 ! battery >/dev/null 2>&1 \ - && printf "Unable to get battery status on this system.\n" 1>&2 \ - && exit 1 \ - || true + && ! printf "%s: Unable to get battery status on this system.\n" "$0" \ + 1>&2 -current_level=$(battery) -previous_level=$current_level +current_level="$(battery)" +previous_level="$current_level" -emit "$(printf "Current level: %d%%" "$current_level")" +date; printf "Current level: %d%%\n" "$current_level" while true; do - current_level=$(battery) - if ! streq $current_level $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 )" + current_level="$(battery)" + date; if ! streq "$current_level" "$previous_level"; then + printf '%s: %s%% -> %s%%\n' "$( + test "$current_level" -lt "$previous_level" \ + && printf 'Discharged' \ + || printf ' Charged')" \ + "$previous_level" "$current_level" previous_level=$current_level fi - sleep $POLLING_FREQUENCY + sleep "$POLLING_FREQUENCY" done