Skip to content

Instantly share code, notes, and snippets.

@monstermunchkin
Last active December 20, 2015 11:19
Show Gist options
  • Save monstermunchkin/6121968 to your computer and use it in GitHub Desktop.
Save monstermunchkin/6121968 to your computer and use it in GitHub Desktop.
Low battery warning with i3-nagbar
#!/usr/bin/env python
import signal
import subprocess
import time
import sys
test = False
def close_fullscreen():
x, y = subprocess.check_output(
['xdotool', 'getdisplaygeometry']).decode().split()
window_id = subprocess.check_output(
['xdotool', 'getactivewindow']).decode().strip()
geometry = subprocess.check_output(
['xdotool', 'getwindowgeometry', window_id]).decode().split()
if geometry[3] == '0,0' and geometry[7] == '{}x{}'.format(x, y):
# toggle full screen mode
subprocess.call(['xdotool', 'key', 'alt+f'])
def handler(signum, frame):
global test
# exit full screen mode if needed
try:
close_fullscreen()
except:
pass
# Broadcast message
subprocess.call("echo 'Battery level is critical.'|wall", shell=True)
# fork process
p = subprocess.Popen(
['i3-nagbar', '-t', 'error', '-m',
'Battery level is critical.'])
if test:
time.sleep(4)
p.terminate()
return
while True:
try:
with open('/sys/class/power_supply/BAT0/status') as f:
status = f.read().strip()
except:
p.terminate()
return
if status and status != 'Discharging':
p.terminate()
return
time.sleep(1)
def main(argv=[]):
timeout = 60
signal.signal(signal.SIGALRM, handler)
if argv and argv[0] == 'test':
global test
test = True
signal.alarm(1)
time.sleep(1)
sys.exit(0)
while True:
try:
with open('/sys/class/power_supply/BAT0/status') as f:
status = f.read().strip()
except:
pass
else:
if status == 'Discharging':
try:
with open('/sys/class/power_supply/BAT0/capacity') as f:
level = int(f.read())
except:
pass
else:
if level < 2:
signal.alarm(1)
elif level < 5:
timeout = 15
elif level < 10:
timeout = 30
else:
timeout = 60
finally:
time.sleep(timeout)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment