battery.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. """System-battery read-out for the CLI/TUI status bar.
  2. Reads the host battery through ``psutil`` and exposes a compact, colour-coded label. Everything
  3. degrades to "unavailable" (no battery / read failure) so callers can render unconditionally. The
  4. status bar repaints on every keystroke, so :func:`read_battery` memoises the reading for a few seconds.
  5. """
  6. from __future__ import annotations
  7. import time
  8. from dataclasses import dataclass
  9. from typing import Optional
  10. @dataclass(frozen=True)
  11. class BatteryStatus:
  12. """One reading: ``percent`` clamped 0-100; ``plugged`` None when the platform can't tell."""
  13. available: bool
  14. percent: Optional[int] = None
  15. plugged: Optional[bool] = None
  16. @property
  17. def charging(self) -> bool:
  18. return bool(self.plugged)
  19. UNAVAILABLE = BatteryStatus(available=False)
  20. # Colour buckets, mirroring the status-bar context styles but inverted (full battery = "good").
  21. CATEGORY_GOOD = "good"
  22. CATEGORY_WARN = "warn"
  23. CATEGORY_BAD = "bad"
  24. CATEGORY_CRITICAL = "critical"
  25. CATEGORY_DIM = "dim"
  26. # (upper bound inclusive, category) for a discharging battery; first match wins.
  27. _LEVEL_CATEGORIES = ((10, CATEGORY_CRITICAL), (20, CATEGORY_BAD), (50, CATEGORY_WARN))
  28. _CACHE_TTL_SECONDS = 8.0
  29. _cache: Optional[tuple[float, BatteryStatus]] = None
  30. def _read_battery_uncached() -> BatteryStatus:
  31. try:
  32. import psutil
  33. # ``sensors_battery`` is missing on some platforms/builds of psutil.
  34. batt = psutil.sensors_battery()
  35. except Exception:
  36. return UNAVAILABLE
  37. if batt is None:
  38. return UNAVAILABLE
  39. percent: Optional[int] = None
  40. raw_percent = getattr(batt, "percent", None)
  41. if raw_percent is not None:
  42. try:
  43. percent = max(0, min(100, round(float(raw_percent))))
  44. except (TypeError, ValueError):
  45. percent = None
  46. plugged = getattr(batt, "power_plugged", None)
  47. return BatteryStatus(available=True, percent=percent, plugged=None if plugged is None else bool(plugged))
  48. def read_battery(use_cache: bool = True) -> BatteryStatus:
  49. """Return the current battery status (cached for a few seconds)."""
  50. global _cache
  51. if use_cache and _cache is not None and time.monotonic() - _cache[0] < _CACHE_TTL_SECONDS:
  52. return _cache[1]
  53. status = _read_battery_uncached()
  54. _cache = (time.monotonic(), status)
  55. return status
  56. def clear_cache() -> None:
  57. """Drop the memoised reading (used by tests)."""
  58. global _cache
  59. _cache = None
  60. def battery_category(status: BatteryStatus) -> str:
  61. """Bucket a reading into a colour category: good/warn/bad/critical/dim."""
  62. if not status.available or status.percent is None:
  63. return CATEGORY_DIM
  64. if status.charging: # on AC power the level isn't a concern
  65. return CATEGORY_GOOD
  66. for bound, category in _LEVEL_CATEGORIES:
  67. if status.percent <= bound:
  68. return category
  69. return CATEGORY_GOOD
  70. def battery_glyph(status: BatteryStatus) -> str:
  71. """Leading glyph: a bolt while charging, else a battery."""
  72. return "\u26a1" if status.charging else "\U0001f50b" # ⚡ / 🔋
  73. def format_battery(status: BatteryStatus) -> str:
  74. """Compact label like ``🔋 82%`` / ``⚡ 82%`` (empty if N/A)."""
  75. if not status.available or status.percent is None:
  76. return ""
  77. return f"{battery_glyph(status)} {status.percent}%"