Initial commit: Home Assistant MQTT bridge for monitor brightness (DDC/CI)
This commit is contained in:
commit
82cd5a8f2c
6 files changed
+283
No files matched your search
+14
@@ -0,0 +1,14 @@
|
|||||||
|
# Real config holds the MQTT credentials; config.example.json is the template
|
||||||
|
config.json
|
||||||
|
|
||||||
|
# Runtime files
|
||||||
|
pc_monitor.log
|
||||||
|
pc_monitor.lock
|
||||||
|
|
||||||
|
# Python
|
||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# Backups
|
||||||
|
*.bak
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# ha-monitor-brightness
|
||||||
|
|
||||||
|
Makes the PC monitor's brightness controllable from Home Assistant: the monitor appears as
|
||||||
|
`light.pc_monitor` (MQTT discovery) and its brightness is set over DDC/CI.
|
||||||
|
|
||||||
|
- Home Assistant 1-255 maps onto monitor brightness `min_level`..`max_level` (default 5-100).
|
||||||
|
- "Off" sets the minimum brightness; the monitor itself stays on.
|
||||||
|
- Brightness changed with the monitor's own buttons is reported back every `poll_seconds` (default 30).
|
||||||
|
- When the PC is off the light shows as unavailable.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
1. In Home Assistant create a user for the service (Settings → People → Users → Add user,
|
||||||
|
e.g. `pc-monitor`, "Can only log in from the local network"). The Mosquitto add-on accepts
|
||||||
|
Home Assistant users.
|
||||||
|
2. Create the virtual environment and install the dependencies:
|
||||||
|
`py -m venv .venv` then `.venv\Scripts\pip install -r requirements.txt`
|
||||||
|
3. Copy `config.example.json` to `config.json` and put that user's name and password in it.
|
||||||
|
`config.json` is ignored by git, so the credentials stay out of the repo.
|
||||||
|
4. Run once to test: `.venv\Scripts\python.exe pc_monitor_mqtt.py` (Ctrl+C to stop).
|
||||||
|
5. Start it at login (no console window): `start.vbs` in the Startup folder or a scheduled task.
|
||||||
|
|
||||||
|
The log is written to `pc_monitor.log` next to the script.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"host": "homeassistant.local",
|
||||||
|
"port": 1883,
|
||||||
|
"username": "pc-monitor",
|
||||||
|
"password": "change-me",
|
||||||
|
"client_id": "pc-monitor",
|
||||||
|
"unique_id": "pc_monitor",
|
||||||
|
"device_name": "PC monitor",
|
||||||
|
"model": "34WK95U",
|
||||||
|
"model_hint": "WK95U",
|
||||||
|
"min_level": 5,
|
||||||
|
"max_level": 100,
|
||||||
|
"poll_seconds": 30
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
"""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; 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":
|
||||||
|
self.on = False
|
||||||
|
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()
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
paho-mqtt>=2.0
|
||||||
|
monitorcontrol>=3.1
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
' Starts pc_monitor_mqtt.py without a console window (for the Startup folder or a scheduled task).
|
||||||
|
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||||
|
dir = fso.GetParentFolderName(WScript.ScriptFullName)
|
||||||
|
CreateObject("WScript.Shell").Run """" & dir & "\.venv\Scripts\pythonw.exe"" """ & dir & "\pc_monitor_mqtt.py""", 0, False
|
||||||
Reference in new issue
Block a user