"""Local control of the Tuya/SmartLife WiFi relays — no Tuya cloud in the loop. The relays pair via the SmartLife app (BLE-assisted onboarding) but once on WiFi they speak Tuya's local protocol on TCP 6668, which tinytuya drives directly. Each relay needs its device id + LOCAL KEY in config.json under "relays" — extracted once with `tinytuya wizard` (see the wiki: wifi-relays). tinytuya is synchronous/blocking, so every call runs in a worker thread via asyncio.to_thread to keep the OCPP socket responsive. """ import asyncio import logging try: import tinytuya except ImportError: # backend still runs (charger-only) without it tinytuya = None from .config import CONFIG log = logging.getLogger("relays") class RelayError(RuntimeError): pass def configured() -> dict: """The relay registry without secrets — safe to return over the API.""" return { name: {"label": cfg.get("label", name), "ip": cfg.get("ip", "auto")} for name, cfg in CONFIG["relays"].items() } def _device(name: str): if tinytuya is None: raise RelayError("tinytuya is not installed (pip install tinytuya)") cfg = CONFIG["relays"].get(name) if cfg is None: raise RelayError(f"unknown relay {name!r}; configured: {list(CONFIG['relays'])}") ip = cfg.get("ip", "auto") # "Auto" makes tinytuya find the device via its UDP broadcast (slower); # pin the IP in config.json (with a DHCP reservation) once known. dev = tinytuya.OutletDevice( cfg["id"], ip if ip and ip != "auto" else "Auto", cfg["key"] ) dev.set_version(float(cfg.get("version", 3.3))) dev.set_socketTimeout(5) return dev, str(cfg.get("switch", 1)) def _check(name: str, result) -> dict: if not isinstance(result, dict) or "dps" not in result: raise RelayError(f"relay {name!r} did not answer: {result!r}") return result["dps"] def _status_sync(name: str) -> dict: dev, sw = _device(name) dps = _check(name, dev.status()) return {"relay": name, "on": bool(dps.get(sw)), "dps": dps} def _switch_sync(name: str, on: bool) -> dict: dev, sw = _device(name) result = dev.set_status(on, int(sw)) # some firmwares reply with the new dps, some with an empty ack — verify if not (isinstance(result, dict) and "dps" in result): result = dev.status() dps = _check(name, result) actual = bool(dps.get(sw, on)) if actual != on: raise RelayError(f"relay {name!r} did not switch (wanted {on}, reads {actual})") return {"relay": name, "on": actual} async def status(name: str) -> dict: return await asyncio.to_thread(_status_sync, name) async def switch(name: str, on: bool) -> dict: return await asyncio.to_thread(_switch_sync, name, on) async def toggle(name: str) -> dict: current = await status(name) return await switch(name, not current["on"]) async def status_all() -> dict: """Poll every configured relay concurrently; errors become per-relay strings.""" names = list(CONFIG["relays"]) results = await asyncio.gather(*(status(n) for n in names), return_exceptions=True) out = {} for name, res in zip(names, results): if isinstance(res, BaseException): out[name] = {"relay": name, "error": str(res)} else: out[name] = res out[name]["label"] = CONFIG["relays"][name].get("label", name) return out