Reporting OFF made Adaptive Lighting stop adapting the monitor. The screen never really turns off, so "off" now sets the minimum brightness and the light stays on at brightness 1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
231 lines
8.7 KiB
Python
231 lines
8.7 KiB
Python
"""Expose the PC monitor's brightness (DDC/CI) to Home Assistant as an MQTT light.
|
|
|
|
The light is announced with MQTT discovery, so Home Assistant (and Adaptive Lighting)
|
|
can set the brightness. Changes made on the monitor itself (OSD buttons) are polled and
|
|
reported back, so Home Assistant sees them as manual changes.
|
|
|
|
"Off" in Home Assistant sets the monitor to its minimum brightness and keeps reporting
|
|
it as on (1), so Adaptive Lighting keeps adapting it; the monitor is not
|
|
switched off (power control over DDC/CI is unreliable).
|
|
"""
|
|
|
|
import json
|
|
import logging
|
|
import signal
|
|
import sys
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import paho.mqtt.client as mqtt
|
|
from monitorcontrol import get_monitors
|
|
|
|
CONFIG_FILE = Path(__file__).with_name("config.json")
|
|
log = logging.getLogger("pc_monitor")
|
|
|
|
|
|
class Monitor:
|
|
"""Brightness of one monitor over DDC/CI (VCP 0x10, 0-100)."""
|
|
|
|
def __init__(self, model_hint):
|
|
self.model_hint = model_hint
|
|
self.lock = threading.Lock()
|
|
self._monitor = None
|
|
|
|
def _find(self):
|
|
monitors = get_monitors()
|
|
if not monitors:
|
|
raise RuntimeError("no DDC/CI monitor found")
|
|
if self.model_hint:
|
|
for m in monitors:
|
|
with m:
|
|
try:
|
|
if self.model_hint.lower() in str(m.get_vcp_capabilities().get("model", "")).lower():
|
|
return m
|
|
except Exception: # capabilities are optional; fall back to the first monitor
|
|
pass
|
|
return monitors[0]
|
|
|
|
def _cached(self):
|
|
# Finding the monitor reads its capabilities string, which is slow; do it once and
|
|
# reuse the handle, and look it up again only after an error (e.g. monitor replugged).
|
|
if self._monitor is None:
|
|
self._monitor = self._find()
|
|
return self._monitor
|
|
|
|
def get(self):
|
|
with self.lock:
|
|
try:
|
|
with self._cached() as m:
|
|
return int(m.get_luminance())
|
|
except Exception:
|
|
self._monitor = None
|
|
raise
|
|
|
|
def set(self, level):
|
|
with self.lock:
|
|
try:
|
|
with self._cached() as m:
|
|
m.set_luminance(int(level))
|
|
except Exception:
|
|
self._monitor = None
|
|
raise
|
|
|
|
|
|
class Bridge:
|
|
def __init__(self, cfg):
|
|
self.cfg = cfg
|
|
self.monitor = Monitor(cfg.get("model_hint", ""))
|
|
self.min_level = int(cfg.get("min_level", 5))
|
|
self.max_level = int(cfg.get("max_level", 100))
|
|
base = cfg.get("topic", "pc_monitor")
|
|
self.t_set, self.t_state, self.t_avail = f"{base}/set", f"{base}/state", f"{base}/availability"
|
|
self.on = True
|
|
self.brightness = 255 # Home Assistant scale 1-255
|
|
self.last_level = None
|
|
self.read_failing = False
|
|
self.stop = threading.Event()
|
|
|
|
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=cfg.get("client_id", "pc-monitor"))
|
|
if cfg.get("username"):
|
|
self.client.username_pw_set(cfg["username"], cfg.get("password", ""))
|
|
self.client.will_set(self.t_avail, "offline", retain=True)
|
|
self.client.on_connect = self.on_connect
|
|
self.client.on_message = self.on_message
|
|
|
|
# --- mapping between Home Assistant brightness (1-255) and the monitor (min..max) ---
|
|
def to_level(self, brightness):
|
|
return round(self.min_level + (max(1, min(255, brightness)) - 1) * (self.max_level - self.min_level) / 254)
|
|
|
|
def to_brightness(self, level):
|
|
level = max(self.min_level, min(self.max_level, level))
|
|
span = max(1, self.max_level - self.min_level)
|
|
return max(1, round(1 + (level - self.min_level) * 254 / span))
|
|
|
|
# --- MQTT ---
|
|
def discovery(self):
|
|
uid = self.cfg.get("unique_id", "pc_monitor")
|
|
return {
|
|
"name": None,
|
|
"unique_id": uid,
|
|
"default_entity_id": "light.pc_monitor",
|
|
"schema": "json",
|
|
"command_topic": self.t_set,
|
|
"state_topic": self.t_state,
|
|
"availability_topic": self.t_avail,
|
|
"brightness": True,
|
|
"brightness_scale": 255,
|
|
"supported_color_modes": ["brightness"],
|
|
"icon": "mdi:monitor",
|
|
"device": {
|
|
"identifiers": [uid],
|
|
"name": self.cfg.get("device_name", "PC monitor"),
|
|
"manufacturer": "LG",
|
|
"model": self.cfg.get("model", "34WK95U"),
|
|
},
|
|
}
|
|
|
|
def on_connect(self, client, userdata, flags, reason_code, properties):
|
|
if reason_code.is_failure:
|
|
log.error("MQTT connect failed: %s", reason_code)
|
|
return
|
|
log.info("connected to MQTT")
|
|
prefix = self.cfg.get("discovery_prefix", "homeassistant")
|
|
client.publish(f"{prefix}/light/{self.cfg.get('unique_id', 'pc_monitor')}/config",
|
|
json.dumps(self.discovery()), retain=True)
|
|
client.subscribe(self.t_set)
|
|
client.publish(self.t_avail, "online", retain=True)
|
|
self.read_and_publish(force=True)
|
|
|
|
def on_message(self, client, userdata, msg):
|
|
try:
|
|
cmd = json.loads(msg.payload)
|
|
except ValueError:
|
|
log.warning("ignoring non-JSON command: %r", msg.payload)
|
|
return
|
|
if cmd.get("state") == "OFF":
|
|
# The screen never really turns off, so stay "on" at the lowest brightness.
|
|
# Reporting OFF would make Adaptive Lighting stop adapting the monitor.
|
|
self.on = True
|
|
self.brightness = 1
|
|
self.apply(self.min_level)
|
|
else:
|
|
self.on = True
|
|
if "brightness" in cmd:
|
|
self.brightness = int(cmd["brightness"])
|
|
self.apply(self.to_level(self.brightness))
|
|
self.publish_state()
|
|
|
|
def apply(self, level):
|
|
try:
|
|
self.monitor.set(level)
|
|
self.last_level = level
|
|
log.info("brightness -> %s", level)
|
|
except Exception as e:
|
|
log.warning("could not set brightness: %s", e)
|
|
|
|
def publish_state(self):
|
|
payload = {"state": "ON" if self.on else "OFF", "brightness": self.brightness, "color_mode": "brightness"}
|
|
self.client.publish(self.t_state, json.dumps(payload), retain=True)
|
|
|
|
def read_and_publish(self, force=False):
|
|
"""Report changes made on the monitor itself (OSD buttons)."""
|
|
try:
|
|
level = self.monitor.get()
|
|
except Exception as e:
|
|
if not self.read_failing: # log once, not every poll
|
|
log.warning("could not read brightness: %s", e)
|
|
self.read_failing = True
|
|
return
|
|
self.read_failing = False
|
|
if force or (self.last_level is not None and abs(level - self.last_level) > 1):
|
|
self.last_level = level
|
|
if self.on or force:
|
|
self.on = True
|
|
self.brightness = self.to_brightness(level)
|
|
log.info("monitor reports %s", level)
|
|
self.publish_state()
|
|
elif self.last_level is None:
|
|
self.last_level = level
|
|
|
|
def run(self):
|
|
self.client.connect_async(self.cfg.get("host", "homeassistant.local"), int(self.cfg.get("port", 1883)))
|
|
self.client.loop_start()
|
|
interval = float(self.cfg.get("poll_seconds", 30))
|
|
while not self.stop.wait(interval):
|
|
if self.client.is_connected():
|
|
self.read_and_publish()
|
|
self.client.publish(self.t_avail, "offline", retain=True).wait_for_publish(2)
|
|
self.client.loop_stop()
|
|
self.client.disconnect()
|
|
|
|
|
|
def single_instance():
|
|
"""Exit if another copy is already running: two copies with the same MQTT client id
|
|
would keep disconnecting each other. Returns the lock file handle (keep it open)."""
|
|
import msvcrt
|
|
|
|
handle = open(Path(__file__).with_name("pc_monitor.lock"), "w")
|
|
try:
|
|
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
except OSError:
|
|
log.info("another instance is already running; exiting")
|
|
sys.exit(0)
|
|
return handle
|
|
|
|
|
|
def main():
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
|
|
handlers=[logging.FileHandler(Path(__file__).with_name("pc_monitor.log"), encoding="utf-8"),
|
|
logging.StreamHandler(sys.stdout)])
|
|
lock = single_instance() # noqa: F841 - held for the lifetime of the process
|
|
cfg = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
|
bridge = Bridge(cfg)
|
|
signal.signal(signal.SIGINT, lambda *_: bridge.stop.set())
|
|
signal.signal(signal.SIGTERM, lambda *_: bridge.stop.set())
|
|
bridge.run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|