dashboard/app/collect/power.py

49 lines
1.4 KiB
Python

import glob
from typing import Any
_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 sample() -> dict[str, Any | None]:
out: dict[str, Any | None] = {"battery": None, "battery_status": None, "ac_online": 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:
out["battery"] = int(cap)
except ValueError:
pass
out["battery_status"] = _read(f"{p}/status")
break
for t, p in supplies:
if t == "mains" and _read(f"{p}/online") == "1":
out["ac_online"] = True
break
if out["ac_online"] is None:
for t, p in supplies:
if t == "usb" and _read(f"{p}/online") == "1":
out["ac_online"] = True
break
except OSError:
pass
return out