battery-notify

battery level notifier
git clone git://git.pyratebeard.net/battery-notify.git
Log | Files | Refs | README

check-batt (2138B)


      1 #!/usr/bin/env bash
      2 
      3 BAT_NUM='0'
      4 STATUS_FILE=/tmp/check-bat.tmp
      5 BATTPERC=$(cat /sys/class/power_supply/BAT${BAT_NUM}/capacity)
      6 BATTSTATUS=$(cat /sys/class/power_supply/BAT${BAT_NUM}/status)
      7 LAST_STATUS=''
      8 LAST_NOTIF_LEVEL=0
      9 NOTIF_LEVEL=0
     10 CHECK="N"
     11 
     12 if [ -e $STATUS_FILE ] ; then
     13 	. $STATUS_FILE
     14 fi
     15 
     16 save_status() {
     17 	LAST_STATUS=$BATTSTATUS
     18 	echo "LAST_STATUS=${BATTSTATUS}" > $STATUS_FILE
     19 	echo "LAST_NOTIF_LEVEL=${NOTIF_LEVEL}" >> $STATUS_FILE
     20 }
     21 
     22 notify() {
     23 	level=$1
     24 	msg=$2
     25 	DISPLAY=:0 /usr/bin/notify-send -t 3500 -u "$level" "POWER" "$msg"
     26 }
     27 
     28 while getopts "c" arg ; do
     29 	case "$arg" in
     30 		c) CHECK="Y" ;;
     31 	esac
     32 done
     33 
     34 if [[ "$CHECK" == "Y" ]] ; then
     35 	notify "normal" "battery is now $BATTSTATUS, Capacity: $BATTPERC"
     36 	exit
     37 fi
     38 
     39 # Battery status changed
     40 LAST_STATUS=$(grep ^LAST_STATUS $STATUS_FILE | awk -F= '{print $2}')
     41 if [[ "$BATTSTATUS" != "$LAST_STATUS" ]] ; then
     42 	notify "normal" "battery is now $BATTSTATUS, Capacity: $BATTPERC"
     43 	save_status
     44 	exit
     45 fi
     46 
     47 if [ "$BATTSTATUS" = Discharging ] && [ "$BATTPERC" -le 10 ]; then
     48 	NOTIF_LEVEL=10
     49 	notify "critical" "battery is less than 10% - Connect charger, going to sleep in 10s"
     50 	sleep 10
     51 	BATTSTATUS=$(cat /sys/class/power_supply/BAT${BAT_NUM}/status)
     52 	if [ "$BATTSTATUS" = Discharging ]; then
     53 		notify "critical" "going to suspend now"
     54 		sleep 3
     55 		logger "Critical battery threshold, suspending"
     56 		systemctl suspend
     57 	else
     58 		notify "normal" "battery is now charging, cancelling suspend"
     59 	fi
     60 	save_status
     61 	exit
     62 fi
     63 
     64 if [ "$BATTPERC" -le 20 ] && [ ! "$BATTSTATUS" = Charging ] ; then
     65 	NOTIF_LEVEL=20
     66 	notify "critical" "battery $BATTSTATUS is less than 20%"
     67 	save_status
     68 elif [[ $BATTPERC -le 30 ]] ; then
     69 	NOTIF_LEVEL=30
     70 	if [ "$NOTIF_LEVEL" != "$LAST_NOTIF_LEVEL" ]; then
     71 		notify "normal" "battery $BATTSTATUS is at 30%"
     72 		save_status
     73 	fi
     74 elif [[ $BATTPERC -le 50 ]] ; then
     75 	NOTIF_LEVEL=50
     76 	if [ "$NOTIF_LEVEL" != "$LAST_NOTIF_LEVEL" ] ; then
     77 		notify "low" "battery $BATTSTATUS is at 50%"
     78 		save_status
     79 	fi
     80 elif [[ $BATTPERC -le 60 ]] ; then
     81 	NOTIF_LEVEL=60
     82 	if [ "$NOTIF_LEVEL" != "$LAST_NOTIF_LEVEL" ] ; then
     83 		notify "normal" "battery $BATTSTATUS is at 60%"
     84 		save_status
     85 	fi
     86 fi
     87