fix battery usage

This commit is contained in:
2025-09-29 11:36:33 +02:00
parent fe87de7580
commit c4e522f17a
5 changed files with 177 additions and 50 deletions

View File

@@ -1,38 +1,13 @@
import psutil
from gi.repository import GLib
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.image import Image
from fabric import Fabricator
class BatteryProvider:
def __init__(self):
self.bat_percent = 0.0
self.bat_charging = None
self._update()
GLib.timeout_add_seconds(1, self._update)
def _update(self):
battery = psutil.sensors_battery()
if battery is None:
self.bat_percent = 0.0
self.bat_charging = None
else:
self.bat_percent = battery.percent
self.bat_charging = battery.power_plugged
return True
def get_battery(self):
return (self.bat_percent, self.bat_charging)
from bar.services.battery import BatteryService
class Battery(Box):
def __init__(self, **kwargs):
super().__init__(name="battery-widget", orientation="h", spacing=4, **kwargs)
self.bat_provider = BatteryProvider()
self.bat_icon = Image(
name="bat-icon", icon_name="battery-full-symbolic", icon_size=16
@@ -40,18 +15,17 @@ class Battery(Box):
self.bat_label = Label(name="bat-label", label="100%")
self.bat_fabricator = Fabricator(
poll_from=lambda *_: self.bat_provider.get_battery(),
on_changed=self.update_battery,
interval=1000,
stream=False,
default_value=(100, False),
)
# Create battery service with signal-based updates
self.battery_service = BatteryService(update_interval=10000) # Check every 10 seconds
self.battery_service.connect("battery-changed", self.update_battery)
self.children = [self.bat_icon, self.bat_label]
self.show_all()
GLib.idle_add(self.update_battery, None, self.bat_provider.get_battery())
# Initialize with current battery status
initial_percent = self.battery_service.percent
initial_charging = self.battery_service.charging
GLib.idle_add(self.update_battery, None, initial_percent, initial_charging)
def _icon_lookup(self, bat, charging):
# Round to nearest 10 for level-based icons
@@ -62,19 +36,16 @@ class Battery(Box):
else:
return f"battery-level-{level}-symbolic"
def update_battery(self, sender, battery_data):
value, charging = battery_data
icon_name = self._icon_lookup(value, charging)
def update_battery(self, service, percent, charging):
"""Update battery display when battery status changes"""
icon_name = self._icon_lookup(percent, charging)
self.bat_icon.set_property("icon-name", icon_name)
self.bat_label.set_text(f"{int(value)}%")
self.bat_label.set_text(f"{int(percent)}%")
if value < 20 and not charging:
if percent < 20 and not charging:
self.bat_label.add_style_class("battery-low")
self.bat_icon.add_style_class("battery-low")
else:
self.bat_label.remove_style_class("battery-low")
self.bat_icon.remove_style_class("battery-low")
return True