#!/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" PROJECTS_DIR = "/opt/work-hub/compat/projects" # направления (в перспективе — все три, сейчас ВКС) 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.pkg = load_yaml("package.yaml") self.pkg_ver = load_yaml("package_verified.yaml") self.kits = load_yaml("kits.yaml") self.extra = load_yaml("specs_extra.yaml") self.infra = load_yaml("infrastructure.yaml") self.limits = load_yaml("limitations.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") # доп. характеристики из specs_extra.yaml (проверено) for x in (self.extra.get("devices") or []): k = norm(x["device"]) self.attrs.setdefault(k, {}) for ak, av in (x.get("attributes") or {}).items(): self.attrs[k].setdefault(ak, av) if x.get("package"): self.pkg_map_extra = getattr(self, "pkg_map_extra", {}) self.pkg_map_extra[k] = x["package"] self.pkg_map = {} for x in (self.pkg_ver.get("devices") or []): self.pkg_map[norm(x["device"])] = x 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 # ── ГРУППЫ оборудования (как в Yealink Room Calculator) ── GROUPS_V2 GROUP_DEFS = [ {"id": "mic", "name": "Микрофоны", "roles": ["audio"], "skip": r"^CP50|^CP965|^CPE|^CP\d|^PA\d|^CS10-D|^CLS120"}, {"id": "speaker", "name": "Громкоговорители", "roles": ["speaker"], "extra": r"^CS10-D|^CLS120|^MSpeaker"}, {"id": "camera", "name": "Камеры", "roles": ["camera"], "skip": None}, {"id": "panel", "name": "Панели управления", "roles": ["touch", "remote"], "skip": None}, {"id": "sharing", "name": "Презентация и хабы", "roles": ["sharing_or_hub"], "skip": None}, {"id": "phone", "name": "Аудиоустройства и телефоны", "roles": ["audio"], "only": r"^CP50|^CP965|^CPE|^CP\d|^PA\d"}, {"id": "display", "name": "Дисплеи", "roles": ["display"], "skip": None}, {"id": "mount", "name": "Кронштейны", "roles": ["mount"], "skip": None}, {"id": "infra", "name": "Инфраструктура (PoE, хабы)", "roles": [], "skip": None}, ] # ── ПОЗИЦИОННЫЙ конструктор: места установки ── 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} # ── полнота данных по хосту ── data_completeness def data_completeness(self, host_key): hk = norm(host_key) srcs = {} for e in self.edges.get(hk, []): srcs[e.get("source") or "?"] = srcs.get(e.get("source") or "?", 0) + 1 total = sum(srcs.values()) supported = sum(1 for e in self.edges.get(hk, []) if e.get("supported")) if "matrix" in srcs and "accessories_list" in srcs: level, note = "full", "два официальных источника: матрица + лист аксессуаров" elif "matrix" in srcs: level, note = "partial", "только матрица — лист аксессуаров не найден" elif "accessories_list" in srcs: level, note = "sparse", ("только лист аксессуаров (%d строк) — в основной " "матрице Yealink этого хоста нет, данные могут быть " "неполными" % total) else: level, note = "none", "связей нет — данных о совместимости не найдено" return {"level": level, "note": note, "edges": total, "supported": supported, "sources": srcs} # ── группы оборудования ── def groups(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": "хост не найден"} out = [] used = set() for g in self.GROUP_DEFS: items = [] if g["id"] == "infra": for x in (self.infra.get("devices") or []): items.append({"model": x["device"], "role": "infrastructure", "max_qty": 4, "condition": x.get("why") or "", "pickup_m": None, "zoom": None, "power_w": None, "ports_vch": None, "specs": x.get("specs") or {}}) out.append({"id": g["id"], "name": g["name"], "hint": "PoE-коммутаторы и хабы для роста системы", "items": items}) continue for e in self.edges.get(hk, []): t = e["to"] k = norm(t) if k in used: continue r = self.devices.get(k, {}).get("role") if r not in g["roles"]: continue if not e.get("supported") or not e.get("usable", True): continue if g.get("skip") and re.match(g["skip"], t, re.I): continue if g.get("only") and not re.match(g["only"], t, re.I): continue a = self.attrs.get(k, {}) f = {norm(x) for x in self.feats.get(k, set())} if need_n and not need_n <= f: continue used.add(k) 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 g["id"] == "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, "role": "mount", "max_qty": 1, "condition": "лист Mounts & Bracket", "power_w": None, "pickup_m": None, "zoom": None, "ports_vch": None}) if items: out.append({"id": g["id"], "name": g["name"], "hint": "", "items": sorted(items, key=lambda x: x["model"])}) return {"host": self.devices[hk]["name"], "groups": out, "completeness": self.data_completeness(hk)} # ── проверка одной пары: хост + устройство ── def check_pair(self, host_key, accessory): hk = norm(host_key) ak = norm(accessory) host = self.devices.get(hk, {}).get("name") acc_name = self.devices.get(ak, {}).get("name") or accessory if not host: return {"error": "хост не найден"} found = None for e in self.edges.get(hk, []): if norm(e["to"]) == ak: found = e break if not found: return {"host": host, "device": acc_name, "known": False, "supported": False, "verdict": "нет в матрице для этого хоста", "note": "устройство не описано как аксессуар этого хоста"} supported = bool(found.get("supported")) usable = found.get("usable", True) if not usable: verdict = "исключено: источники расходятся — требуется проверка у вендора" elif supported: q = found.get("max_qty") verdict = "совместимо" + (" (до %s шт)" % q if q else "") else: verdict = "несовместимо" cond = re.sub(r"^[\u221a\u2713\u2714\u00d7\u2717\u2718\u2022\s]+", "", (found.get("condition") or "")).strip() # cond_clean return {"host": host, "device": acc_name, "known": True, "supported": supported, "usable": usable, "max_qty": found.get("max_qty"), "condition": cond, "source": found.get("source") or "матрица", "verdict": verdict} # ── матрица: хосты × аксессуары + порты ── def matrix(self): hosts = [h for h in self.hosts()] accs = {} for hk in [h["key"] for h in hosts]: for e in self.edges.get(hk, []): if not e.get("supported") or not e.get("usable", True): continue accs[norm(e["to"])] = e["to"] acc_list = sorted(accs.values()) rows = [] for h in hosts: hk = h["key"] cells = {} for e in self.edges.get(hk, []): if not e.get("supported") or not e.get("usable", True): continue k = norm(e["to"]) q = e.get("max_qty") cells[k] = q if q else 1 ins, outs, src = self.device_ports(h["name"]) rows.append({"host": h["name"], "cells": cells, "ports": {"in": ins, "out": outs, "source": src}}) return {"hosts": [r["host"] for r in rows], "rows": rows, "accessories": acc_list} # ── порты всех устройств ── def ports_table(self): out = [] for k, v in sorted(self.devices.items(), key=lambda x: x[1]["name"]): name = v["name"] ins, outs, src = self.device_ports(name) pkg = [] for x in (self.pkg.get("devices") or []): if norm(x["device"]) == k: pkg = x.get("items") or [] break lim = [] for x in (self.limits.get("devices") or []): if norm(x["device"]) == k: lim = x.get("limits") or [] break out.append({"device": name, "role": v["role"], "in": ins, "out": outs, "source": src, "package": pkg, "limits": lim}) return out # ── предложения: как закрыть проблему ── def suggest_fixes(self, host_key, items, issues, missing_power): hk = norm(host_key) ha = self.attrs.get(hk, {}) vch_ports = ha.get("ports.vch") qtys = {} for row in items: qtys[row[0]] = qtys.get(row[0], 0) + int(row[1]) def compat(role): out = [] for e in self.edges.get(hk, []): if not e.get("supported") or not e.get("usable", True): continue if self.devices.get(norm(e["to"]), {}).get("role") != role: continue a = self.attrs.get(norm(e["to"]), {}) out.append({"model": e["to"], "max_qty": e.get("max_qty"), "vch": a.get("ports.vch"), "wifi": a.get("network.wifi"), "poe": a.get("network.poe"), "power_w": a.get("power.consumption_w")}) return out variants = [] need_vch = any("VCH" in i for i in issues) # инфраструктура: RCH40 E2 даёт 4 PoE-порта infra_items = [] for x in (self.infra.get("devices") or []): sp = x.get("specs") or {} infra_items.append({ "title": "Добавить %s" % x["device"], "why": "%s PoE+ портов, бюджет %s Вт (%s Вт на порт), uplink 1G" % (sp.get("poe_ports"), sp.get("poe_budget_w"), sp.get("poe_per_port_w")), "add": [[x["device"], 1]], "kind": "infra"}) variants.extend(infra_items) if need_vch: # вариант 1: добавить хаб с VCH-портами # hub_filter: только реальные VCH-хабы (VCH51/VCH51 Pro), не донглы hubs = [] for h in compat("sharing_or_hub"): if not re.match(r"^VCH", h["model"], re.I): iv = self.iface_map.get(norm(h["model"])) or {} if "VCH" not in (iv.get("in") or []) + (iv.get("out") or []): continue hubs.append(h) for h in hubs[:3]: variants.append({ "title": "Добавить %s" % h["model"], "why": "даёт %s VCH-порт(а) для цепочки" % (h["vch"] or 1), "add": [[h["model"], 1]], "kind": "hub"}) if not hubs: for h in compat("sharing_or_hub")[:2]: variants.append({ "title": "Добавить %s" % h["model"], "why": "расширяет подключение (VCH-порты не указаны в данных — проверить)", "add": [[h["model"], 1]], "kind": "hub_unknown"}) # вариант 2: беспроводные микрофоны wifi = [a for a in compat("audio") if a.get("wifi")] for a in wifi[:2]: variants.append({ "title": "Заменить проводные на %s" % a["model"], "why": "беспроводной микрофон — не занимает VCH-порт", "replace_role": "audio", "add": [[a["model"], 1]], "kind": "wireless"}) # вариант 3: уменьшить количество variants.append({ "title": "Сократить количество на VCH", "why": "у хоста %s VCH-порт(а) — распределить устройства или снизить число" % (int(vch_ports) if vch_ports else "?"), "kind": "reduce"}) if missing_power: variants.append({ "title": "Уточнить питание", "why": "нет данных о потреблении: %s — запросить у вендора" % ", ".join(missing_power[:5]), "kind": "data"}) # PoE-бюджет: если есть устройства без PoE, но с питанием no_poe = [m for m in qtys if not (self.attrs.get(norm(m), {}) or {}).get("network.poe")] if no_poe: variants.append({ "title": "Проверить питание %s" % ", ".join(no_poe[:3]), "why": "у этих устройств нет данных о PoE — возможно, нужен блок питания", "kind": "data"}) return variants # ── проверка ёмкости хоста ── 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])) suggestions = self.suggest_fixes(host_key, items, issues, sorted(set(missing_w))) return {"host": host, "vch_ports": vch_ports, "vch_users": vch_users, "suggestions": suggestions, "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": "основа системы"}) def mark_included(): """Помечает позиции, чьи кабели/крепёж уже в комплекте.""" for b in bom: k = norm(b["model"]) pk = self.pkg_map.get(k) or {} items = pk.get("items") or (getattr(self, "pkg_map_extra", {}) or {}).get(k) or [] if items: b["included"] = items 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"])) mark_included() # что входит в комплект (не покупать отдельно) included, kits = [], [] for b in bom: if b["model"].startswith("встроенный") or b["model"].startswith("внешний"): continue k = norm(b["model"]) p = self.pkg_map.get(k) if p: included.append({"device": b["model"], "items": p.get("items") or [], "kits": p.get("optional_kits") or []}) for kk in (self.kits.get("kits") or []): if norm(kk.get("base")) == hk: kits.append(kk) # схема: узлы с портами и связи 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, "included": included, "kits": kits, "scheme": {"nodes": nodes, "links": links}} D = Data() def _ensure_dir(): os.makedirs(PROJECTS_DIR, exist_ok=True) def list_projects(): _ensure_dir() out = [] for f in sorted(os.listdir(PROJECTS_DIR), reverse=True): if not f.endswith(".json"): continue try: d = json.load(open(os.path.join(PROJECTS_DIR, f), encoding="utf-8")) except Exception: continue out.append({"id": d.get("id"), "name": d.get("name"), "host": d.get("host"), "items": len(d.get("items") or []), "updated": d.get("updated")}) return {"projects": out[:50]} def load_project(pid): if not pid or not re.match(r"^[\w-]{1,32}$", pid): return {"error": "bad id"} p = os.path.join(PROJECTS_DIR, pid + ".json") if not os.path.exists(p): return {"error": "not found"} return json.load(open(p, encoding="utf-8")) def save_project(payload): _ensure_dir() pid = payload.get("id") or ("p" + str(int(__import__("time").time()))) if not re.match(r"^[\w-]{1,32}$", str(pid)): return {"error": "bad id"} payload["id"] = pid payload["updated"] = __import__("time").strftime("%Y-%m-%dT%H:%M:%S") if not payload.get("created"): payload["created"] = payload["updated"] with open(os.path.join(PROJECTS_DIR, str(pid) + ".json"), "w", encoding="utf-8") as f: json.dump(payload, f, ensure_ascii=False, indent=2) return {"ok": True, "id": pid} 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/groups": return self._out(D.groups(q.get("host", [""])[0], [x for x in q.get("need", []) if x])) 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/projects": return self._out(list_projects()) if p == "/api/project": pid = q.get("id", [""])[0] return self._out(load_project(pid)) if p == "/api/save": try: length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length).decode() or "{}") except Exception as e: return self._out({"error": "bad json: %s" % e}, 400) return self._out(save_project(payload)) if p == "/api/gaps": return self._out({"missing": D.extra.get("missing") or []}) if p == "/api/kits": return self._out(D.kits) if p == "/api/check": return self._out(D.check_pair(q.get("host", [""])[0], q.get("device", [""])[0])) if p == "/api/matrix": return self._out(D.matrix()) if p == "/api/ports": return self._out(D.ports_table()) 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) def do_POST(self): u = urllib.parse.urlparse(self.path) if u.path == "/api/save": try: n = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(n).decode() or "{}") except Exception as e: return self._out({"error": "bad json: %s" % e}, 400) return self._out(save_project(payload)) 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()