"""Сторож mesh: следит за узлами, уведомляет и чинит «Родителей» при появлении.""" import json import os import subprocess import sys import time import urllib.request sys.path.insert(0, "/opt/hub-core") from keenetic_client import Keenetic # noqa: E402 STATE = "/var/lib/hub-mesh/state.json" NOTIFY = "http://127.0.0.1:9120/notify" PASSWORD = "73145146" NODES = { "192.168.1.3": "Кабинет", "192.168.1.63": "Родители", } THRESHOLD = 2 def ping(ip): r = subprocess.run(["ping", "-c", "2", "-W", "2", ip], capture_output=True, text=True, timeout=15) return r.returncode == 0 def notify(title, message): body = json.dumps({"title": title, "message": message}).encode() req = urllib.request.Request(NOTIFY, data=body, method="POST", headers={"Content-Type": "application/json"}) try: urllib.request.urlopen(req, timeout=15).read() except Exception as e: print("notify error:", e, flush=True) def load(): try: return json.load(open(STATE, encoding="utf-8")) except Exception: return {} def save(state): os.makedirs(os.path.dirname(STATE), exist_ok=True) json.dump(state, open(STATE, "w", encoding="utf-8")) def fix_node(ip): """Приводит узел к нашим настройкам (каналы, ширина, автообновление).""" k = Keenetic(f"http://{ip}", "admin", PASSWORD) ok, _ = k.auth() if not ok: return "нет доступа" acts = [] ch = k.rci("/rci/show/interface/WifiMaster0") if ch.get("channel") not in (1, 6, 11): k._req("POST", "/rci/", [{"interface": {"WifiMaster0": {"channel": 11}}}]) acts.append("канал 2,4 → 11") if str(ch.get("bandwidth")) != "20": k._req("POST", "/rci/", [{"interface": {"WifiMaster0": {"channel": {"width": 20}}}}]) acts.append("ширина 2,4 → 20") st, hd, raw = k._req("GET", "/rci/show/running-config") if "auto-update no disable" in raw.decode("utf-8", "replace"): k._req("POST", "/rci/", [{"components": {"auto-update": {"disable": {}}}}]) acts.append("автообновление выкл") if acts: k._req("POST", "/rci/", [{"system": {"configuration": {"save": {}}}}]) return ", ".join(acts) or "уже настроен" def main(): state = load() now = time.time() for ip, name in NODES.items(): st = state.setdefault(ip, {"down": 0, "notified": False, "fixed": False}) alive = ping(ip) if alive: if st["notified"]: notify(f"Mesh: {name} снова в сети", f"Узел {ip} отвечает. Падение длилось около " f"{int((now - st.get('down_since', now)) / 60)} мин.") st["notified"] = False st["down"] = 0 if not st.get("fixed"): result = fix_node(ip) if result != "нет доступа": st["fixed"] = True print(f"{ip}: {result}", flush=True) if result != "уже настроен": notify(f"Mesh: {name} настроен", f"Применил настройки: {result}") else: st["down"] = st.get("down", 0) + 1 if st["down"] == THRESHOLD and not st["notified"]: st["down_since"] = now st["notified"] = True notify(f"Mesh: {name} не отвечает", f"Узел {ip} недоступен {THRESHOLD} проверки подряд. " f"Проверьте питание и расстояние до главного роутера.") state[ip] = st save(state) print(json.dumps(state, ensure_ascii=False), flush=True) if __name__ == "__main__": main()