Battery State Monitor Script

Oops, completely missed posting last weekend, mostly just because I'm too easily distracted. Such is life, hopefully I'll do two or three posts this weekend to even it up.

This is a simple script I wrote to notify me whenever my battery is running low on power. Basically to use it you just create a new shell script with the following in it and then run it using bash ~/bin/battery_monitor.sh & in your .xinitrc script. This should then check your battery status every minute and if it's below ten minutes remaining it will produce a warning message, after generating a warning it will wait five minutes before checking again to make sure it doesn't get really annoying.

#!/bin/bash
# Simple shell script that runs as a daemon to check the status of a Laptops
# battery and produce an error message every five minutes if it get's to
# less than 10 minutes of charge remaining and is not plugged in.

# Copyright (c) 2009, Timothy Pollard
#
# Redistribution and use with or without modification, are permitted provided
# that the above Copyright notification remains complete.

# The file that contains the state of the Battery
PROC_FILE=/proc/acpi/battery/BAT1/state

while true; do
    # Get the charging state from the PROC_FILE, this should be one of "charged",
    # "charging", or "discharging"
    CHARGING_STATE=$(cat $PROC_FILE | grep "^charging state:" | sed -e "s/charging state: *//g")
    
    if [ $CHARGING_STATE == "discharging" ]; then
        # Get the current rate and remaining capacity
        CURRENT_RATE=$(cat $PROC_FILE | grep "^present rate:" | sed -e "s/present rate: *//g" -e "s/ mW//g")
        REMAINING_CAPACITY=$(cat $PROC_FILE | grep "^remaining capacity:" | sed -e "s/remaining capacity: *//g" -e "s/ mWh//g")
    
        # Remaining battery life in minutes
        REMAINING_TIME=$(echo "scale=4; $REMAINING_CAPACITY/$CURRENT_RATE*60" | bc | sed -e "s/\..*//g")
    
        if [ $REMAINING_TIME -lt 10 ]; then
            xmessage -center "There are currently only $REMAINING_TIME minutes of battery life remaining."

            # Sleep for 4 minutes (4*60=240), this combined with the default
            # sleep of 60 seconds assures that you are only alerted once every 5
            # minutes
            sleep 240
        fi
    fi

    # Delay the next run for 60 seconds
    sleep 60
done
Categories: Computers, Scripting, Linux
Date: 2009-04-04 23:03:53, 8 years and 325 days ago

Leave reply

No html allowed in reply

Notify me of follow-up comments via email.