dashboard/app/collect/power.py

48 lines
1.3 KiB
Python

import glob
from app.sample import Sample
_PS = "/sys/class/power_supply"
def _read(path: str) -> str | None:
try:
with open(path) as f:
return f.read().strip()
except OSError:
return None
def _supplies() -> list[tuple[str, str]]:
out: list[tuple[str, str]] = []
for p in sorted(glob.glob(f"{_PS}/*")):
t = _read(f"{p}/type")
if t:
out.append((t.lower(), p))
return out
def fill(s: Sample) -> None:
try:
supplies = _supplies()
for t, p in supplies:
if t == "battery" and _read(f"{p}/present") == "1":
cap = _read(f"{p}/capacity")
if cap is not None:
try:
s.battery = int(cap)
except ValueError:
pass
s.battery_status = _read(f"{p}/status")
break
for t, p in supplies:
if t == "mains" and _read(f"{p}/online") == "1":
s.ac_online = True
break
if s.ac_online is None:
for t, p in supplies:
if t == "usb" and _read(f"{p}/online") == "1":
s.ac_online = True
break
except OSError:
pass