Created
August 22, 2016 03:11
-
-
Save lukassup/caa43c839c1e235172e6e63edac84948 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import os | |
import subprocess | |
from shutil import which # Python 3.3 | |
# Reset locale | |
os.environ.setdefault("LC_ALL", "C") | |
class UPowerBatteryMonitor(object): | |
"""UPower Battery Monitor utility""" | |
BINARY = "upower" | |
def __init__(self): | |
binary = which(self.BINARY) | |
if binary: | |
self.binary = binary | |
else: | |
raise Exception("Cannot find '{0}' in path".format(self.BINARY)) | |
self.discover_batteries() | |
def discover_batteries(self): | |
batteries = [] | |
output = subprocess.run( # Python 3.5 | |
[self.binary, "-e"], | |
check=True, | |
stdout=subprocess.PIPE).stdout.decode() | |
for line in output.splitlines(): | |
if "battery" in line: | |
batteries.append(line) | |
self.batteries = dict().fromkeys(batteries, {}) | |
def get_stats(self): | |
for battery in self.batteries: | |
self.batteries[battery] = {} | |
output = subprocess.run( # Python 3.5 | |
[self.binary, "-i", battery], | |
check=True, | |
stdout=subprocess.PIPE).stdout.decode() | |
for line in output.splitlines(): | |
stat = line.strip().partition(":") | |
if all(stat): | |
k = stat[0].replace(" ", "-") | |
v = stat[2].strip() | |
self.batteries[battery][k] = v | |
def batteries_by_state(self, state): | |
batts_by_state = [] | |
for battery, stats in self.batteries.items(): | |
if stats["state"].lower() == state: | |
batts_by_state.append(battery) | |
return {state: batts_by_state} | |
def discharging(self): | |
return self.batteries_by_state("discharging") | |
def charging(self): | |
return self.batteries_by_state("charging") | |
def fully_charged(self): | |
return self.batteries_by_state("fully-charged") | |
def levels(self): | |
levels = {} | |
for battery, stats in self.batteries.items(): | |
levels[battery] = stats["percentage"] | |
return levels | |
if __name__ == "__main__": | |
import sys | |
try: | |
import pprint | |
p = pprint.PrettyPrinter(indent=2) | |
bmon = UPowerBatteryMonitor() | |
bmon.get_stats() | |
p.pprint(bmon.batteries) | |
p.pprint(bmon.charging()) | |
p.pprint(bmon.discharging()) | |
p.pprint(bmon.fully_charged()) | |
p.pprint(bmon.levels()) | |
except Exception as e: | |
print(e) | |
sys.exit(1) | |
else: | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment