"""Мост Яндекс Умный дом → MQTT (discovery) → Home Assistant.""" import json import threading import time import urllib.error import urllib.request import paho.mqtt.client as mqtt TOKEN_FILE = "/root/.yandex-mtoken" MQTT_HOST = "192.168.1.107" MQTT_USER, MQTT_PASS = "hub", "hubmqtt" PREFIX = "homeassistant" API = "https://api.iot.yandex.net/v1.0" POLL = 30 SKIP_PREFIX = ("devices.types.hub", "devices.types.smart_speaker", "devices.types.sensor.button") _tok = "" _known = {} _lock = threading.Lock() def token(): return open(TOKEN_FILE, encoding="utf-8").read().strip() def api_get(path): req = urllib.request.Request(API + path, headers={"Authorization": "OAuth " + _tok}) with urllib.request.urlopen(req, timeout=20) as r: return json.loads(r.read() or b"{}") def api_action(dev_id, actions): body = json.dumps({"devices": [{"id": dev_id, "actions": actions}]}).encode() req = urllib.request.Request(API + "/devices/actions", data=body, method="POST", headers={"Authorization": "OAuth " + _tok, "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=20) as r: return r.status except urllib.error.HTTPError as e: return "HTTP %s" % e.code except Exception as e: return str(e)[:60] def capability(dev, ctype, instance=None): for c in dev.get("capabilities") or []: if c.get("type") != ctype: continue if instance and (c.get("state") or {}).get("instance") != instance: continue return c return None def cap_value(dev, ctype, instance=None): c = capability(dev, ctype, instance) return None if not c else (c.get("state") or {}).get("value") def prop_value(dev, ptype, instance=None): for p in dev.get("properties") or []: if p.get("type") != ptype: continue if instance and (p.get("state") or {}).get("instance") != instance: continue return (p.get("state") or {}).get("value") return None def slug(dev): raw = str(dev.get("id") or dev.get("name")) return "yandex_" + "".join(c if c.isalnum() else "_" for c in raw)[:40] def kind_of(dtype): if dtype.endswith(".light"): return "light" if dtype.endswith(".sensor.climate"): return "temperature" if dtype.endswith(".sensor.motion"): return "motion" if dtype.endswith(".sensor.open"): return "open" return "switch" def discovery(comp, uid, name, dev, area): cfg = { "unique_id": uid, "name": name, "device": { "identifiers": [uid], "name": name, "manufacturer": "Yandex Smart Home", "model": (dev.get("type") or "").split(".")[-1], }, } if area: cfg["device"]["suggested_area"] = area if comp == "light": cfg.update({ "state_topic": "yandex/%s/state" % uid, "command_topic": "yandex/%s/set" % uid, "payload_on": "ON", "payload_off": "OFF", "brightness_state_topic": "yandex/%s/brightness" % uid, "brightness_command_topic": "yandex/%s/brightness_set" % uid, "brightness_scale": 100, "rgb_state_topic": "yandex/%s/rgb" % uid, "rgb_command_topic": "yandex/%s/rgb_set" % uid, "supported_color_modes": ["rgb"], }) elif comp == "switch": cfg.update({ "state_topic": "yandex/%s/state" % uid, "command_topic": "yandex/%s/set" % uid, "payload_on": "ON", "payload_off": "OFF", }) elif comp == "temperature": cfg.update({ "state_topic": "yandex/%s/temperature" % uid, "device_class": "temperature", "unit_of_measurement": "°C", }) elif comp == "motion": cfg.update({ "state_topic": "yandex/%s/motion" % uid, "payload_on": "ON", "payload_off": "OFF", "device_class": "motion", }) elif comp == "open": cfg.update({ "state_topic": "yandex/%s/open" % uid, "payload_on": "ON", "payload_off": "OFF", "device_class": "door", }) return cfg def publish_discovery(client, info): rooms = {r.get("id"): r.get("name") for r in (info.get("rooms") or [])} count = 0 for dev in info.get("devices") or []: dtype = dev.get("type") or "" if dtype.startswith(SKIP_PREFIX): continue uid = slug(dev) comp = kind_of(dtype) area = rooms.get(dev.get("room")) if dev.get("room") else None name = dev.get("name") or "Яндекс" cfg = discovery(comp, uid, name, dev, area) with _lock: _known[uid] = {"dev": dev, "kind": comp} topic = "%s/%s/%s/config" % (PREFIX, comp, uid) client.publish(topic, json.dumps(cfg, ensure_ascii=False), retain=True) count += 1 return count def publish_states(client, info): for dev in info.get("devices") or []: dtype = dev.get("type") or "" if dtype.startswith(SKIP_PREFIX): continue uid = slug(dev) kind = kind_of(dtype) on = cap_value(dev, "devices.capabilities.on_off") if kind in ("light", "switch"): client.publish("yandex/%s/state" % uid, "ON" if on else "OFF", retain=True) if kind == "light": bright = cap_value(dev, "devices.capabilities.range", "brightness") if bright is not None: client.publish("yandex/%s/brightness" % uid, int(bright), retain=True) if kind == "temperature": v = prop_value(dev, "devices.properties.float", "temperature") if v is None: v = cap_value(dev, "devices.capabilities.range", "temperature") if v is not None: client.publish("yandex/%s/temperature" % uid, v, retain=True) if kind == "motion": v = prop_value(dev, "devices.properties.event", "motion") client.publish("yandex/%s/motion" % uid, "ON" if str(v).lower() in ("detected", "true", "on") else "OFF", retain=True) if kind == "open": v = prop_value(dev, "devices.properties.event", "open") state = "ON" if str(v).lower() in ("opened", "true", "on") else "OFF" client.publish("yandex/%s/open" % uid, state, retain=True) def find_device(uid): with _lock: item = _known.get(uid) return item["dev"] if item else None def on_message(client, userdata, msg): topic = msg.topic payload = msg.payload.decode("utf-8", "replace").strip() parts = topic.split("/") if len(parts) != 3 or parts[0] != "yandex": return uid, action = parts[1], parts[2] dev = find_device(uid) if not dev: return dev_id = dev.get("id") if action == "set": value = payload.upper() == "ON" actions = [{ "type": "devices.capabilities.on_off", "state": {"instance": "on", "value": value}, }] elif action == "brightness_set": try: value = max(0, min(100, int(float(payload)))) except ValueError: return actions = [{ "type": "devices.capabilities.range", "state": {"instance": "brightness", "value": value, "relative": False}, }] elif action == "rgb_set": try: r, g, b = [max(0, min(255, int(x))) for x in payload.split(",")[:3]] except Exception: return value = (r << 16) | (g << 8) | b actions = [{ "type": "devices.capabilities.color_setting", "state": {"instance": "rgb", "value": value}, }] else: return result = api_action(dev_id, actions) print("cmd", uid, action, payload, "->", result, flush=True) def main(): global _tok _tok = token() client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id="yandex-iot-bridge") client.username_pw_set(MQTT_USER, MQTT_PASS) client.on_message = on_message client.connect(MQTT_HOST, 1883, 30) client.loop_start() client.subscribe("yandex/+/set") client.subscribe("yandex/+/brightness_set") client.subscribe("yandex/+/rgb_set") print("bridge started", flush=True) last_discovery = 0 while True: try: info = api_get("/user/info") if time.time() - last_discovery > 600: n = publish_discovery(client, info) last_discovery = time.time() print("discovery:", n, "устройств", flush=True) publish_states(client, info) except Exception as e: print("poll error:", str(e)[:120], flush=True) time.sleep(POLL) if __name__ == "__main__": main()