290 lines
13 KiB
Python
290 lines
13 KiB
Python
#!/usr/bin/env python3
|
||
"""Комбайн: веб-интерфейс (v2) — направления, сценарии, чипы, Link View.
|
||
|
||
Модель схемы повторяет Yealink Room Designer:
|
||
устройство = блок с ВХОДАМИ слева и ВЫХОДАМИ справа
|
||
связи — только между однотипными портами (HDMI→HDMI, USB→USB, VCH→VCH, LAN→LAN)
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import socketserver
|
||
import urllib.parse
|
||
from http.server import BaseHTTPRequestHandler
|
||
|
||
BASE = "/opt/work-hub/compat"
|
||
|
||
# направления (в перспективе — все три, сейчас ВКС)
|
||
DIRECTIONS = [
|
||
{"id": "vcs", "name": "ВКС", "note": "видеоконференции: комнаты, бары, кодеки",
|
||
"ready": True},
|
||
{"id": "telephony", "name": "Телефония", "note": "SIP-аппараты, гарнитуры, линии",
|
||
"ready": False},
|
||
{"id": "webrtc", "name": "WebRTC", "note": "браузерные решения, шлюзы", "ready": False},
|
||
]
|
||
|
||
|
||
def norm(s):
|
||
return re.sub(r"[^a-z0-9]", "", str(s).lower())
|
||
|
||
|
||
def load_yaml(name):
|
||
import yaml
|
||
p = os.path.join(BASE, name)
|
||
if not os.path.exists(p):
|
||
return {}
|
||
try:
|
||
return yaml.safe_load(open(p, encoding="utf-8")) or {}
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
class Data:
|
||
def __init__(self):
|
||
self.cat = load_yaml("catalog.yaml")
|
||
self.graph = load_yaml("graph.yaml")
|
||
self.values = load_yaml("values.yaml")
|
||
self.features = load_yaml("features.yaml")
|
||
self.protocols = load_yaml("protocols.yaml")
|
||
self.mounts = load_yaml("mounts.yaml")
|
||
self.dante = load_yaml("dante.yaml")
|
||
self.devices = {norm(d["name"]): {"name": d["name"], "role": d.get("role", "unknown")}
|
||
for d in self.cat.get("devices") or []}
|
||
self.edges = {}
|
||
for e in self.graph.get("edges") or []:
|
||
self.edges.setdefault(norm(e.get("from")), []).append(e)
|
||
self.attrs = {norm(x.get("device")): x.get("attributes") or {}
|
||
for x in self.values.get("devices") or []}
|
||
self.feats = {}
|
||
for x in self.features.get("devices") or []:
|
||
self.feats.setdefault(norm(x.get("device")), set()).update(x.get("features") or [])
|
||
for x in self.protocols.get("devices") or []:
|
||
f = x.get("features") or {}
|
||
self.feats.setdefault(norm(x.get("device")), set()).update(
|
||
f.keys() if isinstance(f, dict) else f)
|
||
for x in self.dante.get("dante_devices") or []:
|
||
self.feats.setdefault(norm(x.get("device")), set()).add("Dante")
|
||
self.mounts_map = {}
|
||
for e in self.mounts.get("edges") or []:
|
||
self.mounts_map.setdefault(norm(e["host"]), []).append(e["mount"])
|
||
|
||
# ── хосты ──
|
||
def hosts(self):
|
||
out = []
|
||
for k, v in self.devices.items():
|
||
if v["role"] != "codec" or not self.edges.get(k):
|
||
continue
|
||
acc = [e for e in self.edges[k] if e.get("supported")]
|
||
out.append({"key": k, "name": v["name"], "accessories": len(acc)})
|
||
return sorted(out, key=lambda x: x["name"])
|
||
|
||
# ── все доступные требования ──
|
||
def requirements(self):
|
||
groups = {
|
||
"Аудио": ["AEC", "ANC", "Dante", "AES67", "Wireless Microphone",
|
||
"Speaker Tracking", "Audio Fence"],
|
||
"Видео": ["Auto Framing", "Presenter Tracking", "4K", "IntelliFrame"],
|
||
"ВКС": ["Teams", "Zoom", "H.323", "SIP"],
|
||
"Сеть": ["PoE", "Wi-Fi", "Bluetooth", "802.1X", "VLAN", "SRTP"],
|
||
"Презентация": ["AirPlay", "Miracast", "USB-C"],
|
||
}
|
||
return [{"group": g, "items": items} for g, items in groups.items()]
|
||
|
||
def device_row(self, key):
|
||
d = self.devices[key]
|
||
return {"key": key, "name": d["name"], "role": d["role"],
|
||
"features": sorted(self.feats.get(key, [])),
|
||
"attributes": self.attrs.get(key, {}),
|
||
"accessories": [{"model": e["to"], "supported": e.get("supported"),
|
||
"max_qty": e.get("max_qty"),
|
||
"condition": e.get("condition"),
|
||
"usable": e.get("usable", True)}
|
||
for e in self.edges.get(key, [])],
|
||
"mounts": self.mounts_map.get(key, [])}
|
||
|
||
# ── порты по роли (если в даташите не указаны) ──
|
||
PORTS_BY_ROLE = {
|
||
"display": {"in": ["HDMI"], "out": []},
|
||
"camera": {"in": ["LAN"], "out": ["USB", "HDMI"]},
|
||
"audio": {"in": ["VCH"], "out": ["VCH"]},
|
||
"speaker": {"in": ["VCH"], "out": []},
|
||
"touch": {"in": ["LAN"], "out": ["USB"]},
|
||
"sharing_or_hub": {"in": ["USB"], "out": ["HDMI"]},
|
||
"mount": {"in": [], "out": []},
|
||
"codec": {"in": ["LAN"], "out": ["HDMI", "USB", "VCH"]},
|
||
}
|
||
|
||
# ── порты устройства для схемы ──
|
||
def ports(self, name):
|
||
a = self.attrs.get(norm(name), {})
|
||
ins, outs = [], []
|
||
out_map = (("ports.hdmi_out", "HDMI"), ("ports.usb", "USB"), ("ports.vch", "VCH"))
|
||
in_map = (("ports.hdmi_in", "HDMI"),)
|
||
for aid, label in out_map:
|
||
n = a.get(aid)
|
||
if n:
|
||
outs += [label] * int(n)
|
||
for aid, label in in_map:
|
||
n = a.get(aid)
|
||
if n:
|
||
ins += [label] * int(n)
|
||
role = self.devices.get(norm(name), {}).get("role", "unknown")
|
||
dflt = self.PORTS_BY_ROLE.get(role, {"in": ["LAN"], "out": ["—"]})
|
||
if not ins:
|
||
ins = list(dflt["in"])
|
||
if not outs:
|
||
outs = list(dflt["out"]) or ["—"]
|
||
return ins, outs
|
||
|
||
# ── подбор ──
|
||
def bom(self, host_key, seats=8, need=None, add=None):
|
||
need = need or []
|
||
need_n = {norm(x) for x in need}
|
||
add = add or []
|
||
hk = norm(host_key)
|
||
if hk not in self.devices:
|
||
return {"error": "хост не найден"}
|
||
host = self.devices[hk]["name"]
|
||
need_m = 3 if seats <= 6 else 6 if seats <= 12 else 8 if seats <= 16 else 10
|
||
bom, warn, cross = [], [], []
|
||
|
||
def by_role(role):
|
||
return [e for e in self.edges.get(hk, [])
|
||
if e.get("supported") and e.get("usable", True)
|
||
and self.devices.get(norm(e["to"]), {}).get("role") == role]
|
||
|
||
bom.append({"role": "Хост", "model": host, "qty": 1, "why": "основа системы"})
|
||
ha = {norm(f) for f in self.feats.get(hk, [])}
|
||
for n in need:
|
||
if norm(n) not in ha:
|
||
warn.append("хост не имеет функции «%s»" % n)
|
||
|
||
built = self.attrs.get(hk, {}).get("audio.pickup_m")
|
||
if built and built >= need_m:
|
||
bom.append({"role": "Микрофон", "model": "встроенный " + host, "qty": 1,
|
||
"why": "захват %s м ≥ %s м" % (built, need_m)})
|
||
else:
|
||
cands = sorted(((self.attrs.get(norm(e["to"]), {}).get("audio.pickup_m") or 0, e)
|
||
for e in by_role("audio")), key=lambda x: -x[0])
|
||
if cands:
|
||
p, e = cands[0]
|
||
q = max(1, -(-need_m // max(int(p), 1))) if p else 1
|
||
bom.append({"role": "Микрофон", "model": e["to"], "qty": q,
|
||
"why": "нужно %s м, у %s %s м (до %s шт)"
|
||
% (need_m, e["to"], p or "—", e.get("max_qty") or "—")})
|
||
|
||
cams = by_role("camera")
|
||
if cams:
|
||
def sc(e):
|
||
a = self.attrs.get(norm(e["to"]), {})
|
||
z = (a.get("camera.zoom_optical") or 0) + (a.get("camera.zoom_hybrid") or 0)
|
||
return z - (100 if "content camera" in (e.get("condition") or "").lower() else 0)
|
||
cams.sort(key=sc, reverse=True)
|
||
bom.append({"role": "Камера", "model": cams[0]["to"], "qty": 1,
|
||
"why": "совместима, до %s шт" % (cams[0].get("max_qty") or "—")})
|
||
for role, label in (("touch", "Панель"), ("sharing_or_hub", "Презентация")):
|
||
it = by_role(role)
|
||
if it:
|
||
bom.append({"role": label, "model": it[0]["to"], "qty": 1,
|
||
"why": (it[0].get("condition") or "совместимо")[:70]})
|
||
disps = by_role("display")
|
||
bom.append({"role": "Дисплей", "model": disps[0]["to"] if disps else "внешний ТВ",
|
||
"qty": 1, "why": "совместим" if disps else "у Yealink нет дисплея"})
|
||
mnts = self.mounts_map.get(hk) or [e["to"] for e in by_role("mount")]
|
||
if mnts:
|
||
bom.append({"role": "Кронштейн", "model": mnts[0], "qty": 1,
|
||
"why": "вариантов: %d" % len(mnts)})
|
||
for n in add:
|
||
bom.append({"role": "Якорь", "model": n, "qty": 1, "why": "задано вручную"})
|
||
if any(norm(x) == "dante" for x in need):
|
||
bom.append({"role": "Dante", "model": "CM50+CS10-D+AP08", "qty": 1,
|
||
"why": "нативный Dante-комплект"})
|
||
|
||
chosen = {norm(b["model"]) for b in bom}
|
||
for e in self.edges.get(hk, []):
|
||
if norm(e["to"]) not in chosen:
|
||
continue
|
||
c = e.get("condition") or ""
|
||
for known, info in self.devices.items():
|
||
if len(known) > 3 and known in norm(c) and known not in chosen:
|
||
cross.append("%s требует %s" % (e["to"], info["name"]))
|
||
|
||
# схема: узлы с портами и связи
|
||
nodes = []
|
||
for b in bom:
|
||
if b["role"] in ("Кронштейн",) or b["model"].startswith("встроенный"):
|
||
continue
|
||
ins, outs = self.ports(b["model"])
|
||
nodes.append({"model": b["model"], "role": b["role"], "qty": b["qty"],
|
||
"ins": ins[:6], "outs": outs[:6],
|
||
"central": b["role"] == "Хост"})
|
||
links = []
|
||
center = next((n for n in nodes if n["central"]), None)
|
||
if center:
|
||
for n in nodes:
|
||
if n["central"]:
|
||
continue
|
||
links.append({"from": center["model"], "to": n["model"],
|
||
"type": (n["outs"] or ["-"])[0]})
|
||
return {"host": host, "seats": seats, "need_pickup": need_m,
|
||
"bom": bom, "warnings": warn, "cross": cross,
|
||
"scheme": {"nodes": nodes, "links": links}}
|
||
|
||
|
||
D = Data()
|
||
|
||
|
||
class H(BaseHTTPRequestHandler):
|
||
def _out(self, obj, code=200, ctype="application/json; charset=utf-8"):
|
||
body = obj if isinstance(obj, bytes) else json.dumps(obj, ensure_ascii=False).encode()
|
||
self.send_response(code)
|
||
self.send_header("Content-Type", ctype)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
|
||
def log_message(self, *a):
|
||
pass
|
||
|
||
def do_GET(self):
|
||
u = urllib.parse.urlparse(self.path)
|
||
q = urllib.parse.parse_qs(u.query)
|
||
p = u.path
|
||
if p == "/":
|
||
f = os.path.join(os.path.dirname(__file__), "index.html")
|
||
return self._out(open(f, encoding="utf-8").read().encode(), ctype="text/html; charset=utf-8")
|
||
if p == "/api/stats":
|
||
return self._out({"devices": len(D.devices),
|
||
"edges": sum(len(v) for v in D.edges.values()),
|
||
"hosts": len(D.hosts()),
|
||
"mounts": len(D.mounts.get("mounts") or []),
|
||
"attrs": len(D.attrs)})
|
||
if p == "/api/directions":
|
||
return self._out(DIRECTIONS)
|
||
if p == "/api/hosts":
|
||
return self._out(D.hosts())
|
||
if p == "/api/requirements":
|
||
return self._out(D.requirements())
|
||
if p == "/api/device":
|
||
k = norm(q.get("key", [""])[0])
|
||
if k not in D.devices:
|
||
return self._out({"error": "not found"}, 404)
|
||
return self._out(D.device_row(k))
|
||
if p == "/api/bom":
|
||
need = [x for x in q.get("need", []) if x]
|
||
add = [x for x in q.get("add", []) if x]
|
||
return self._out(D.bom(q.get("host", [""])[0],
|
||
int(q.get("seats", ["8"])[0]), need, add))
|
||
return self._out({"error": "not found"}, 404)
|
||
|
||
|
||
class S(socketserver.ThreadingTCPServer):
|
||
allow_reuse_address = True
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import sys
|
||
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8095
|
||
print("combine v2 on :%d" % port, flush=True)
|
||
S(("0.0.0.0", port), H).serve_forever()
|