domingo, 20 de diciembre de 2009

How to make your own laptop battery drain alarm for linux

Helo, many times I have lost my work because of a laptop battery drain.
If you use linux and dont want to use something like gnome, or kde, I personally
use awesome, the tiling window manager, you should have some way to know
when your laptop battery is about to drain.
What I did is a small python script, runnig with cron. I took me, about less than an hour to build
the script, and I think it could be helpful to you.

These are the ingredients you need:

1 - python
2 - acpi
2 - mplayer or any other command line media player
3 - cron
4 - linux

The small python script is as follows:


import subprocess
from subprocess import call

plug_now_audio = "~/tts.wav"
p = subprocess.Popen("acpi",stdout=subprocess.PIPE)
str = p.communicate()[0]
remaining_minutes = str.split(":")[2]
alarm_minutes_before = 10
if ((str.find("Discharging")!=-1) and (int(remaining_minutes) < alarm_minutes_before)) :
print "Plug the cord!"
call(["mplayer",plug_now_audio])
else:
print "You still have time"


Now follow these steps:

  • Copy this script to your /usr/bin directory for example.

  • Now go to your crontab file and add the following line:

9 * * * * root python /usr/bin/battery.py

This means the battery.py script will run every 9 minutes to check the battery status

  • Restart the cron service:
sudo /etc/init.d/crond restart

(Check the cron you have installed with your distro, I have gentoo and I did it by typing: sudo /etc/init.d/vixie-cron restart )

  • Get a sound or in my case liked the idea of an automated voice like this:
Download tts.wav
Verify the path to the sound is correct in the script

  • Verify you have all the requeriments installed, if so do it by:
sudo apt-get install python
sudo apt-get install acpi
sudo apt-get install mplayer

Cron comes by default with most distros

  • That's it, enjoy going everywhere without the cord, and when the battery is almost drain, go and plug it.
Comments or questions are wellcome.