home · contact · privacy
To sway status bar add battery status display.
authorPlom Heller <plom@plomlompom.com>
Mon, 14 Sep 2026 23:35:38 +0000 (01:35 +0200)
committerPlom Heller <plom@plomlompom.com>
Mon, 14 Sep 2026 23:35:38 +0000 (01:35 +0200)
home/user/.config/sway/status.py

index e3182457e49eed6b2f1d89de346ae494ff46e9dc..295b03f49391c4e1a6f5aaafadaf1d406dd1dc1a 100755 (executable)
@@ -6,17 +6,56 @@ from pathlib import Path
 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')},