display_control.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. """Display brightness and screen blanking control for SpoolBuddy kiosk.
  2. Brightness: DSI backlights are controlled via sysfs /sys/class/backlight/*/brightness.
  3. HDMI brightness is handled by the frontend via CSS filter.
  4. Blanking: The daemon tracks idle state and controls HDMI power via wlopm when
  5. available. NFC tag scans and scale weight changes wake the display
  6. automatically, and the idle timeout re-blanks it. swayidle handles
  7. touch-based wake/blank independently — both are idempotent via wlopm.
  8. """
  9. import logging
  10. import os
  11. import shutil
  12. import subprocess
  13. import time
  14. from pathlib import Path
  15. logger = logging.getLogger(__name__)
  16. BACKLIGHT_BASE = Path("/sys/class/backlight")
  17. class DisplayControl:
  18. def __init__(self):
  19. self._backlight_path = self._find_backlight()
  20. self._max_brightness = self._read_max_brightness()
  21. self._blank_timeout = 0 # seconds, 0 = disabled
  22. self._last_activity = time.monotonic()
  23. self._blanked = False
  24. self._wlopm_path = shutil.which("wlopm")
  25. self._wayland_env: dict[str, str] | None = None
  26. self._output = os.environ.get("SPOOLBUDDY_DISPLAY_OUTPUT", "HDMI-A-1")
  27. if self._backlight_path:
  28. logger.info("Backlight found: %s (max=%d)", self._backlight_path, self._max_brightness)
  29. else:
  30. logger.info("No DSI backlight found, brightness control via frontend CSS")
  31. if self._wlopm_path:
  32. logger.info("wlopm found at %s, HDMI wake/blank enabled", self._wlopm_path)
  33. else:
  34. logger.info("wlopm not found, HDMI wake/blank disabled")
  35. def _find_backlight(self) -> Path | None:
  36. if not BACKLIGHT_BASE.exists():
  37. return None
  38. for entry in BACKLIGHT_BASE.iterdir():
  39. brightness_file = entry / "brightness"
  40. if brightness_file.exists():
  41. return entry
  42. return None
  43. def _read_max_brightness(self) -> int:
  44. if not self._backlight_path:
  45. return 100
  46. try:
  47. return int((self._backlight_path / "max_brightness").read_text().strip())
  48. except Exception:
  49. return 255
  50. @property
  51. def has_backlight(self) -> bool:
  52. return self._backlight_path is not None
  53. def set_brightness(self, pct: int):
  54. """Set backlight brightness (0-100%). No-op if no backlight."""
  55. if not self._backlight_path:
  56. return
  57. pct = max(0, min(100, pct))
  58. value = round(self._max_brightness * pct / 100)
  59. try:
  60. (self._backlight_path / "brightness").write_text(str(value))
  61. logger.debug("Brightness set to %d%% (%d/%d)", pct, value, self._max_brightness)
  62. except PermissionError:
  63. logger.warning(
  64. "Permission denied writing to %s/brightness. Ensure spoolbuddy user is in the 'video' group.",
  65. self._backlight_path,
  66. )
  67. except Exception as e:
  68. logger.warning("Failed to set brightness: %s", e)
  69. def set_blank_timeout(self, seconds: int):
  70. """Set screen blank timeout in seconds. 0 = disabled."""
  71. self._blank_timeout = max(0, seconds)
  72. def wake(self):
  73. """Wake screen on activity (NFC tag, scale weight change)."""
  74. self._last_activity = time.monotonic()
  75. if self._blanked:
  76. self._unblank()
  77. def tick(self):
  78. """Called periodically from heartbeat loop. Blanks screen if idle."""
  79. if self._blank_timeout <= 0:
  80. if self._blanked:
  81. self._unblank()
  82. return
  83. idle = time.monotonic() - self._last_activity
  84. if not self._blanked and idle >= self._blank_timeout:
  85. self._blank()
  86. def _discover_wayland_env(self) -> dict[str, str] | None:
  87. """Discover WAYLAND_DISPLAY and XDG_RUNTIME_DIR for the kiosk session.
  88. The daemon runs as a systemd service outside the Wayland session, so
  89. these variables aren't inherited. We probe the same runtime dir that
  90. labwc uses (the daemon and kiosk run as the same user).
  91. """
  92. xdg = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
  93. runtime = Path(xdg)
  94. if not runtime.is_dir():
  95. return None
  96. for entry in sorted(runtime.iterdir()):
  97. if entry.name.startswith("wayland-") and not entry.name.endswith(".lock"):
  98. return {"WAYLAND_DISPLAY": entry.name, "XDG_RUNTIME_DIR": xdg}
  99. return None
  100. def _wlopm(self, on: bool) -> None:
  101. """Toggle HDMI output via wlopm. No-op if wlopm is unavailable."""
  102. if not self._wlopm_path:
  103. return
  104. # Retry discovery each call until the Wayland socket appears — labwc
  105. # may start after the daemon on boot.
  106. if self._wayland_env is None:
  107. self._wayland_env = self._discover_wayland_env()
  108. if self._wayland_env is None:
  109. logger.debug("No Wayland socket found, cannot control HDMI")
  110. return
  111. logger.info("Wayland session discovered: %s", self._wayland_env.get("WAYLAND_DISPLAY"))
  112. flag = "--on" if on else "--off"
  113. try:
  114. env = {**os.environ, **self._wayland_env}
  115. subprocess.run(
  116. [self._wlopm_path, flag, self._output],
  117. env=env,
  118. timeout=5,
  119. capture_output=True,
  120. )
  121. except Exception as e:
  122. logger.debug("wlopm %s %s failed: %s", flag, self._output, e)
  123. def _blank(self):
  124. self._blanked = True
  125. self._wlopm(on=False)
  126. logger.debug("Screen idle timeout reached, HDMI off")
  127. def _unblank(self):
  128. self._blanked = False
  129. self._wlopm(on=True)
  130. logger.debug("Activity detected, HDMI on")