#!/usr/bin/python3 import json import os import subprocess import time import typing def run_swaymsg() -> bytes: """Run swaymsg to get list of outputs.""" p = subprocess.run(["swaymsg", "-r", "-t", "get_outputs"], capture_output=True) return p.stdout def parse_json(outputs: bytes) -> dict[str, dict[str, typing.Any]]: """Parse get_outputs JSON.""" try: json_data = json.loads(outputs) except json.decoder.JSONDecodeError: print("JSON parse error") print(outputs) raise return {o["name"]: o for o in json_data} def sony_tv_connected() -> None: """Run command when HDMI is connected.""" subprocess.run([os.path.expanduser("~/bin/desk")]) def hdmi_disconnected() -> None: """Run command when HDMI is disconnected.""" subprocess.run([os.path.expanduser("~/bin/unplugged")]) def get_outputs(attempts: int = 10) -> dict[str, dict[str, typing.Any]] | None: """Ask sway for the current list of outputs.""" for attempt in range(attempts): outputs = run_swaymsg() if outputs.strip() == b"": return None try: return parse_json(outputs) except json.decoder.JSONDecodeError: if attempt == attempts - 1: raise time.sleep(1) return None def main() -> None: outputs = get_outputs() assert outputs if outputs["eDP-1"]["active"]: sony_tv_connected() else: hdmi_disconnected() if __name__ == "__main__": main()