[WORK] Link View: связи по разъёмам (HDMI/USB/USB-C/VCH/LAN/3.5mm), порты с источником (даташит/извлечено/роль), запрет UVC86 HDMI+MVC

This commit is contained in:
root committed 2026-11-06 16:02:51 +03:00
1 parent b433314eae
commit daffbe41dd
5 files changed
+582 -24

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
# Link View: связи по разъёмам
Дата: 06.11.2026. Три задачи: порты всех устройств, связи по разъёмам,
запрещённые связи.
## 1. Порты: три уровня доверия
| Уровень | Источник | Устройств |
|---|---|---|
| **verified** | `interfaces_verified.yaml` — выписано из даташитов вручную | 7 |
| **auto** | `interfaces.yaml` — извлечено регексом из даташитов | 23 |
| **role** | эвристика по роли (помечена как ненадёжная) | остальные |
Интерфейс **показывает источник** у каждого узла: даташит / извлечено / по роли.
## 2. Связи по разъёмам
`/api/links` строит пары «выход аксессуара → вход хоста» (и наоборот)
по правилам совместимости:
| Пара | Что передаёт |
|---|---|
| HDMI ↔ HDMI | видео |
| USB ↔ USB | данные |
| USB-C ↔ USB-C | данные + видео |
| USB ↔ USB-C | данные (через переходник) |
| VCH ↔ VCH | аудио + питание |
| LAN ↔ LAN | сеть / PoE |
| 3.5mm ↔ 3.5mm | аналоговый звук |
| DP ↔ DP | видео |
Если пары нет — связь показывается **красным пунктиром** с причиной:
«нет совместимого разъёма» и перечислением портов обеих сторон.
### Пример (MeetingBar A50)
```
хост порты: in=VCH,USB,USB-C,LAN out=HDMI,USB,3.5mm (извлечено)
✓ UVC86 [даташит] USB -> USB данные
✓ WPP30 [даташит] USB -> USB-C данные (через переходник)
✓ VCH51 Pro [даташит] USB -> USB-C данные (через переходник)
✓ CTP25 [извлечено] USB -> USB данные
```
## 3. Запрещённые связи
Правило из даташита UVC86:
> HDMI-выход UVC86 совместим с VCS-устройствами, но **НЕ с MVC**.
Реализовано в `FORBIDDEN`: если устройство = UVC86, порт = HDMI,
а хост в MVC-режиме — связь запрещается с пояснением.
**Ограничение:** в данных пока нет MVC-хостов (MVC — это комплект/режим,
а не отдельная модель), поэтому правило ещё ни разу не сработало на реальном
примере. Нужно добавить режим системы (VCS/MVC) в выбор, чтобы проверять.
## Что осталось
1. **Порты остальных ~100 устройств** — выписать из даташитов (сейчас 30 из 131)
2. **Режим системы VCS/MVC** — добавить переключатель, тогда запрет заработает
3. **Направление связи** — различать «хост → устройство» и «устройство → хост»
4. **Кабели в BOM** — если связь HDMI, добавить HDMI-кабель
+252
View File
@@ -0,0 +1,252 @@
source: даташиты (регекс по строкам Interface/Ports)
devices:
- device: AP08
in:
- LAN
- USB
out:
- LAN
- USB
- PHOENIX
evidence:
- 'Input Channels: - 2 * RCA input - 2 * 3-pin Analog input Output Channels: - 2 * RCA output - 2 * 3-pin Analog output Frequency Response: 20-20KHz THD+N: <1% Input Dynamic Range: 96dB Output
Dynamic Range: 98dB Self-Noise: - RCA (Unbalanced): -94dBu - Analog (Balanced): -86dBu Input Clipping Range: 0 to 64dB Output Sensitivity Range: -40dBu to 24dBu Phantom power: +48VDC 10 mA
max'
- 'Input Channels: 2 * USB input Output Channels: 2 * USB output Sampling Rate: 48KHz Bit Depth: 16bit/24bit'
- 'MGMT: RJ-45 for API control RS232: 1 * 3-pin phoenix port GPIO in: 8-pin phoenix port, 1-8 inputs, Analog input or contact closure (up to 24V) with switchable 5V pull-up GPIO out: 8-pin phoenix
port, 1-8 outputs, open-drain output (up to 24V, 0.3A), default state +3.3V +12VDC: 0.1A GND: Earth'
- device: CM50
in:
- LAN
out:
- PHOENIX
evidence:
- 'Frequency response range: 120-20KHz Sensitivity: 0 dBV/Pa 94dBSPL@1kHZ Signal-to-noise ratio: 86dB @1kHz, 94dBSPL A-Weighted Maximum sound pressure level: 122dB at < 1% THD Dynamic range:
86dB @<1% THD Support Protocol: Dante, AES67'
- 'Microphone array: 127 MENS array Acoustic technology: Beamforming Product dimensions: L592*W592*T56mm Product weight: 5.15kg (net weight, excluding accessories) Product color: Apple White
Product Material: SGCC/SPCC/AL5052 Certification: Plenum Rated UL 2043 (suitable for air handling spaces) Physical interface: - 1* RJ-45 interface - 1* 3-pin Phoenix connectors for analog
output'
- 'Giftbox dimensions (L*W*H): 722 * 687 * 110 mm Weight: - N.W/CTN: 7.750 kg - G.W/CTN: 9.790 kg Storage temperature: -30~70℃'
- device: CP50
in:
- USB-C
out: []
evidence:
- 'Power input: - DC power adapter: DC48V/0.7A or DC48V/2A - PoE power: Not supported'
- 'Power output: - USB external power: Not supported'
- Built-in 1 x 4W speaker
- device: CPE40
in:
- USB-C
out: []
evidence:
- 'Power output: - USB power supply: Not supported'
- Built-in 1 x 4W speaker
- '1×Codec port: Connect to the previous omnidirectional microphone'
- device: CT300
in:
- PHOENIX
- LAN
- USB-C
out:
- PHOENIX
evidence:
- 1 × PoE port 1 × RJ45 port 6 × RS232 port 2 × RS422/485 port 2 × IR out port 4 × Relay port 4 × GPIO in/out 1 × IR Learning port 1 × MGMT port 1× 12V/2A power supply port
- '2 bidirectional RS232 ports Baud Rate: 300~11520 baud Pin configurations: Pin1=Tx, Pin2=Rx, Pin3=Gnd'
- '2 bidirectional RS422/485 port Baud Rate: 300~11520 baud Pin configurations:RS422: Pin1=Tx+, Pin2=Rx+, Pin3=Gnd, Pin4=Tx-, Pin5=Rx- RS485: Pins 1 and 2 (tied together)=data+, pin3=Gnd, pins
4 and 5 (tied together)=data'
- device: CTP25
in:
- USB
out: []
evidence:
- 1280 x 80
- Multi points capacitive touch support
- 802.1X and LLDP-MED
- device: MSpeaker Pro
in:
- VCH
out: []
evidence:
- Additionally, MSpeaker Pro supports star-t opology
- 1 x VCH, supports standard PoE/POE+ power supply
- 1 x Yealink MSpeaker pro 1 x mount bracket kit 1 x 3m CAT5e cable 1 x quick start guide
- device: MVC MCoreKit-C5U
in:
- USB
- LAN
- HDMI
- 3.5mm
out:
- HDMI
evidence:
- 'Processor: Intel Ultra5 125H Memory: 16GB(2*8GB) DDR5 Storage: 256GB SSD BIOS feature: 3x HDMI video output - CEC - EDID TPM2.0 Kernel DMA Interfaces: 1 x HDMI-Out 2.1 port 2 x HDMI-Out 2.0
port 1 x HDMI-In port 4 x USB3.0 type-A port 1 x MTouch port (RJ-45) 1 x LAN port for AV network 1 x 10/100/1000 Gigabit Ethernet port 1 x power supply port 1 x 3.5mm headphone port 1 x reset
port 1 x security slot WiFi: IEEE 802.11 a/b/g/n/ac/ax Bluetooth: BT5.2'
- 'Physical features: 11.6-inch narrow bezel IPS display Angle between screen and desktop (30° ~ 70°) Adjustable angle of support frame (50° ~ 180°) Function features: 1920 x 1080 video resolution
Support wired and wireless (with WPP30) content sharing Support an external PD power supply to power the sharing device'
- 6GB(2*8GB) DDR
- device: MeetingBar A40
in:
- USB-C
- HDMI
- USB
- LAN
- VCH
out:
- HDMI
- 3.5mm
evidence:
- Lens FOV - 2x Tele Camera:120° DFOV, 110° HFOV, 54° VFOV
- 'Maximum pixels: 2 * 48MP pixels'
- USB2.0C USB-C port
- device: MeetingBar A50
in:
- VCH
- USB
- USB-C
- LAN
out:
- HDMI
- USB
- 3.5mm
evidence:
- 'Lens FOV - 1x Wide Camera: DFOV 110, HFOV 98°, VFOV 81° - 2x Tele Camera: DFOV 51°, HFOV 41.6°, VFOV 31.8°'
- 'Maximum pixels: 3x 50MP pixel'
- 8 x digital zoom
- device: MeetingBoard Pro
in:
- USB
- VCH
- OPS
out:
- HDMI
evidence:
- 'Size MeetingBoard 65 Pro: 65 inch MeetingBoard 75 Pro: 75 inch MeetingBoard 86 Pro: 86 inch Anti-Glare Panel Resolution: 3840 × 2160 Color Gamut: 72% NTSC/99% sRGB Color Depth: 1.07G (10
bit) Contrast Ratio: 1200:1 Brightness: 400 cd/㎡ Refresh Rate: 60 Hz Viewing Angle: 178°(H)/178°(V)'
- 'Max Resolution: Built-in triple 50MP camera Image Sensor: Sony Sensor X3 Viewing Angle: Wide-Angle HFOV 98.2° PTZ Type: Electronic Pan-Tilt Zoom/Digital Zoom: 8 × digital zoom Max Resolution:
3840 × 2160 Max Frame Rate: 60 Hz Video Output Resolution: 3840 × 2160 Autofocus: Supported Wide Dynamic Range: Supported High Dynamic Range Imaging: Supported Exposure: Auto White Balance:
Auto/Manual/ATW Number of Presets: 9 Privacy shutter: Electric privacy shutter Swappable Optical Zoom Camera Module MB-12X Pro 8MP, Sony Image Sensor 12× Optical Zoom Lens Angle: HFOV 90°
Horizontal Rotation: ±100° Vertical rotation: 0°/-90° AI Smart Framing'
- 'Speakers: Stereo Speakers Frequency Response: 90~20 KHz Sensitivity: 87±3 dB SPL @ 0.5 m, 1 W Sampling Rate: 48 KHz Expansion Output: Supports RCA Output THD (Total Harmonic Distortion):
at 20 W, 1 KHz, < 5% Rated Impedance: Tweeter-4ohm,Full-Range Speaker-8ohm Rated Power: 30 W Max Power: 36 W'
- device: MeetingDisplay
in:
- LAN
out:
- USB
evidence:
- 'Screen Size MeetingDisplay 55: 55 inch MeetingDisplay 65: 65 inch MeetingDisplay 75: 75 inch MeetingDisplay 86: 86 inch Display Type: IPS Surface Treatment: Anti-glare Coating Refresh Rate:
60 Hz Grayscale Response Time: 8ms Color Gamut: 72% NTSC Colour Depth: 1.07G (10-bit) Viewing Angle: 178°(H)/178°(V) Contrast Ratio: 1200: 1 Resolution: 3840 × 2160 Brightness: 500 cd/㎡'
- 'Video: HDMI In 2.1 × 3 Audio: 3.5mm Stereo Mini Jack (Output) USB: USB-A 2.0 × 2, USB-B 2.0 × 1 LAN: 2 × RJ45 10/100/1000M network ports Control: RS232 × 1, IP Control(Via LAN) Others: Reset
× 1'
- 'WiFi: Wi-Fi 6 2.4G & 5G dual-band, 802.11a/b/g/n/ac/ax Bluetooth: Bluetooth 5.1 IR: Supported'
- device: MeetingEye 500
in:
- USB
- HDMI
- VCH
out: []
evidence:
- It supports 4Kp30 UHD video and content sharing .
- MeetingEye 500 can work wit h the Yealink 36x
- It s VCH interface is able to convey not only the data a nd control signal but also
- device: PVB650_750_860 (MeetingBoard Pro
in:
- USB
- LAN
- VCH
- HDMI
- OPS
out:
- HDMI
- USB
evidence:
- 'Resolution: 3840 x 2160'
- 'Expansion output: Supports RCA output'
- 'Expansion input: supports RCA input'
- device: RCH40&RCH40 E2
in:
- LAN
out: []
evidence:
- 0x30 to 0x3f 48 ~ 63 110000 to 111111
- 0x27 to 0x2f 39 ~ 47 100111 to 101111
- 0x22 to 0x26 34 ~ 38 100010 to 100110
- device: RCH40pRCH40 E2
in:
- LAN
out: []
evidence:
- 0x30 to 0x3f 48 ~ 63 110000 to 111111
- 0x27 to 0x2f 39 ~ 47 100111 to 101111
- 0x22 to 0x26 34 ~ 38 100010 to 100110
- device: RoomSensor_Pro
in:
- USB
- LAN
out: []
evidence:
- 'Ethernet: 1 x Ethernet port (10/100Mbps)'
- 'USB: 1 x USB-A'
- 'LED: - 1×USB LED - 1×System LED'
- device: UVC40 E2
in:
- USB
out: []
evidence:
- UVC40 E2 supports r emote managemen t on the Yealink Device Management Platform via a
- nly supports framing t he groups automatically according to the number a nd position of the
- It s upports an optional w ireless/ wired expansio n microphone to expand the boundaries
- device: UVC85-BYOD
in:
- USB
- 3.5mm
- VCH
- USB-C
out:
- HDMI
- 3.5mm
evidence:
- supports 4K ultra high definition video.
- optical zo om, 3x digit al zoom, and a 90° wide angle lens, it easily c overs medium to large
- s unified m anagemen t and reportin g of t he main device and its connected accessories, and
- device: UVC86
in:
- USB
out: []
evidence:
- HD z oom ( 12x optical, 1.7x digital)
- 1 x USB3.0 Type B Port
- x USB2.0 Type A Port
- device: UVC86 E2
in:
- USB
- 3.5mm
- LAN
- VCH
out:
- 3.5mm
- HDMI
evidence:
- 1 x USB3.0 Type-B Port
- 1 x USB2.0 Type-A Port
- 1 x Yealink LAN Port (RJ45)
- device: VCH51 Pro
in:
- USB-C
- LAN
out: []
evidence:
- USB C cable of VCH51 Pro supports 4K content sharing, wired BYOD (Bring
- Pro supports up to 4K/60fps wired presenting with low latency,
- Pro is suitable for devices that s upport free c ollaboration and have a full
- device: VCM36-W
in:
- USB-C
- USB
out: []
evidence:
- 'Dimension: Microphone: 100 x 16.5 mm Charge Cradle: 100 x 10.5 mm'
- 1x VCM36-W Video Conference Microphone
- 1x Charger Cradle
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Извлечение портов из даташитов (v2): надёжный разбор строк Interface/Ports.
Умеет разбирать склеенные строки вида:
"Interface -1 x 1000Mbps RJ45 port -1 x USB 2.0 Type C -1 x PD power port"
Выдаёт: устройство -> {in: [...], out: [...], evidence: [...]}
"""
import glob
import os
import re
import sys
BASE = "/opt/work-hub/compat"
DEV = "/opt/work-hub/devices/yealink"
CONNECTORS = [
(r"usb[\s-]?c|type[\s-]?c", "USB-C"),
(r"usb\s*3|usb\s*2|usb\s*type|usb", "USB"),
(r"hdmi", "HDMI"),
(r"vch", "VCH"),
(r"rj[\s-]?45|ethernet|1000mbps|lan", "LAN"),
(r"displayport|\bdp\b", "DP"),
(r"3\.5\s*mm|line[\s-]?in|line[\s-]?out|line", "3.5mm"),
(r"rj[\s-]?9", "RJ-9"),
(r"phoenix|gpio|rs232|rs-232", "PHOENIX"),
(r"ops slot|ops", "OPS"),
(r"sd card|microsd", "SD"),
]
SPLIT = re.compile(r"(?=\d+\s*[x×*]\s*[A-Za-zА-Яа-я0-9])")
def canon(desc):
d = desc.lower()
for pat, name in CONNECTORS:
if re.search(pat, d):
return name
return None
def direction(desc):
d = desc.lower()
if re.search(r"\bout(put)?\b", d):
return "out"
if re.search(r"\bin(put)?\b", d) or "video input" in d:
return "in"
if "device interface" in d or "device port" in d:
return "in"
return None
def parse_text(text):
ins, outs, unknown = [], [], []
for chunk in SPLIT.split(text):
m = re.match(r"(\d+)\s*[x×*]\s*(.+)", chunk.strip())
if not m:
continue
n = int(m.group(1))
if not (1 <= n <= 16):
continue
desc = m.group(2)
c = canon(desc)
if not c:
continue
d = direction(desc)
if d == "out":
outs += [c] * n
elif d == "in":
ins += [c] * n
else:
unknown += [c] * n
return ins, outs, unknown
def main():
import yaml
result = {}
for f in glob.glob(os.path.join(DEV, "*.yaml")):
try:
d = yaml.safe_load(open(f, encoding="utf-8"))["device"]
except Exception:
continue
model = re.sub(r"\s*\(\d+\)?\s*$", "", d.get("model") or "").strip()
if not model:
continue
lines = []
for k, vals in (d.get("specs") or {}).items():
lines += [str(v) for v in vals]
# строки, где вообще есть упоминание портов
cand = [ln for ln in lines if re.search(r"\d+\s*[x×*]|interface|port", ln, re.I)]
ins, outs, unk = [], [], []
for ln in cand:
a, b, c = parse_text(ln)
ins += a
outs += b
unk += c
if not (ins or outs or unk):
continue
# неизвестные по умолчанию считаем входами
ins += unk
def dedupe(seq):
from collections import Counter
return [k for k, _ in Counter(seq).most_common()]
entry = {"in": dedupe(ins)[:6], "out": dedupe(outs)[:6]}
prev = result.get(model)
score = len(entry["in"]) + len(entry["out"])
if prev and prev["_score"] >= score:
continue
entry["_score"] = score
entry["evidence"] = cand[:3]
result[model] = entry
for v in result.values():
v.pop("_score", None)
path = os.path.join(BASE, "interfaces.yaml")
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump({"source": "даташиты (регекс по строкам Interface/Ports)",
"devices": [{"device": k, **v} for k, v in sorted(result.items())]},
f, allow_unicode=True, sort_keys=False, width=190)
print("устройств с портами:", len(result))
for k in ("VCH51 Pro", "WPP30", "VCH51", "AP08", "UVC86", "UVC86 E2",
"MeetingEye 500", "CTP25", "MSpeaker Pro", "CM50"):
v = result.get(k)
print(" %-16s in=%-22s out=%s" % (k, ",".join(v["in"]) if v else "нет данных",
",".join(v["out"]) if v else ""))
return 0
if __name__ == "__main__":
sys.exit(main())
+82
View File
@@ -57,6 +57,7 @@ class Data:
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 []}
@@ -75,8 +76,11 @@ class Data:
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"])
@@ -237,6 +241,81 @@ class Data:
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, лимиты, питание."""
@@ -498,6 +577,9 @@ class H(BaseHTTPRequestHandler):
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", []):
+54 -24
View File
@@ -216,34 +216,64 @@ async function capacity(){
${c.notes.length?`<div class="muted" style="margin-top:6px">${c.notes.join('<br>')}</div>`:''}
${c.missing_power.length?`<div class="box">нет данных о питании: ${c.missing_power.join(', ')}</div>`:''}`;
}
function scheme(){
const hk=$('#host').value, name=HOSTS.find(h=>h.key===hk)?.name||hk;
const nodes=[{model:name,role:'Хост',qty:1,central:true,ins:['LAN'],outs:['HDMI','USB','VCH']}];
Object.keys(SEL).forEach(k=>nodes.push({model:k,role:SEL[k].role,qty:SEL[k].qty,ins:['LAN'],
outs:[/амер|исплей/i.test(SEL[k].role)?'HDMI':/ронштейн/i.test(SEL[k].role)?'—':'USB']}));
draw({nodes});
async function scheme(){
const hk=$('#host').value, host=HOSTS.find(h=>h.key===hk)?.name||hk;
const ks=Object.keys(SEL);
const q=ks.map(k=>'item='+encodeURIComponent(k)).join('&');
const lp=await J(`/api/links?host=${hk}&${q}`);
renderLinks(lp);
$('#schemecard').classList.remove('hidden');
drawLinks(lp, host);
}
const COLOR={HDMI:'#2f81f7',USB:'#3fb950',VCH:'#a371f7',LAN:'#d29922','—':'#8b949e'};
function draw(sc){
function renderLinks(lp){
const ok=lp.links.filter(l=>l.ok).length, bad=lp.links.filter(l=>!l.ok);
let html=`<div class="kv" style="margin-bottom:8px">
<div>порты хоста (вход)</div><div><b>${(lp.host_ports.in||[]).join(', ')||'—'}</b></div>
<div>порты хоста (выход)</div><div><b>${(lp.host_ports.out||[]).join(', ')||'—'}</b></div>
<div>источник портов</div><div><b>${lp.host_ports.source==='verified'?'даташит':lp.host_ports.source==='auto'?'извлечено':'по роли'}</b></div>
</div>
<div class="box ${ok===lp.links.length?'ok':''}">
связей собрано: <b>${ok}</b> из ${lp.links.length}
${bad.length?`<br>✗ ${bad.map(l=>l.device+': '+(l.reason||'нет пары')).join('<br>✗ ')}`:''}
</div>`;
$('#schemecard').querySelector('h3').innerHTML='Link View — связи по разъёмам';
let extra=document.getElementById('linkinfo');
if(!extra){extra=document.createElement('div');extra.id='linkinfo';$('#schemecard').appendChild(extra);}
extra.innerHTML=html;
}
const COLOR={HDMI:'#2f81f7',USB:'#3fb950','USB-C':'#3fb950',VCH:'#a371f7',LAN:'#d29922','3.5mm':'#8b949e',DP:'#a371f7',PHOENIX:'#8b949e','—':'#484f58'};
function drawLinks(lp, hostname){
const svg=$('#svg');svg.innerHTML='';
const c=sc.nodes.find(n=>n.central)||sc.nodes[0], others=sc.nodes.filter(n=>n!==c);
const W=960,H=460,cx=W/2,cy=H/2,bw=170,bh=80;
const cx=480,cy=230,bw=180,bh=90;
const good=lp.links.filter(l=>l.ok), bad=lp.links.filter(l=>!l.ok);
const all=lp.links;
let s='';
others.forEach((n,i)=>{const a=(2*Math.PI*i)/Math.max(others.length,1)-Math.PI/2;
const x=cx+320*Math.cos(a),y=cy+160*Math.sin(a);
s+=`<path d="M ${cx+bw/2} ${cy} C ${cx+110} ${cy}, ${x-130} ${y}, ${x-bw/2} ${y}" fill="none" stroke="${COLOR[(n.outs||['—'])[0]]||'#8b949e'}" stroke-width="2" opacity=".85"/>`;});
others.forEach((n,i)=>{const a=(2*Math.PI*i)/Math.max(others.length,1)-Math.PI/2;
const x=cx+320*Math.cos(a),y=cy+160*Math.sin(a);s+=box(n,x-bw/2,y-36,bw,72);});
s+=box(c,cx-bw/2,cy-bh/2,bw,bh,true);svg.innerHTML=s;
}
function box(n,x,y,w,h,central){
let s=`<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="10" fill="${central?'#132239':'#161b22'}" stroke="${central?'#2f81f7':'#30363d'}" stroke-width="${central?2:1.2}"/>`;
s+=`<text x="${x+11}" y="${y+19}" fill="#e6edf3" font-size="12" font-weight="600">${esc(n.model).slice(0,23)}</text>`;
s+=`<text x="${x+11}" y="${y+33}" fill="#8b949e" font-size="10">${esc(n.role)}${n.qty>1?' ×'+n.qty:''}</text>`;
let a=y+48;(n.ins||[]).forEach(p=>{s+=`<circle cx="${x}" cy="${a}" r="4" fill="${COLOR[p]||'#8b949e'}"/><text x="${x+9}" y="${a+3.5}" fill="#8b949e" font-size="9">in ${esc(p)}</text>`;a+=12;});
let b=y+48;(n.outs||[]).forEach(p=>{s+=`<circle cx="${x+w}" cy="${b}" r="4" fill="${COLOR[p]||'#8b949e'}"/><text x="${x+w-9}" y="${b+3.5}" fill="#8b949e" font-size="9" text-anchor="end">out ${esc(p)}</text>`;b+=12;});
return s;
// хост
s+=`<rect x="${cx-bw/2}" y="${cy-bh/2}" width="${bw}" height="${bh}" rx="10" fill="#132239" stroke="#2f81f7" stroke-width="2"/>`;
s+=`<text x="${cx-bw/2+12}" y="${cy-bh/2+20}" fill="#e6edf3" font-size="12.5" font-weight="600">${esc(hostname).slice(0,24)}</text>`;
s+=`<text x="${cx-bw/2+12}" y="${cy-bh/2+34}" fill="#8b949e" font-size="10">хост · ${lp.host_ports.source}</text>`;
// порты хоста
(lp.host_ports.in||[]).slice(0,4).forEach((p,i)=>{
const y=cy-bh/2+52+i*12;
s+=`<circle cx="${cx-bw/2}" cy="${y}" r="4" fill="${COLOR[p]||'#8b949e'}"/><text x="${cx-bw/2+9}" y="${y+3.5}" fill="#8b949e" font-size="9">in ${esc(p)}</text>`;
});
(lp.host_ports.out||[]).slice(0,4).forEach((p,i)=>{
const y=cy-bh/2+52+i*12;
s+=`<circle cx="${cx+bw/2}" cy="${y}" r="4" fill="${COLOR[p]||'#8b949e'}"/><text x="${cx+bw/2-9}" y="${y+3.5}" fill="#8b949e" font-size="9" text-anchor="end">out ${esc(p)}</text>`;
});
// аксессуары
all.forEach((l,i)=>{
const a=(2*Math.PI*i)/Math.max(all.length,1)-Math.PI/2;
const x=cx+300*Math.cos(a), y=cy+150*Math.sin(a);
const col=l.ok?(COLOR[l.from_port]||'#3fb950'):'#f85149';
const dash=l.ok?'':'stroke-dasharray="5 4"';
s+=`<path d="M ${cx} ${cy} L ${x} ${y}" stroke="${col}" stroke-width="2" ${dash} opacity=".8" fill="none"/>`;
s+=`<rect x="${x-78}" y="${y-26}" width="156" height="52" rx="9" fill="#161b22" stroke="${col}" stroke-width="1.3"/>`;
s+=`<text x="${x}" y="${y-7}" text-anchor="middle" fill="#e6edf3" font-size="11.5" font-weight="600">${esc(l.device).slice(0,22)}</text>`;
s+=`<text x="${x}" y="${y+8}" text-anchor="middle" fill="#8b949e" font-size="9.5">${l.ok?esc(l.from_port)+' → '+esc(l.to_port):'нет пары'}</text>`;
s+=`<text x="${x}" y="${y+19}" text-anchor="middle" fill="#8b949e" font-size="9">${l.source==='verified'?'даташит':l.source==='auto'?'извлечено':'по роли'}</text>`;
});
svg.innerHTML=s;
}
function esc(s){return String(s).replace(/[<>&]/g,c=>({'<':'&lt;','>':'&gt;','&':'&amp;'}[c]))}
boot();