#!/usr/bin/env python3 """Ядро комбайна: модели данных и доменная логика. Используется всеми сервисами (catalog, engine, draw, project, docs). Никакого HTTP здесь — только данные и расчёты. """ import glob import json import os import re BASE = "/opt/work-hub/compat" PROJECTS_DIR = os.path.join(BASE, "projects") def norm(s): return re.sub(r"[^a-z0-9]", "", str(s).lower()) def load(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 Core: """Единая точка доступа к данным модели.""" POSITIONS_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"]}, # ПК/BYOD — источник: отдаёт видео в комнату, принимает USB-периферию "pc": {"in": ["USB", "USB-C"], "out": ["HDMI", "USB-C"]}, "power": {"in": ["220"], "out": ["220"]}, "charger": {"in": ["220"], "out": ["USB", "220"]}, "codec": {"in": ["LAN", "HDMI"], "out": ["HDMI", "USB", "VCH"]}, "mount": {"in": [], "out": []}, "infrastructure": {"in": ["LAN"], "out": ["LAN"]}, } ROLE_PORT_PREF = { "display": ["HDMI", "DP", "USB-C"], "camera": ["USB", "USB-C", "LAN", "HDMI"], "audio": ["VCH", "USB", "USB-C"], "speaker": ["VCH"], "touch": ["USB", "LAN", "USB-C"], "sharing_or_hub": ["USB", "USB-C", "HDMI", "VCH"], "pc": ["HDMI", "USB-C", "USB"], } PORT_RANK = {"USB": 0, "USB-C": 1, "VCH": 2, "RJ-9": 3, "3.5mm": 4, "LAN": 5, "HDMI": 6, "DP": 7} LINKABLE = { ("HDMI", "HDMI"): "видео", ("USB", "USB"): "данные", ("USB-C", "USB-C"): "данные+видео", ("USB", "USB-C"): "данные (переходник)", ("USB-C", "USB"): "данные (переходник)", ("VCH", "VCH"): "аудио+питание", ("LAN", "LAN"): "сеть/PoE", ("3.5mm", "3.5mm"): "аналоговый звук", ("DP", "DP"): "видео", ("WL", "WL"): "беспроводно", ("220", "220"): "питание 220В", ("RJ-9", "RJ-9"): "телефон", } FEATURE_ROLE = { "aec": "audio", "anc": "audio", "dante": "audio", "aes67": "audio", "autoframing": "camera", "speakertracking": "camera", "presentertracking": "camera", "4k": "camera", "airplay": "sharing_or_hub", "miracast": "sharing_or_hub", "usbc": "sharing_or_hub", "poe": "infrastructure", "teams": "codec", "zoom": "codec", "h323": "codec", "sip": "codec", } GROUP_DEFS = [ {"id": "mic", "name": "Микрофоны", "roles": ["audio"], "static_role": "audio", "skip": r"^CP50|^CP965|^CPE|^CP\d|^PA\d|^CS10-D|^CLS120"}, {"id": "speaker", "name": "Громкоговорители", "roles": ["speaker"], "static_role": "speaker", "extra": r"^CS10-D|^CLS120|^MSpeaker"}, {"id": "camera", "name": "Камеры", "roles": ["camera"], "static_role": "camera"}, {"id": "panel", "name": "Панели управления", "roles": ["touch", "remote"]}, {"id": "sharing", "name": "Презентация и хабы", "roles": ["sharing_or_hub"]}, {"id": "pc", "name": "ПК и источники (BYOD)", "roles": ["pc"], "static_role": "pc"}, {"id": "power", "name": "Питание (розетки, зарядки)", "roles": ["power", "charger"], "static_role": "power"}, {"id": "phone", "name": "Аудиоустройства и телефоны", "roles": ["audio"], "only": r"^CP50|^CP965|^CPE|^CP\d|^PA\d"}, {"id": "display", "name": "Дисплеи", "roles": ["display"], "static_role": "display"}, {"id": "mount", "name": "Кронштейны", "roles": ["mount"]}, {"id": "infra", "name": "Инфраструктура (PoE, хабы)", "roles": []}, ] def __init__(self): self._stamp = 0.0 self.cat = load("catalog.yaml") self.graph = load("graph.yaml") self.values = load("values.yaml") self.features = load("features.yaml") self.protocols = load("protocols.yaml") self.mounts = load("mounts.yaml") self.dante = load("dante.yaml") self.iface_v = load("interfaces_verified.yaml") self.iface_a = load("interfaces.yaml") self.pkg_v = load("package_verified.yaml") self.pkg_a = load("package.yaml") self.limits = load("limitations.yaml") self.infra = load("infrastructure.yaml") self.kits = load("kits.yaml") self.extra = load("specs_extra.yaml") self.overrides = load("overrides.yaml") self.i_extract = load("interfaces_extract.yaml") self.s_extract = load("specs_extract.yaml") self.p_extract = load("package_extract.yaml") self.rebuild() WATCH = ("overrides.yaml", "values.yaml", "graph.yaml", "catalog.yaml", "interfaces_verified.yaml", "infrastructure.yaml", "package_verified.yaml") def reload_if_changed(self): """Перечитывает модель, если файлы изменились (ручной ввод, LLM-данные).""" stamp = 0.0 for f in self.WATCH: p = os.path.join(BASE, f) try: stamp = max(stamp, os.path.getmtime(p)) except OSError: pass if stamp > getattr(self, "_stamp", 0): self.__init__() self._stamp = stamp return True return False def rebuild(self): 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 = {} for x in self.values.get("devices") or []: self.attrs[norm(x.get("device"))] = dict(x.get("attributes") or {}) 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) for x in (self.s_extract.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) # ручные значения — перекрывают всё self.manual = {} for x in (self.overrides.get("devices") or []): k = norm(x["device"]) self.manual[k] = dict(x.get("attributes") or {}) self.feats = {} for src in (self.features, self.protocols): for x in src.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") for k, v in getattr(self, "manual", {}).items(): self.attrs.setdefault(k, {}) self.attrs[k].update(v) self.iface_map = {norm(x["device"]): x for x in self.iface_v.get("devices") or []} self.iface_auto = {norm(x["device"]): x for x in self.iface_a.get("devices") or []} self.iface_ext = {norm(x["device"]): x for x in self.i_extract.get("devices") or [] if x.get("in") or x.get("out")} self.pkg_map = {norm(x["device"]): x for x in self.pkg_v.get("devices") or []} self.pkg_llm = {norm(x["device"]): (x.get("items") or []) for x in self.p_extract.get("devices") or []} self.mounts_map = {} for e in self.mounts.get("edges") or []: self.mounts_map.setdefault(norm(e["host"]), []).append(e["mount"]) # ── сигналы и совместимость разъёмов ── SIGNAL_OF = { "HDMI": "video", "DP": "video", "USB": "data", "USB-C": "data", "VCH": "audio", "3.5mm": "audio", "LAN": "network", "RJ-9": "telephony", "PHOENIX": "control", "OPS": "data", "WL": "беспроводно", "220": "питание 220В", } # какие соединения допустимы на уровне сигнала SIGNAL_LINK = { ("video", "video"), ("data", "data"), ("audio", "audio"), ("network", "network"), ("telephony", "telephony"), ("control", "control"), ("беспроводно", "беспроводно"), ("питание 220В", "питание 220В"), } # разъём -> разъём (физическая совместимость) PHYSICAL = { ("HDMI", "HDMI"), ("DP", "DP"), ("USB", "USB"), ("USB-C", "USB-C"), ("VCH", "VCH"), ("LAN", "LAN"), ("3.5mm", "3.5mm"), ("RJ-9", "RJ-9"), ("PHOENIX", "PHOENIX"), # допустимые переходники ("USB", "USB-C"), ("USB-C", "USB"), ("USB-C", "DP"), ("DP", "USB-C"), ("WL", "WL"), ("220", "220"), } def vendor_of(self, name): """Вендор и направление устройства (пока yealink/vcs, структура готова).""" return {"vendor": "yealink", "domain": "vcs"} def vendors(self): out = {} for k, v in self.devices.items(): meta = self.vendor_of(v["name"]) key = (meta["vendor"], meta["domain"]) out.setdefault(key, []).append(v["name"]) return [{"vendor": k[0], "domain": k[1], "devices": len(v), "examples": sorted(v)[:5]} for k, v in sorted(out.items())] def port_objects(self, name): """Порты как объекты: разъём, сигнал, направление, версия.""" ins, outs, src = self.ports(name) objs = [] for i, p in enumerate(x for x in ins if x and x != "—"): objs.append({"connector": p, "signal": self.SIGNAL_OF.get(p, "unknown"), "direction": "in", "index": i, "source": src}) for i, p in enumerate(x for x in outs if x and x != "—"): objs.append({"connector": p, "signal": self.SIGNAL_OF.get(p, "unknown"), "direction": "out", "index": i, "source": src}) return objs def signal_ok(self, a, b): """Совместимы ли два порта по физике и сигналу.""" if (a, b) not in self.PHYSICAL and (b, a) not in self.PHYSICAL: return False, "разъёмы несовместимы: %s / %s" % (a, b) sa, sb = self.SIGNAL_OF.get(a), self.SIGNAL_OF.get(b) if (sa, sb) not in self.SIGNAL_LINK: return False, "разные сигналы: %s / %s" % (sa, sb) return True, "ok" def signal_chains(self, host_key, items): """Проверка сигнальных цепочек для каждого устройства.""" plan = self.port_plan(host_key, items) rows = [] for r in plan["rows"]: if r.get("via"): # устройство подключено через промежуточное (цепочка) — # это не блокер, сигнал идёт через него rows.append({"device": r["device"], "ok": True, "reason": r.get("reason") or ("через " + r["via"]), "from_port": r.get("needs_port"), "to_port": r.get("needs_port"), "via": r["via"], "signal": self.SIGNAL_OF.get(r.get("needs_port") or "")}) continue if not r["ok"]: rows.append({"device": r["device"], "ok": False, "reason": "нет подходящего порта", "from_port": None, "to_port": None}) continue hp = r["host_port"] or "" hp = hp[4:] if hp.startswith("out:") else hp ok, why = self.signal_ok(hp, r["needs_port"] or "") rows.append({"device": r["device"], "ok": ok, "reason": why, "from_port": hp, "to_port": r["needs_port"], "signal": self.SIGNAL_OF.get(hp)}) return {"host": plan["host"], "chains": rows, "ok": sum(1 for r in rows if r["ok"]), "total": len(rows)} # ── порты ── def ports(self, name): k = norm(name) if k in self.iface_map: v = self.iface_map[k] return list(v.get("in") or ["—"]), list(v.get("out") or ["—"]), "verified" if k in self.iface_ext: v = self.iface_ext[k] return list(v.get("in") or ["—"]), list(v.get("out") or ["—"]), "datasheet-llm" if k in self.iface_auto: v = self.iface_auto[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" role = self.devices.get(k, {}).get("role", "unknown") d = self.POSITIONS_ROLE.get(role, {"in": ["LAN"], "out": ["—"]}) return list(d["in"]), list(d["out"]) or ["—"], "role" # ── прослеживаемость данных (как lineage в data-платформах) ── def lineage(self, name): """По каждому атрибуту: значение, источник, файл, свежесть.""" import os import time k = norm(name) out = [] sources = [ ("manual", "overrides.yaml", "ручной ввод"), ("verified", "interfaces_verified.yaml", "выверено по даташиту"), ("values", "values.yaml", "извлечено из даташита"), ("extra", "specs_extra.yaml", "доп. даташит"), ("llm", "specs_extract.yaml", "извлечено LLM"), ] for kind, fname, label in sources: p = os.path.join(BASE, fname) try: age_h = round((time.time() - os.path.getmtime(p)) / 3600, 1) except OSError: continue out.append({"source": kind, "file": fname, "label": label, "file_age_hours": age_h}) attrs = self.attrs.get(k, {}) rows = [] for attr, val in sorted(attrs.items()): src = "values" if (getattr(self, "manual", {}) or {}).get(k, {}).get(attr) is not None: src = "manual" elif (getattr(self, "iface_map", {}) or {}).get(k) and attr.startswith(("ports.", "network.")): src = "verified" rows.append({"attr": attr, "value": val, "source": src, "verified": src in ("manual", "verified")}) verified_count = sum(1 for r in rows if r["verified"]) return {"device": self.devices.get(k, {}).get("name") or name, "attributes": rows, "total": len(rows), "verified": verified_count, "trust_pct": round(100.0 * verified_count / max(len(rows), 1), 1), "files": out, "package": self.package(name), "completeness": self.completeness(k)} # ── единый список проблем (clash detection) ── def issues(self, host_key, items, infra=None, hours=None): hk = norm(host_key) host = self.devices.get(hk, {}).get("name") or host_key out = [] cap = self.capacity(hk, items, infra or []) for i in cap["issues"]: out.append({"level": "blocker", "kind": "capacity", "text": i}) if cap["missing_power"]: out.append({"level": "warning", "kind": "data", "text": "нет данных о питании: " + ", ".join(cap["missing_power"][:6])}) sig = self.signal_chains(hk, items) for r in sig["chains"]: if not r["ok"]: out.append({"level": "blocker", "kind": "signal", "text": "%s: %s" % (r["device"], r["reason"])}) plan = self.port_plan(hk, items) if plan["unresolved"]: out.append({"level": "blocker", "kind": "port", "text": "нет порта для: " + ", ".join(plan["unresolved"])}) comp = self.completeness(hk) if comp["level"] != "full": out.append({"level": "warning", "kind": "data", "text": "неполные данные: " + comp["note"]}) for row in items: pk = self.package(row[0]) if not pk["items"]: out.append({"level": "info", "kind": "package", "text": "%s: комплектация неизвестна" % row[0]}) try: for p in self.poe_check(items): out.append({"level": "warning" if not p.get("ok") else "info", "kind": "poe", "text": p["text"]}) except Exception: pass try: for b in self.battery_check(items, hours or 8.0): lvl = "warning" if not b.get("ok") else "info" out.append({"level": lvl, "kind": "battery", "text": b["text"]}) except Exception: pass blockers = sum(1 for i in out if i["level"] == "blocker") warnings = sum(1 for i in out if i["level"] == "warning") return {"host": host, "issues": out, "blockers": blockers, "warnings": warnings, "ready": blockers == 0, "by_kind": {k: sum(1 for i in out if i["kind"] == k) for k in {i["kind"] for i in out}}} # ── PoE-бюджет ── def poe_check(self, items): """Хватает ли PoE-бюджета коммутаторов на устройства в составе.""" switches, ports_total = [], 0 for row in items: m = row[0] q = int(row[1]) if len(row) > 1 else 1 info = self.iface_map.get(norm(m)) or {} b = info.get("poe_budget_w") if b: switches.append((m, float(b) * q, q)) ports_total += int(info.get("poe_ports") or 0) * q if not switches: return [] budget = sum(b for _, b, _ in switches) need, unknown, powered = 0.0, [], [] for row in items: m = row[0] q = int(row[1]) if len(row) > 1 else 1 k = norm(m) role = (self.devices.get(k) or {}).get("role") if role in ("infrastructure", "power", "charger", "display", "pc"): continue w = (self.attrs.get(k) or {}).get("power.consumption_w") if w is None: unknown.append(m) else: need += float(w) * q powered.append(m) out = [{"kind": "poe", "ok": need <= budget, "text": "PoE: нужно %.0f Вт из %.0f Вт (портов PoE: %d)%s" % (need, budget, ports_total, "" if need <= budget else " — НЕ ХВАТАЕТ")}] if unknown: out.append({"kind": "poe", "ok": True, "text": "нет данных о потреблении: " + ", ".join(unknown[:6])}) return out # ── батарея беспроводных устройств ── def battery_check(self, items, hours=8.0): """Хватит ли заряда на совещание заданной длительности.""" out = [] total_mah = 0 worst = None for row in items: model = row[0] qty = int(row[1]) if len(row) > 1 else 1 k = norm(model) info = (self.iface_map.get(k) or {}) bh = info.get("battery_hours") if not bh: continue mah = info.get("battery_mah") total_mah += int(mah or 0) * qty if worst is None or bh < worst[1]: worst = (model, bh, qty) need = "хватит" if bh >= hours else "НЕ хватит (%.0f ч < %.0f ч)" % (bh, hours) out.append({"kind": "battery", "device": model, "qty": qty, "hours": bh, "mah": mah, "need_hours": hours, "ok": bh >= hours, "text": "%s ×%d: заряд %s ч — %s" % (model, qty, bh, need)}) if out and worst: out.append({"kind": "battery", "ok": True, "text": "суммарная ёмкость беспроводных: %d мА·ч; " "минимальный запас — %s (%s ч)" % (total_mah, worst[0], worst[1])}) return out # ── ручной ввод характеристики ── ALLOWED_ATTRS = { "audio.pickup_m": "м", "audio.spl_max": "dB SPL", "camera.fov_h": "°", "camera.fov_v": "°", "camera.zoom_optical": "×", "camera.zoom_hybrid": "×", "power.consumption_w": "Вт", "ports.vch": "шт", "ports.hdmi_out": "шт", "ports.hdmi_in": "шт", "ports.usb": "шт", "physical.weight_kg": "кг", } def set_override(self, device, attr, value): import yaml as _yaml if attr not in self.ALLOWED_ATTRS: return {"error": "недопустимый параметр: %s" % attr} try: v = float(str(value).replace(",", ".")) except (TypeError, ValueError): return {"error": "значение должно быть числом"} if v < 0 or v > 100000: return {"error": "значение вне допустимого диапазона"} k = norm(device) entry = None for x in (self.overrides.get("devices") or []): if norm(x["device"]) == k: entry = x break if entry is None: entry = {"device": self.devices.get(k, {}).get("name") or device, "attributes": {}} self.overrides.setdefault("devices", []).append(entry) entry.setdefault("attributes", {})[attr] = v entry["updated"] = __import__("time").strftime("%Y-%m-%dT%H:%M:%S") p = os.path.join(BASE, "overrides.yaml") with open(p, "w", encoding="utf-8") as f: _yaml.safe_dump(self.overrides, f, allow_unicode=True, sort_keys=False, width=180) # применить сразу self.rebuild() return {"ok": True, "device": entry["device"], "attr": attr, "value": v, "unit": self.ALLOWED_ATTRS[attr]} # ── тип установки устройства ── CEILING = r"^VCM|^CM50|^CS10-D|^CLS120|^MSpeaker|^RCH|^AVHub" TABLE = r"^CM20|^CS10\b|^CP50|^CPE|^CP965|^CTP|^MTouch|^PA\d|^VCR" WALL = r"^UVC|^SmartVision|^MB-CAM|MeetingDisplay|^ETV" RACK = r"^MCore|^MeetingEye|^MeetingBar|^MeetingBoard|^PVB|^PVT|^AP08|^AVBridge|^VCH|^WPP" def mount_class(self, name): n = str(name) if re.match(self.CEILING, n, re.I): return "ceiling" if re.match(self.TABLE, n, re.I): return "table" if re.match(self.WALL, n, re.I): return "wall" if re.match(self.RACK, n, re.I): return "rack" return "other" def coverage(self, name): """Радиус захвата микрофона и угол обзора камеры (из данных).""" a = self.attrs.get(norm(name), {}) return {"pickup_m": a.get("audio.pickup_m"), "fov_h": a.get("camera.fov_h"), "zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid")} # ── покрытие по зонам (сетка) ── def coverage_grid(self, host_key, items, w=8.0, l=10.0, cell=0.5): """Считает покрытие микрофонами по сетке комнаты. Возвращает матрицу «сколько микрофонов достаёт до точки» и процент площади с покрытием хотя бы одним микрофоном. """ mics = [] for r in items: model, qty = r[0], int(r[1]) p = self.attrs.get(norm(model), {}).get("audio.pickup_m") if p: mics.append({"model": model, "qty": qty, "radius": float(p)}) built = self.attrs.get(norm(host_key), {}).get("audio.pickup_m") if built: mics.append({"model": "встроенный", "qty": 1, "radius": float(built)}) if not mics: return {"ok": False, "reason": "нет данных о дальности микрофонов", "grid": [], "covered_pct": 0} nx, ny = max(1, int(w / cell)), max(1, int(l / cell)) # считаем, что микрофоны распределены по потолку равномерно total_units = sum(m["radius"] and m["qty"] for m in mics) or 1 positions = [] idx = 0 for m in mics: for _ in range(m["qty"]): frac = (idx + 1) / (total_units + 1) positions.append({"x": w * frac, "y": l * 0.5, "r": m["radius"], "model": m["model"]}) idx += 1 grid, covered = [], 0 for j in range(ny): row = [] for i in range(nx): cx, cy = (i + 0.5) * cell, (j + 0.5) * cell n = sum(1 for p in positions if (p["x"] - cx) ** 2 + (p["y"] - cy) ** 2 <= p["r"] ** 2) row.append(n) if n: covered += 1 grid.append(row) return {"ok": True, "grid": grid, "nx": nx, "ny": ny, "cell": cell, "w": w, "l": l, "positions": positions, "covered_pct": round(100.0 * covered / (nx * ny), 1), "mics": len(positions)} # ── комплектация ── def package(self, name): k = norm(name) p = self.pkg_map.get(k) if p: return {"items": p.get("items") or [], "kits": p.get("optional_kits") or [], "source": "verified"} if self.pkg_llm.get(k): return {"items": self.pkg_llm[k], "kits": [], "source": "llm"} for x in self.pkg_a.get("devices") or []: if norm(x.get("device")) == k: return {"items": x.get("items") or [], "kits": [], "source": "auto"} return {"items": [], "kits": [], "source": None} # ── крепление уже в комплекте? ── def mount_included(self, name): pkg = self.package(name) for it in pkg.get("items") or []: low = str(it).lower() if any(w in low for w in ("кронштейн", "крепёж", "крепеж", "bracket", "mount", "стойк")): return True return False # ── полнота данных ── def completeness(self, host_key): hk = norm(host_key) srcs = {} for e in self.edges.get(hk, []): s = e.get("source") or "?" srcs[s] = srcs.get(s, 0) + 1 total = sum(srcs.values()) 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 строк) — в матрице хоста нет" % total) else: level, note = "none", "связей нет" return {"level": level, "note": note, "edges": total, "sources": srcs} # ── авто-сборка по выбору пользователя ── def autofill(self, host_key, seats=8, include=None, need=None): """include: ['camera','panel','display','mount','sharing','mic']""" include = set(include or ["mic", "camera", "panel", "display", "sharing"]) need = list(need 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 items, notes = [], [] def by_role(role): return [e for e in self.edges_of(hk) if self.devices.get(norm(e["to"]), {}).get("role") == role] items.append({"model": host, "qty": 1, "role": "Хост", "why": "основа"}) # микрофоны if "mic" in include: built = self.attrs.get(hk, {}).get("audio.pickup_m") if built and built >= need_m: notes.append("встроенный микрофон покрывает %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] qty = max(1, -(-need_m // max(int(p), 1))) if p else 1 items.append({"model": e["to"], "qty": qty, "role": "Микрофон", "why": "нужно %s м, у %s %s м" % (need_m, e["to"], p or "—")}) if "camera" in include: 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) c = 1 if "content camera" in (e.get("condition") or "").lower() else 0 return z - c * 100 cams.sort(key=sc, reverse=True) items.append({"model": cams[0]["to"], "qty": 1, "role": "Камера", "why": "совместима"}) if "panel" in include: p = by_role("touch") if p: items.append({"model": p[0]["to"], "qty": 1, "role": "Панель", "why": "совместима"}) if "sharing" in include: sh = [e for e in by_role("sharing_or_hub") if re.match(r"^WPP", e["to"], re.I) or re.match(r"^VCH", e["to"], re.I)] if sh: items.append({"model": sh[0]["to"], "qty": 1, "role": "Презентация", "why": "совместима"}) if "display" in include: d = by_role("display") if d: items.append({"model": d[0]["to"], "qty": 1, "role": "Дисплей", "why": "совместим"}) else: notes.append("у Yealink нет дисплея для этого хоста — нужен внешний ТВ") if "mount" in include: mnts = self.mounts_map.get(hk) or [] chosen = None for m in mnts: if not self.mount_included(m): chosen = m break if chosen: items.append({"model": chosen, "qty": 1, "role": "Кронштейн", "why": "совместим, не входит в комплект"}) elif mnts: notes.append("все совместимые крепления уже входят в комплект") else: notes.append("совместимых креплений нет") if any(norm(x) == "dante" for x in need): notes.append("требуется Dante — добавьте комплект CM50+CS10-D+AP08") cap = self.capacity(hk, [[i["model"], i["qty"]] for i in items if not i["model"].startswith("встроенный")]) return {"host": host, "seats": seats, "need_pickup": need_m, "items": items, "notes": notes, "capacity": cap, "completeness": self.completeness(hk)} # ── совместимость ── def edges_of(self, host_key, supported_only=True): out = [] for e in self.edges.get(norm(host_key), []): if supported_only and (not e.get("supported") or not e.get("usable", True)): continue out.append(e) return out def check_pair(self, host_key, device): hk, ak = norm(host_key), norm(device) host = self.devices.get(hk, {}).get("name") dev = self.devices.get(ak, {}).get("name") or device if not host: return {"error": "хост не найден"} found = next((e for e in self.edges.get(hk, []) if norm(e["to"]) == ak), None) if not found: return {"host": host, "device": dev, "known": False, "supported": False, "verdict": "нет в матрице для этого хоста"} cond = re.sub(r"^[\u221a\u2713\u2714\u00d7\u2717\u2718\u2022\s]+", "", found.get("condition") or "").strip() if not found.get("usable", True): verdict = "исключено: источники расходятся" elif found.get("supported"): q = found.get("max_qty") verdict = "совместимо" + (" (до %s шт)" % q if q else "") else: verdict = "несовместимо" return {"host": host, "device": dev, "known": True, "supported": bool(found.get("supported")), "usable": found.get("usable", True), "max_qty": found.get("max_qty"), "condition": cond, "source": found.get("source"), "verdict": verdict} # ── ёмкость и подсчёт портов ── def capacity(self, host_key, items, infra_items=None): hk = norm(host_key) host = self.devices.get(hk, {}).get("name") ha = self.attrs.get(hk, {}) vch_ports = ha.get("ports.vch") total_w, missing_w, vch_users = 0.0, [], 0 qtys = {} for row in items: model, qty = row[0], int(row[1]) qtys[model] = qtys.get(model, 0) + qty limits = {norm(e["to"]): (e.get("max_qty"), e["to"]) for e in self.edges.get(hk, []) if e.get("supported")} issues = [] 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 # инфраструктура: порты с учётом каскада (каждый доп. коммутатор # занимает 1 порт предыдущего) total_infra_ports, extra_budget, n_switches = 0, 0.0, 0 for inf in (infra_items or []): for x in (self.infra.get("devices") or []): if norm(x["device"]) == norm(inf): sp = x.get("specs") or {} total_infra_ports += int(sp.get("poe_ports") or 0) extra_budget += float(sp.get("poe_budget_w") or 0) n_switches += 1 extra_ports = max(0, total_infra_ports - max(0, n_switches - 1)) chains_needed = None if vch_users and vch_ports is not None: total_ports = int(vch_ports) + extra_ports chains_needed = vch_users if total_ports < vch_users else 1 if vch_users > total_ports: issues.append("VCH: %d устройств на %d порт(а) — нужны цепочки или RCH40 E2" % (vch_users, total_ports)) return {"host": host, "vch_ports": vch_ports, "vch_users": vch_users, "extra_ports": extra_ports, "extra_budget_w": extra_budget, "n_switches": n_switches, "raw_infra_ports": total_infra_ports, "total_power_w": round(total_w, 1), "power_budget_w": extra_budget or None, "missing_power": sorted(set(missing_w)), "issues": issues, "chains_needed": chains_needed} # ── подсчёт портов (port accounting) ── def port_plan(self, host_key, items): hk = norm(host_key) host = self.devices.get(hk, {}).get("name") h_in, h_out, h_src = self.ports(host) used_in, used_out = [], [] rows = [] for row in items: model, qty = row[0], int(row[1]) if len(row) > 1 else 1 a_in, a_out, src = self.ports(model) role_dev = self.devices.get(norm(model), {}).get("role") need = [p for p in a_out if p != "—"] or [p for p in a_in if p != "—"] port = need[0] if need else None slot = None if port: cands = [] # устройство -> вход хоста # инфраструктура (PoE-свитчи): сеть соединяется «порт-порт», # направление не важно — LAN есть и там, и там if role_dev in ("infrastructure", None, "unknown") and "LAN" in (a_in + a_out): for ap in [p for p in (a_in + a_out) if p != "—"]: for hp in (h_in + h_out): if (ap, hp) in self.LINKABLE or (hp, ap) in self.LINKABLE: cands.append((self.PORT_RANK.get(ap, 9), ap, "out:" + hp if hp in h_out else hp)) # устройство (выход) -> вход хоста for ap in [p for p in a_out if p != "—"]: for hp in h_in: if (ap, hp) in self.LINKABLE or (hp, ap) in self.LINKABLE: cands.append((self.PORT_RANK.get(ap, 9), ap, hp)) # выход хоста -> вход устройства (только входы, не выходы!) for hp in h_out: for ap in [p for p in a_in if p != "—"]: if (hp, ap) in self.LINKABLE or (ap, hp) in self.LINKABLE: cands.append((self.PORT_RANK.get(ap, 9) + 100, ap, "out:" + hp)) if cands: role = self.devices.get(norm(model), {}).get("role") pref = self.ROLE_PORT_PREF.get(role) or [] def rank(item): r, ap, hp = item # беспроводная связь приоритетнее любого кабеля if ap == "WL" and str(hp) == "WL": return -1000 base = 0 # дисплей принимает видео — подключаем к ВЫХОДУ хоста, # иначе он цепляется к HDMI-входу кодека (BYOD). if role == "display" and not str(hp).startswith("out:"): base = 500 if ap in pref: return base + pref.index(ap) return base + 90 + r cands.sort(key=rank) _, port, slot = cands[0] # матрица совместимости главнее портов: если связь «хост → устройство» # помечена как неподдерживаемая, схема недействительна. reason = None in_matrix = None for e in self.edges_of(hk, supported_only=False): if norm(e.get("to")) == norm(model): in_matrix = e break if in_matrix is not None and not in_matrix.get("supported"): reason = "не поддерживается матрицей: " + \ ((in_matrix.get("condition") or "").strip() or "×") slot = None elif in_matrix is None and self.devices.get(norm(model), {}).get("role") not in ( "display", "pc", "infrastructure"): # устройство не из матрицы Yealink (ПК, проектор, свитч) — это нормально reason = "нет в матрице — подключение по портам" # ПК с беспроводным мостом (WPP30) в составе — только через мост: # кабелем в терминал нельзя, там HDMI только выход. if role_dev == "pc" and slot: for m2, _q2 in items: b_in, b_out, _ = self.ports(m2) # мост = устройство с беспроводным выходом И USB-входом (донгл), # иначе под правило попадали бы сами микрофоны if "WL" in b_out and ("USB" in b_in or "USB-C" in b_in): slot = None break if slot and slot.startswith("out:"): used_out.append(slot[4:]) elif slot: used_in.append(slot) rows.append({"device": model, "qty": qty, "needs_port": port, "host_port": slot, "source": src, "ok": bool(slot), "reason": reason, "matrix": (None if in_matrix is None else bool(in_matrix.get("supported")))}) # ── второй проход: ЦЕПОЧКИ ── # Если хост не может принять устройство напрямую (или матрица против), # ищем промежуточное устройство в составе, которое это умеет. # Пример: RoomCast E2 + UVC86 + VCM36-W×3 — микрофоны идут через камеру. chains = [] by_name = {norm(r["device"]): r for r in rows} for r in rows: if r["ok"]: continue dn = norm(r["device"]) for cn, c_row in by_name.items(): if not c_row["ok"] or cn == dn: continue e = next((x for x in self.edges.get(cn, []) if norm(x.get("to")) == dn and x.get("supported")), None) if not e: continue # промежуточное устройство должно иметь подходящий порт; # если порт не сходится, допускаем только когда матрица # прямо разрешает (вендор знает лучше нашей модели портов). v_in, v_out, _ = self.ports(self.devices.get(cn, {}).get("name") or cn) a_in, a_out, _ = self.ports(model) vports = [p for p in (v_in + v_out) if p != "—"] aport = [p for p in (a_in + a_out) if p != "—"] port_ok = any((p, q) in self.LINKABLE or (q, p) in self.LINKABLE for p in aport for q in vports) if not port_ok and cn not in by_name: continue mx = e.get("max_qty") used = sum(int(x["qty"]) for x in rows if x.get("via") and norm(x["via"]) == cn) if mx is not None and used + int(r["qty"]) > int(mx): continue via = self.devices.get(cn, {}).get("name") or cn r["via"] = via r["ok"] = True r["reason"] = ("через %s (до %s)" % (via, mx if mx is not None else "—") + ("" if port_ok else " · порт по матрице")) chains.append({"via": via, "device": r["device"], "qty": r["qty"], "max_qty": mx, "condition": (e.get("condition") or "").strip()[:100]}) break # ── третий проход: мост (2 шага) ── # Пример: ПК подключается не кабелем в RoomCast (там HDMI только выход), # а через беспроводной донгл WPP30: ПК ←USB← WPP30 ⇢WL⇢ RoomCast. for r in rows: if r["ok"]: continue for bn, b_row in by_name.items(): if not b_row["ok"] or bn == norm(r["device"]): continue b_in, b_out, _ = self.ports(self.devices.get(bn, {}).get("name") or bn) # мост должен уметь беспроводную передачу и цепляться к хосту if "WL" not in b_out: continue host_ok = ("WL" in h_in) or ("WL" in h_out) if not host_ok: continue a_in, a_out, _ = self.ports(r["device"]) aport = [p for p in (a_in + a_out) if p != "—"] bports = [p for p in (b_in + b_out) if p != "—"] if not any((p, q) in self.LINKABLE or (q, p) in self.LINKABLE for p in aport for q in bports): continue via = self.devices.get(bn, {}).get("name") or bn r["via"] = via r["ok"] = True r["reason"] = "через %s (беспроводно)" % via chains.append({"via": via, "device": r["device"], "qty": r["qty"], "max_qty": None, "condition": "беспроводной мост"}) break return {"host": host, "host_in": h_in, "host_out": h_out, "source": h_src, "rows": rows, "chains": chains, "used_in": used_in, "used_out": used_out, "free_in": [p for p in h_in if p not in used_in], "free_out": [p for p in h_out if p not in used_out], "unresolved": [r["device"] for r in rows if not r["ok"]]} # ── кабельный журнал ── def cable_schedule(self, host_key, items): plan = self.port_plan(host_key, items) cables = [] for r in plan["rows"]: if not r["ok"]: continue port = r["needs_port"] if r.get("via"): # цепочка: промежуточное устройство → аксессуар cables.append({"from": r["via"], "from_port": "→ " + str(port), "to": r["device"], "to_port": port, "type": port, "qty": r["qty"], "note": r.get("reason") or ""}) continue cables.append({"from": plan["host"], "from_port": r["host_port"], "to": r["device"], "to_port": port, "type": port, "qty": r["qty"], "note": "в комплекте" if self.package(r["device"])["items"] else ""}) return {"host": plan["host"], "cables": cables, "count": len(cables), "unresolved": plan["unresolved"]}