Files
buryan-infra/ops/work/web/app.py
T

615 lines
29 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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"
# направления (в перспективе — все три, сейчас ВКС)
VENDORS = [
{"id": "yealink", "name": "Yealink", "ready": True,
"note": "ВКС, PRO AV, телефония, Dante"},
{"id": "poly", "name": "Poly", "ready": False, "note": "скоро"},
{"id": "logitech", "name": "Logitech", "ready": False, "note": "скоро"},
{"id": "cisco", "name": "Cisco", "ready": False, "note": "скоро"},
{"id": "other", "name": "Другие", "ready": False, "note": "по запросу"},
]
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.iface = load_yaml("interfaces_verified.yaml")
self.iface_auto = load_yaml("interfaces.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.iface_map = {}
self.iface_auto_map = {}
for x in (self.iface.get("devices") or []):
self.iface_map[norm(x["device"])] = x
for x in (self.iface_auto.get("devices") or []):
self.iface_auto_map[norm(x["device"])] = x
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):
iv = self.iface_map.get(norm(name))
if iv: # проверено по даташиту
return (list(iv.get("in") or []) or ["—"],
list(iv.get("out") or []) or ["—"])
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
# ── ПОЗИЦИОННЫЙ конструктор: места установки ──
POSITIONS = [
{"id": "rack", "name": "Стойка / шкаф",
"hint": "кодек, DSP, коммутатор",
"roles": ["sharing_or_hub", "power"]},
{"id": "table", "name": "Стол",
"hint": "настольные микрофоны, панели, докстанции",
"roles": ["audio", "touch", "remote"]},
{"id": "ceiling", "name": "Потолок",
"hint": "потолочные микрофоны и громкоговорители",
"roles": ["audio", "speaker", "sensor"]},
{"id": "wall", "name": "Стена / экран",
"hint": "камеры, дисплеи",
"roles": ["camera", "display"]},
{"id": "perimeter", "name": "Периметр",
"hint": "кронштейны и крепления",
"roles": ["mount", "headset"]},
]
# позиция по имени устройства (важнее роли: VCM38 — потолочный, хотя роль audio)
POSITION_RULES = [
(r"^VCM|^CM50|^CS10-D|^CLS120|^MSpeaker|^CS10\b", "ceiling"),
(r"^CM20|^CS10|^CP50|^CPE|^CP965|^CP\d|^CTP|^MTouch|^VCR|^MB-Remote|^PA\d", "table"),
(r"^UVC|^MB-CAM|^MB-12X|^SmartVision|MeetingDisplay|^ETV|^VCC", "wall"),
(r"^MCore|^VCH|^WPP|^AP0|^AVBridge|^AVHub|^BYOD|^YPS|^PVB|^PVT|MeetingEye|^A\d|^MeetingBoard|^MB-FS|^Roomcast", "rack"),
(r"[Mm]ount|Bracket|Stand|^MB-Tray|^MB-Wall|^MD-", "perimeter"),
]
def pos_of(self, name):
for pat, pos in self.POSITION_RULES:
if re.match(pat, str(name)):
return pos
return None
def positions(self, host_key, need=None):
"""Позиции комнаты: в каждой только совместимые с хостом устройства."""
need_n = {norm(x) for x in (need or [])}
hk = norm(host_key)
if hk not in self.devices:
return {"error": "хост не найден"}
host_role = self.devices[hk]["role"]
# у бара камера обычно встроенная — позицию камеры скрываем, если нет совместимых
out = []
for pos in self.POSITIONS:
items = []
for e in self.edges.get(hk, []):
t = e["to"]
r = self.devices.get(norm(t), {}).get("role")
if r not in pos["roles"]:
continue
# уточнение по позиции устройства
real_pos = self.pos_of(t)
if real_pos and real_pos != pos["id"]:
continue
if not e.get("supported") or not e.get("usable", True):
continue
a = self.attrs.get(norm(t), {})
f = {norm(x) for x in self.feats.get(norm(t), set())}
if need_n and not need_n <= f:
continue
items.append({
"model": t, "role": r,
"max_qty": e.get("max_qty"),
"condition": (e.get("condition") or "").strip()[:160],
"power_w": a.get("power.consumption_w"),
"pickup_m": a.get("audio.pickup_m"),
"zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid"),
"ports_vch": a.get("ports.vch"),
})
if pos["id"] == "perimeter":
for m in self.mounts_map.get(hk, []):
items.append({"model": m, "role": "mount", "max_qty": 1,
"condition": "лист Mounts & Bracket",
"power_w": None, "pickup_m": None, "zoom": None,
"ports_vch": None})
uniq = {}
for i in items:
uniq.setdefault(i["model"], i)
items = sorted(uniq.values(), key=lambda x: x["model"])
out.append({"id": pos["id"], "name": pos["name"], "hint": pos["hint"],
"items": items})
return {"host": self.devices[hk]["name"], "host_role": host_role,
"positions": out}
# какие разъёмы соединяются между собой
LINKABLE = {
("HDMI", "HDMI"): "видео",
("USB", "USB"): "данные",
("USB-C", "USB-C"): "данные + видео",
("USB", "USB-C"): "данные (через переходник)",
("VCH", "VCH"): "аудио + питание",
("LAN", "LAN"): "сеть / PoE",
("3.5mm", "3.5mm"): "аналоговый звук",
("DP", "DP"): "видео",
}
# запреты из официальных даташитов
FORBIDDEN = [
{"device": "UVC86", "port": "HDMI", "host_contains": "mvc",
"reason": "HDMI-выход UVC86 совместим с VCS, но НЕ с MVC (даташит)"},
]
def device_ports(self, name):
"""Порты: проверенные -> извлечённые -> по роли. Возвращает (in, out, source)."""
k = norm(name)
if k in self.iface_map:
v = self.iface_map[k]
return (v.get("in") or ["—"], v.get("out") or ["—"], "verified")
if k in self.iface_auto_map:
v = self.iface_auto_map[k]
ins = [p for p in (v.get("in") or []) if p]
outs = [p for p in (v.get("out") or []) if p]
if ins or outs:
return (ins or ["—"], outs or ["—"], "auto")
ins, outs = self.ports(name)
return (ins, outs, "role")
def link_plan(self, host_key, items):
"""План связей: каждый аксессуар -> хост, по совместимости разъёмов."""
hk = norm(host_key)
host = self.devices.get(hk, {}).get("name", host_key)
h_in, h_out, h_src = self.device_ports(host)
links = []
for row in items:
model = row[0] if isinstance(row, (list, tuple)) else row
acc_in, acc_out, src = self.device_ports(model)
link = {"device": model, "host": host, "ok": False,
"from_port": None, "to_port": None, "type": None,
"source": src, "reason": None}
# ищем пару: выход аксессуара -> вход хоста (и наоборот)
pairs = []
for a in acc_out:
for b in h_in:
if (a, b) in self.LINKABLE:
pairs.append((a, b, self.LINKABLE[(a, b)]))
elif (b, a) in self.LINKABLE:
pairs.append((a, b, self.LINKABLE[(b, a)]))
for a in h_out:
for b in acc_in:
if (a, b) in self.LINKABLE:
pairs.append((a, b, self.LINKABLE[(a, b)]))
if pairs:
p = pairs[0]
link.update({"ok": True, "from_port": p[0], "to_port": p[1],
"type": p[2]})
else:
link["reason"] = ("нет совместимого разъёма: %s in=%s out=%s / хост in=%s out=%s"
% (model, ",".join(acc_in) or "-", ",".join(acc_out) or "-",
",".join(h_in) or "-", ",".join(h_out) or "-"))
# запреты
for fb in self.FORBIDDEN:
if norm(fb["device"]) == norm(model) and \
fb["host_contains"] in norm(host) and \
(link.get("from_port") == fb["port"] or link.get("to_port") == fb["port"]):
link.update({"ok": False, "forbidden": True, "reason": fb["reason"]})
links.append(link)
return {"host": host, "host_ports": {"in": h_in, "out": h_out, "source": h_src},
"links": links}
# ── проверка ёмкости хоста ──
def capacity(self, host_key, items):
"""items: [[model, qty], ...]. Проверяет порты VCH, лимиты, питание."""
hk = norm(host_key)
if hk not in self.devices:
return {"error": "хост не найден"}
host = self.devices[hk]["name"]
ha = self.attrs.get(hk, {})
vch_ports = ha.get("ports.vch")
issues, notes = [], []
total_w, missing_w = 0.0, []
vch_users = 0
qtys = {}
for row in items:
model, qty = row[0], int(row[1])
qtys[model] = qtys.get(model, 0) + qty
# лимиты из матрицы
limits = {}
for e in self.edges.get(hk, []):
if e.get("supported"):
limits[norm(e["to"])] = (e.get("max_qty"), e["to"])
for model, q in qtys.items():
lim, name = limits.get(norm(model), (None, model))
if lim and q > lim:
issues.append("%s: %d шт при лимите %d" % (name, q, lim))
a = self.attrs.get(norm(model), {})
w = a.get("power.consumption_w")
if w:
total_w += w * q
else:
missing_w.append(model)
if a.get("audio.pickup_m") or a.get("ports.vch"):
vch_users += q
if vch_ports is not None and vch_users > 0:
notes.append("портов VCH у хоста: %s · устройств на VCH: %d"
% (int(vch_ports), vch_users))
if vch_users > vch_ports:
issues.append(
"VCH: %d устройств на %s порт(а) — требуется цепочка/расширитель; "
"ёмкость цепочки в данных отсутствует — ПРОВЕРИТЬ У ВЕНДОРА"
% (vch_users, int(vch_ports)))
notes.append("суммарное потребление: %.1f Вт (по данным)" % total_w)
if missing_w:
notes.append("нет данных о потреблении: %s" % ", ".join(sorted(set(missing_w))[:8]))
return {"host": host, "vch_ports": vch_ports, "vch_users": vch_users,
"total_power_w": round(total_w, 1),
"missing_power": sorted(set(missing_w)),
"issues": issues, "notes": notes}
# ── варианты для ручной сборки (только совместимые!) ──
FEATURE_ROLE = {
"aec": "audio", "anc": "audio", "dante": "audio", "aes67": "audio",
"autoarchframing": "camera", "autoframing": "camera",
"speakertracking": "camera", "presentertracking": "camera", "4k": "camera",
"airplay": "sharing_or_hub", "miracast": "sharing_or_hub", "usbc": "sharing_or_hub",
"poe": "network", "wifi": "network", "bluetooth": "network",
"teams": "codec", "zoom": "codec", "h323": "codec", "sip": "codec",
}
ROLE_LABELS = [
("audio", "Аудио / микрофоны"),
("camera", "Камеры"),
("touch", "Панели управления"),
("sharing_or_hub", "Презентация / хабы"),
("display", "Дисплеи"),
("speaker", "Громкоговорители"),
("mount", "Кронштейны"),
("remote", "Пульты"),
("headset", "Гарнитуры"),
]
def options(self, host_key, need=None):
"""need — требования: фильтруют позиции внутри групп по ролям.""" # VENDOR_LAYER
need_n = {norm(x) for x in (need or [])}
hk = norm(host_key)
if hk not in self.devices:
return {"error": "хост не найден"}
groups, blocked_count = [], {}
for role, label in self.ROLE_LABELS:
items = []
blocked = 0
for e in self.edges.get(hk, []):
target = e["to"]
r = self.devices.get(norm(target), {}).get("role")
if r != role:
continue
# несовместимые по матрице НЕ показываем
if not e.get("supported") or not e.get("usable", True):
blocked += 1
continue
a = self.attrs.get(norm(target), {})
acc_feats = {norm(f) for f in self.feats.get(norm(target), set())}
# требование применяется к своей роли
role_needs = {n for n in need_n
if self.FEATURE_ROLE.get(n) in (role, None)}
if role_needs and not role_needs <= acc_feats:
blocked += 1
continue
items.append({
"model": target,
"max_qty": e.get("max_qty"),
"condition": (e.get("condition") or "").strip(),
"features": sorted(self.feats.get(norm(target), []))[:8],
"pickup_m": a.get("audio.pickup_m"),
"zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid"),
})
# mount_merge: кронштейны из обоих источников
if role == "mount":
have = {i["model"] for i in items}
for m in self.mounts_map.get(hk, []):
if m in have:
continue
items.append({"model": m, "max_qty": 1,
"condition": "лист Mounts & Bracket",
"features": [], "pickup_m": None, "zoom": None})
have.add(m)
if items:
items.sort(key=lambda x: x["model"])
groups.append({"role": role, "label": label, "items": items})
if blocked:
blocked_count[role] = blocked
return {"host": self.devices[hk]["name"], "groups": groups,
"blocked": blocked_count}
# ── подбор ──
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/positions":
return self._out(D.positions(q.get("host", [""])[0],
[x for x in q.get("need", []) if x]))
if p == "/api/links":
items = [x for x in q.get("item", []) if x]
return self._out(D.link_plan(q.get("host", [""])[0], items))
if p == "/api/capacity":
items = []
for raw in q.get("item", []):
if ":" in raw:
m, n = raw.rsplit(":", 1)
try:
items.append([m, int(n)])
except ValueError:
pass
return self._out(D.capacity(q.get("host", [""])[0], items))
if p == "/api/vendors":
return self._out(VENDORS)
if p == "/api/options":
return self._out(D.options(q.get("host", [""])[0],
[x for x in q.get("need", []) if x]))
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()