from time import sleep
METADATA = {'version': 1}
+
PATH_THERMAL = Path('/sys/class/thermal')
GLOB_THERMAL = 'thermal_zone*/temp'
+PATH_POWER_SUPPLY = Path('/sys/class/power_supply')
+GLOB_BATTERY = 'BAT*'
+BATTERY_STATUS_SYMBOLS = {
+ 'Charging': '^',
+ 'Discharging': 'v',
+ 'Not charging': '-',
+}
+
+
+def int_at_path(
+ path: Path
+ ) -> int:
+ 'Read text file at path as integer representation.'
+ stripped_text = path.read_text(encoding='utf8').strip()
+ assert stripped_text[int(stripped_text[:1] == '-'):].isdigit()
+ return int(stripped_text)
+
+
+def battery_info(
+ ) -> str:
+ 'Produce battery charge, status, health status bar text.'
+ path_battery = next(PATH_POWER_SUPPLY.glob(GLOB_BATTERY))
+ status = BATTERY_STATUS_SYMBOLS.get(
+ (path_battery / 'status').read_text(encoding='utf8').strip(),
+ '?')
+ charge_pc, health_pc = -1, -1
+ for prefix in ('charge', 'energy'):
+ path_full = path_battery / f'{prefix}_full'
+ if path_full.exists():
+ full = int_at_path(path_full)
+ full_design = int_at_path(path_battery / f'{prefix}_full_design')
+ now = int_at_path(path_battery / f'{prefix}_now')
+ charge_pc = round(now / full * 100)
+ health_pc = round(full / full_design * 100)
+ break
+ return f'{charge_pc}%{status}{health_pc}%'
+
if __name__ == '__main__':
print(json_dumps(METADATA))
print('[', end='')
while True:
print(json_dumps([
+ {'full_text': battery_info()},
{'full_text': (
- str(round(max(int(path.read_text(encoding='utf8'))
+ str(round(max(int_at_path(path)
for path in PATH_THERMAL.glob(GLOB_THERMAL)
) / 1000))
+ '°C')},