from time import sleep from phue import Bridge from pathlib import Path class HueHandler: """Handler for Hue API calls.""" registered_ips_file = "hue_bridge_registered.txt" def __init__(self, bridge_ip: str): """Initialize the HueHandler.""" self.bridge = None self.connect(bridge_ip) def connect(self, bridge_ip: str): if bridge_ip in self.get_registered_ips(): self.bridge = Bridge(bridge_ip) self.bridge.connect() return # Connect loop while True: try: self.bridge = Bridge(bridge_ip) self.bridge.connect() break except Exception as e: print(f"Failed to connect to bridge: {bridge_ip}") print(e) print("Trying again in 5 seconds..") sleep(5) self.register_bridge(bridge_ip) def get_registered_ips(self) -> list: """Get a list of registered bridge IPs.""" if not Path(HueHandler.registered_ips_file).is_file(): return [] with open(HueHandler.registered_ips_file, "r") as f: return f.readlines() def register_bridge(self, bridge_ip: str): """Register a bridge IP.""" with open(HueHandler.registered_ips_file, "a") as f: f.write(bridge_ip + "\n") def list_scenes(self) -> dict: return self.bridge.get_scene() def get_scene_by_name(self, name): for key, scene in self.list_scenes().items(): if scene["name"] == name: scene["id"] = key return scene return None def in_room_activate_scene(self, room_name: str, scene_name: str): """Activate a scene in a room. Args: scene (str): The name of the scene to activate. room (str): The name of the room to activate the scene in. """ scene_id = self.get_scene_by_name(scene_name)["id"] if scene_id is None: raise "Scene not found." self.bridge.set_group(room_name, {"scene": scene_id}) def in_room_deactivate_lights(self, room_name: str): """Deactivate all lights in a room. Args: room_name (str): The name of the room to deactivate the lights in. """ self.bridge.set_group(room_name, {"on": False}) def in_room_activate_lights(self, room_name: str): """Activate all lights in a room. Args: room_name (str): The name of the room to activate the lights in. """ self.bridge.set_group(room_name, {"on": True})