How to set up a low battery warning in XMonad

Date created: 2020-1-6

Last updated: 2020-1-6

I currently use XMonad as my window manager on my Dell XPS 15. However I had the issue that when I was working without being plugged in the laptop would frequently automatically shutdown with little warning when the battery was low.

Therefore, I decided to do some googling to see how to get a warning when using a window manager like XMonad and came across a post where a user suggested using cron and osd_cat.

osd_cat is a small program which allows you to display a message in X. It can be installed on Fedora 27 with the following command:

$ sudo yum install xosd
To show a warning when the battery is low I wrote the following short python script:
from subprocess import Popen, PIPE

with open("/sys/class/power_supply/BAT0/charge_now") as f:
    charge_now = float(f.read())
with open("/sys/class/power_supply/BAT0/charge_full") as f:
    charge_full = float(f.read())

percent = 100*charge_now/charge_full

if percent < 20:
    p = Popen(['osd_cat','-A','center','-p','middle','-f','-*-*-bold-*-*-*-36-120-*-*-*-*-*-*','-cred','-s','5'],stdin=PIPE)
    p.communicate(input="Battery Low!")
    p.wait()
and saved it as ~/power_warning.py. Then I added the following cron job:
DISPLAY=:0.0
PATH=/usr/bin

* * * * * python ~/power_warning.py