From 71033afece74a138716e7013d1af06976d76c0f2 Mon Sep 17 00:00:00 2001 From: David Vazgenovich Shakaryan Date: Sun, 3 Mar 2024 01:06:31 -0800 Subject: add battery module (udev) --- panel.py | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) (limited to 'panel.py') diff --git a/panel.py b/panel.py index 8a11f9e..93db494 100755 --- a/panel.py +++ b/panel.py @@ -336,6 +336,68 @@ class ModInputAvail(Mod): self.refreshing = False self.repaint() +class ModBattery(Mod): + def __init__(self, battery, adapter=None, **kwargs): + super().__init__(**kwargs) + self.battery = battery + self.adapter = adapter + + self._percent = None + self._charging = None + + def work(self): + # FIXME copied from ModInputAvail. should abstract udev code. + p = subprocess.Popen( + ('udevadm', 'monitor', '-ups', 'power_supply'), + stdout=subprocess.PIPE, text=True) + + with open(f'/sys/class/power_supply/{self.battery}/capacity') as f: + percent = f.read().rstrip('\n') + charging = None + if self.adapter: + with open(f'/sys/class/power_supply/{self.adapter}/online') as f: + charging = (f.read().rstrip('\n') == '1') + self._update_state(percent, charging) + + building = False + for line in iter(p.stdout.readline, ''): + line = line.rstrip() + + if not building and line.startswith('UDEV'): + building = True + e = {} + elif building: + if '=' in line: + k, v = line.split('=', 1) + e[k] = v + else: + building = False + if e: + self._process_event(e) + + def _process_event(self, e): + if (e.get('ACTION') == 'change' and + (name := e.get('POWER_SUPPLY_NAME'))): + if (name == self.battery and + (cap := e.get('POWER_SUPPLY_CAPACITY'))): + self._update_state(percent=cap) + elif (name == self.adapter and + (online := e.get('POWER_SUPPLY_ONLINE'))): + self._update_state(charging=(online == '1')) + + def _update_state(self, percent=None, charging=None): + self.refreshing = True + if percent is not None: + self._percent = percent + if charging is not None: + self._charging = charging + buf = f'{self._percent}%%' + if self._charging: + buf += ' (charging)' + self.out = Fmt.labelled('BAT', buf) + self.refreshing = False + self.repaint() + class IntervalTimer(): def __init__(self): self.t = None @@ -427,7 +489,7 @@ class Panel: mod.run() self.panel = subprocess.Popen( - ('/home/david/lemonbar-xft/lemonbar', + ('/home/david/dev/lemonbar-xft/lemonbar', '-bf', 'Monospace:size=10:dpi=96', '-f', 'Monospace:size=10:dpi=96:bold', '-g', f'{self.width}x{self.height}', -- cgit v1.2.3-70-g09d2