"""Добавляет ping-сенсоры HA для всех не-контейнерных устройств.""" import json import urllib.error import urllib.request TOK = open("/root/.ha-token", encoding="utf-8").read().strip() BASE = "http://127.0.0.1:8123" HDR = {"Authorization": "Bearer " + TOK, "Content-Type": "application/json"} def call(path, method="GET", body=None): data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR) try: with urllib.request.urlopen(req, timeout=30) as r: raw = r.read() return (json.loads(raw) if raw else {}), None except urllib.error.HTTPError as e: return None, f"HTTP {e.code}" except Exception as e: return None, str(e)[:100] # уже добавленные ping-хосты entries, _ = call("/api/config/config_entries/entry") have = {e.get("title") for e in (entries or []) if e.get("domain") == "ping"} # инвентарь with urllib.request.urlopen("http://192.168.1.10:9120/data/devices", timeout=20) as r: d = json.loads(r.read() or b"{}") items = (d.get("items") or []) devs = ((items[0].get("payload") if items else {}) or {}).get("devices") or [] # цели: все адреса не-контейнеров targets = [] for x in devs: if (x.get("type") or "") == "контейнер": continue ip = x.get("ip") or "" if not ip or ip in have: continue targets.append(ip) print(" новых адресов:", len(targets)) created = 0 for ip in targets[:40]: fl, e1 = call("/api/config/config_entries/flow", "POST", {"handler": "ping"}) if e1 or not fl: print(f" {ip}: {e1}") continue res, e2 = call(f"/api/config/config_entries/flow/{fl['flow_id']}", "POST", {"host": ip}) if e2: print(f" {ip}: {e2}") continue created += 1 print(f" создано: {created}")