battery2go/server/battery2god

59 lines
No EOL
1.6 KiB
Python
Executable file

#!/usr/bin/env python3
import configparser
import argparse
import subprocess
import os
import time
upath=None
def read_values(output: str):
remaining = False
lines = [line.strip() for line in output.split("\n")]
for line in lines:
if line.startswith("time to"):
remaining = line.split(":")[-1].strip()
elif line.startswith("percentage"):
percentage = float(line.split(":")[-1].strip()[:-1])
elif line.startswith("state"):
charging = not "discharging" in line
return percentage, charging, remaining
def write_values(percentage: float, charging: bool, remaining: str, datafile: os.PathLike):
config = configparser.ConfigParser()
config["BATTERY"] = {
"percentage": percentage,
"charging": charging,
"remaining": remaining
}
with open(datafile, "w") as outfile:
config.write(outfile)
def run_upower(path=None):
global upath
if not (path or upath):
finder = subprocess.Popen(["upower", "-e"], stdout=subprocess.PIPE)
finder.wait()
for line in finder.stdout.read().decode().split("\n"):
if "BAT" in line:
upath = line
break
path = path or upath
info = subprocess.Popen(["upower", "-i", path], stdout=subprocess.PIPE)
info.wait()
return info.stdout.read().decode()
def run_loop(datafile):
while True:
write_values(*read_values(run_upower()), datafile)
time.sleep(1)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("datafile")
args = parser.parse_args()
run_loop(args.datafile)