"""Сторож mesh: находит узлы по MAC через контроллер, чинит настройки, уведомляет.""" 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" CONTROLLER = "http://192.168.1.1" PASSWORD = "73145146" THRESHOLD = 2 NODES = { "50:ff:20:ed:de:23": {"name": "Кабинет", "expected": "192.168.1.3"}, "d4:9c:53:25:cb:2d": {"name": "Родители", "expected": "192.168.1.63", "alt_macs": ["d4:9c:53:25:cb:2e"]}, } 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 resolve(controller, mac): hosts = controller.rci("/rci/show/ip/hotspot/host") for h in hosts if isinstance(hosts, list) else []: if str(h.get("mac", "")).lower() == mac.lower(): ip = h.get("ip") if ip and ip != "0.0.0.0": return ip, bool(h.get("active")) return None, False def fix_node(ip, expected): k = Keenetic(f"http://{ip}", "admin", PASSWORD) ok, _ = k.auth() if not ok: return "нет доступа" acts = [] if ip != expected: acts.append(f"IP {ip} (ожидался {expected})") 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 and any(a.startswith(("канал", "ширина", "авто")) for a in acts): k._req("POST", "/rci/", [{"system": {"configuration": {"save": {}}}}]) return ", ".join(acts) or "ок" def main(): state = load() now = time.time() ctrl = Keenetic(CONTROLLER, "admin", PASSWORD) ok, _ = ctrl.auth() for mac, meta in NODES.items(): st = state.setdefault(mac, {"down": 0, "notified": False, "fixed": False}) name = meta["name"] expected = meta["expected"] ip, active = (resolve(ctrl, mac) if ok else (None, False)) target = ip or expected alive = ping(target) if target else False if not alive and ip and ip != expected: alive = ping(expected) if alive: if st.get("notified"): mins = int((now - st.get("down_since", now)) / 60) notify(f"Mesh: {name} снова в сети", f"Узел {target} отвечает. Падение длилось около {mins} мин.") st["notified"] = False st["down"] = 0 result = fix_node(target, expected) if result not in ("нет доступа", "ок"): notify(f"Mesh: {name} настроен", f"Применил: {result}") st["fixed"] = True else: st["down"] = st.get("down", 0) + 1 if st["down"] == THRESHOLD and not st.get("notified"): st["down_since"] = now st["notified"] = True hint = "Проверьте питание и расстояние до главного роутера." notify(f"Mesh: {name} не отвечает", f"Узел {expected} недоступен {THRESHOLD} проверки подряд. {hint}") st["last_ip"] = target state[mac] = st save(state) print(json.dumps(state, ensure_ascii=False), flush=True) if __name__ == "__main__": main()