[WORK] Эталон схемы владельца + PoE + питание: сохранена его ручная схема (12 узлов, 14 связей) с 220В и зарядкой; добавлены роли power/charger, устройства «Розетка 220 В» и «Зарядка»; poe_check считает бюджет (24 из 90 Вт); авто-раскладка по ярусам вместо столбика. Исправлено: WL в PHYSICAL/SIGNAL_LINK, мост ПК срабатывал на микрофонах
This commit is contained in:
1 parent
4a0aefe4e3
commit
17850f2c19
3 files changed
+522
-302
No files matched your search
@@ -0,0 +1,102 @@
|
||||
# Схема проекта: эталон владельца + PoE + питание (12.11.2026)
|
||||
|
||||
## Эталонная схема (нарисована владельцем)
|
||||
|
||||
Владелец нарисовал правильную схему вручную. Она сохранена как модель проекта:
|
||||
|
||||
`/opt/work-hub/compat/layouts/roomcaste2.model.json` — 12 узлов, 14 связей.
|
||||
|
||||
```
|
||||
┌── RCH40 E2 (PoE коммутатор) ──┐
|
||||
│ LAN VCH(RJ45)/PoE │ LAN
|
||||
▼ ▼ ▼
|
||||
Roomcast E2 UVC86 ПК (BYOD) ◄─USB─ WPP30
|
||||
│ │ │
|
||||
HDMI VCH(RJ45) Wi-Fi
|
||||
▼ ▼ ▼
|
||||
Проектор MSpeaker pro Roomcast E2
|
||||
▲
|
||||
220 В UVC86 ▲ ▲ ▲ Wi-Fi
|
||||
│ │ │ └── VCM36-W
|
||||
Розетка ──220──► Зарядка ──USB──► VCM36-W
|
||||
▲
|
||||
220 В
|
||||
│
|
||||
Roomcast E2
|
||||
```
|
||||
|
||||
Ключевое, чего не было в движке:
|
||||
1. **Питание 220 В** — отдельная цепочка (розетка → терминал, проектор, зарядка).
|
||||
2. **Зарядка микрофонов** — крэдл, питание, а не сигнал.
|
||||
3. **RCH40 как PoE-центр** — от него питание и сеть на камеру и ПК.
|
||||
4. **VCH у камеры — это RJ45**, а не отдельный разъём.
|
||||
|
||||
## Что реализовано
|
||||
|
||||
### 1. Розетка и зарядка в модели
|
||||
|
||||
Добавлены роли `power` и `charger`, устройства «Розетка 220 В» и
|
||||
«Зарядка (крэдл)», связь `220 В` (`("220","220")` в LINKABLE и PHYSICAL).
|
||||
|
||||
### 2. PoE-бюджет
|
||||
|
||||
`poe_check(items)`:
|
||||
|
||||
```
|
||||
PoE: нужно 24 Вт из 90 Вт (портов PoE: 4)
|
||||
нет данных о потреблении: UVC86, VCM36-W, WPP30
|
||||
```
|
||||
|
||||
Считает бюджет коммутаторов (RCH40 — 90 Вт, 4 порта) и потребление
|
||||
устройств из каталога. Если данных о мощности нет — честно перечисляет.
|
||||
|
||||
### 3. Авто-раскладка по ярусам
|
||||
|
||||
`/canvas/model?...&fresh=1` строит схему не в столбик, а по смыслу:
|
||||
|
||||
| Ярус | Что |
|
||||
|---|---|
|
||||
| y=60 | коммутаторы (RCH40) |
|
||||
| y=170 | камера, спикер, презентация |
|
||||
| y=300–380 | ПК справа, дисплеи слева |
|
||||
| y=520 | терминал (центр) |
|
||||
| y=640+ | питание (зарядка, розетка) |
|
||||
|
||||
Проверка:
|
||||
|
||||
```
|
||||
Roomcast E2 x=700 y=520 (терминал)
|
||||
RCH40 E2 x=420 y=60 (коммутатор)
|
||||
UVC86 x=140 y=170 (камера)
|
||||
MSpeaker Pro x=420 y=170
|
||||
WPP30 x=700 y=170
|
||||
Проектор x=120 y=380
|
||||
ПК (BYOD) x=980 y=300
|
||||
VCM36-W ×3 x=200 y=640
|
||||
```
|
||||
|
||||
### 4. Исправления по ходу
|
||||
|
||||
| Проблема | Причина | Исправление |
|
||||
|---|---|---|
|
||||
| WPP30 «разъёмы несовместимы WL/WL» | WL не было в PHYSICAL/SIGNAL_LINK | добавлено |
|
||||
| ПК без WPP30 «нет порта» | правило моста срабатывало на микрофоны (у них WL) | мост = WL-выход **и** USB-вход |
|
||||
| Свитчи не в каталоге | были только в `infrastructure.yaml` | добавлены RCH40/RCH80/RCH240 |
|
||||
|
||||
## Состояние схемы
|
||||
|
||||
```
|
||||
blockers: 0 · ready: True
|
||||
PoE: 24 из 90 Вт
|
||||
батарея: VCM36-W 12 ч — хватит (8 ч)
|
||||
```
|
||||
|
||||
## Что осталось (следующий шаг)
|
||||
|
||||
1. **Данные о потреблении** — UVC86, VCM36-W, WPP30 без мощности,
|
||||
поэтому PoE-бюджет неполный.
|
||||
2. **Автогенерация по практикам Yealink** — нужен слой «правил взаимодействия»
|
||||
(что с чем соединяется и почему), извлечённый LLM из документации,
|
||||
поверх матрицы совместимости.
|
||||
3. **Авто-раскладка** пока простая (ярусы), не учитывает минимизацию
|
||||
пересечений линий.
|
||||
@@ -40,6 +40,8 @@ class Core:
|
||||
"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"]},
|
||||
@@ -69,6 +71,7 @@ class Core:
|
||||
("3.5mm", "3.5mm"): "аналоговый звук",
|
||||
("DP", "DP"): "видео",
|
||||
("WL", "WL"): "беспроводно",
|
||||
("220", "220"): "питание 220В",
|
||||
("RJ-9", "RJ-9"): "телефон",
|
||||
}
|
||||
|
||||
@@ -92,6 +95,8 @@ class Core:
|
||||
{"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"},
|
||||
@@ -193,11 +198,14 @@ class Core:
|
||||
"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 = {
|
||||
@@ -206,6 +214,7 @@ class Core:
|
||||
("PHOENIX", "PHOENIX"),
|
||||
# допустимые переходники
|
||||
("USB", "USB-C"), ("USB-C", "USB"), ("USB-C", "DP"), ("DP", "USB-C"),
|
||||
("WL", "WL"), ("220", "220"),
|
||||
}
|
||||
|
||||
def vendor_of(self, name):
|
||||
@@ -361,6 +370,12 @@ class Core:
|
||||
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"
|
||||
@@ -374,6 +389,44 @@ class Core:
|
||||
"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):
|
||||
"""Хватит ли заряда на совещание заданной длительности."""
|
||||
@@ -808,7 +861,10 @@ class Core:
|
||||
# кабелем в терминал нельзя, там HDMI только выход.
|
||||
if role_dev == "pc" and slot:
|
||||
for m2, _q2 in items:
|
||||
if "WL" in self.ports(m2)[1]:
|
||||
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:"):
|
||||
|
||||
+363
-301
@@ -1,301 +1,363 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ручной редактор схем Комбайна (Cytoscape.js, полностью локально).
|
||||
|
||||
Возможности:
|
||||
* добавить устройство из каталога (поиск по названию) или произвольный блок;
|
||||
* соединить два блока кабелем (режим «кабель»);
|
||||
* переименовать блок/кабель, удалить выбранное;
|
||||
* двигать, панорамировать, масштабировать;
|
||||
* сохранить схему в проект, загрузить, экспорт PNG.
|
||||
|
||||
Данные: /opt/work-hub/compat/layouts/<хост>.model.json
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
sys.path.insert(0, "/root/buryan-infra/ops/work/web")
|
||||
from svc_base import serve # noqa: E402
|
||||
import combine_core as cc # noqa: E402
|
||||
|
||||
C = cc.Core()
|
||||
BASE = "/opt/work-hub/compat"
|
||||
LAY = os.path.join(BASE, "layouts")
|
||||
STATIC = "/root/buryan-infra/ops/work/web/static"
|
||||
os.makedirs(LAY, exist_ok=True)
|
||||
|
||||
|
||||
def items_of(q):
|
||||
out = []
|
||||
for raw in (q.get("item") or []):
|
||||
if ":" in raw:
|
||||
m, n = raw.rsplit(":", 1)
|
||||
try:
|
||||
out.append([m, int(n)])
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
out.append([raw, 1])
|
||||
return out
|
||||
|
||||
|
||||
def model_path(hk):
|
||||
return os.path.join(LAY, hk + ".model.json")
|
||||
|
||||
|
||||
def auto_model(q):
|
||||
"""Схема из port_plan: вершины + рёбра."""
|
||||
hk = cc.norm((q.get("host") or [""])[0])
|
||||
if hk not in C.devices:
|
||||
return {"error": "хост не найден"}
|
||||
plan = C.port_plan(hk, items_of(q))
|
||||
nodes = [{"id": "host", "label": plan["host"], "role": "codec", "x": 420, "y": 40}]
|
||||
edges = []
|
||||
y = 180
|
||||
for i, r in enumerate(plan["rows"]):
|
||||
nid = "d%d" % i
|
||||
label = r["device"] + (" ×%s" % r["qty"] if r["qty"] > 1 else "")
|
||||
nodes.append({"id": nid, "label": label,
|
||||
"role": (C.devices.get(cc.norm(r["device"]), {}) or {}).get("role") or "",
|
||||
"ok": bool(r["ok"]), "x": 420, "y": y})
|
||||
port = r.get("host_port") or ""
|
||||
port = port[4:] if str(port).startswith("out:") else port
|
||||
edges.append({"source": "host", "target": nid,
|
||||
"label": "%s%s" % (port or "?",
|
||||
" → " + str(r["needs_port"]) if r.get("needs_port") else "")})
|
||||
y += 110
|
||||
return {"host": plan["host"], "hk": hk, "nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
def model(q, body):
|
||||
hk = cc.norm((q.get("host") or [""])[0])
|
||||
try:
|
||||
d = json.load(open(model_path(hk), encoding="utf-8"))
|
||||
d["saved"] = True
|
||||
return d
|
||||
except Exception:
|
||||
pass
|
||||
m = auto_model(q)
|
||||
m["saved"] = False
|
||||
return m
|
||||
|
||||
|
||||
def save(q, body):
|
||||
body = body or {}
|
||||
host = body.get("host") or ""
|
||||
if not host:
|
||||
return {"error": "нужен host"}
|
||||
hk = cc.norm(host)
|
||||
d = {"host": host, "nodes": body.get("nodes") or [],
|
||||
"edges": body.get("edges") or []}
|
||||
json.dump(d, open(model_path(hk), "w", encoding="utf-8"),
|
||||
ensure_ascii=False, indent=1)
|
||||
return {"ok": True, "saved": model_path(hk),
|
||||
"nodes": len(d["nodes"]), "edges": len(d["edges"])}
|
||||
|
||||
|
||||
def devices(q, body):
|
||||
out = []
|
||||
for k, v in C.devices.items():
|
||||
out.append({"key": k, "name": v.get("name"), "role": v.get("role")})
|
||||
return {"devices": sorted(out, key=lambda x: (x["name"] or "").lower())}
|
||||
|
||||
|
||||
def static(q, body, path=""):
|
||||
name = (path or "").split("?")[0].lstrip("/")
|
||||
if not name or "/" in name or ".." in name:
|
||||
return {"error": "not found"}
|
||||
full = os.path.join(STATIC, name)
|
||||
if not os.path.isfile(full):
|
||||
return {"error": "not found", "file": name}
|
||||
ctype = {"js": "application/javascript", "css": "text/css",
|
||||
"png": "image/png", "svg": "image/svg+xml"}.get(
|
||||
name.rsplit(".", 1)[-1], "application/octet-stream")
|
||||
return {"__file__": open(full, "rb").read(), "filename": name,
|
||||
"content_type": ctype}
|
||||
|
||||
|
||||
PAGE = r"""<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||||
<title>Схема — ручной редактор</title>
|
||||
<style>
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:#0a0e13;color:#e6edf3;font-family:Segoe UI,system-ui,sans-serif;
|
||||
display:flex;flex-direction:column;height:100vh}
|
||||
#top{display:flex;gap:8px;align-items:center;padding:8px 12px;background:#0d1117;
|
||||
border-bottom:1px solid #233040;flex-wrap:wrap;font-size:13px}
|
||||
#main{flex:1;display:flex;min-height:0}
|
||||
#side{width:260px;background:#0d1117;border-right:1px solid #233040;display:flex;
|
||||
flex-direction:column;min-height:0}
|
||||
#side h4{margin:10px 12px 6px;font-size:12px;color:#8b9cb0;text-transform:uppercase}
|
||||
#search{margin:0 12px 8px;padding:6px 8px;background:#0a0e13;border:1px solid #233040;
|
||||
color:#e6edf3;border-radius:6px;font-size:13px}
|
||||
#list{overflow:auto;flex:1;padding:0 8px 12px}
|
||||
.item{padding:6px 8px;border-radius:6px;cursor:pointer;font-size:12.5px;
|
||||
border:1px solid transparent}
|
||||
.item:hover{background:#161b22;border-color:#233040}
|
||||
.item .r{color:#8b9cb0;font-size:11px}
|
||||
#cy{flex:1;min-width:0}
|
||||
button{background:#21262d;color:#e6edf3;border:1px solid #30363d;border-radius:6px;
|
||||
padding:6px 10px;cursor:pointer;font-size:13px}
|
||||
button.pri{background:#238636;border-color:#2ea043}
|
||||
button.on{background:#1f6feb;border-color:#388bfd}
|
||||
input[type=password]{background:#0a0e13;border:1px solid #30363d;color:#e6edf3;
|
||||
border-radius:6px;padding:5px 8px;font-size:13px}
|
||||
#st{color:#8b9cb0;margin-left:auto;font-size:12px}
|
||||
</style></head><body>
|
||||
<div id="top">
|
||||
<b>Схема: ручной режим</b><span id="host"></span>
|
||||
<button id="bAdd" onclick="addCustom()">+ Блок</button>
|
||||
<button id="bCable" onclick="toggleCable()">+ Кабель</button>
|
||||
<button onclick="delSel()">Удалить</button>
|
||||
<button onclick="autoLayout()">Авто-раскладка</button>
|
||||
<button class="pri" onclick="saveAll()">Сохранить</button>
|
||||
<button onclick="loadAll()">Загрузить</button>
|
||||
<button onclick="exportPng()">PNG</button>
|
||||
<input id="tok" type="password" placeholder="X-Token" size="14">
|
||||
<span id="st"></span>
|
||||
</div>
|
||||
<div id="main">
|
||||
<div id="side">
|
||||
<h4>Устройства каталога</h4>
|
||||
<input id="search" placeholder="поиск…" oninput="renderList()">
|
||||
<div id="list"></div>
|
||||
</div>
|
||||
<div id="cy"></div>
|
||||
</div>
|
||||
<script src="/static/cytoscape.min.js"></script>
|
||||
<script>
|
||||
const q=new URLSearchParams(location.search);
|
||||
const host=q.get('host')||'';
|
||||
document.getElementById('host').textContent=host;
|
||||
let cy, DEV=[], cable=false, pending=null, dirty=false;
|
||||
|
||||
function st(t){document.getElementById('st').textContent=t;}
|
||||
|
||||
fetch('/canvas/devices').then(r=>r.json()).then(d=>{DEV=d.devices||[];renderList();});
|
||||
function renderList(){
|
||||
const f=(document.getElementById('search').value||'').toLowerCase();
|
||||
const el=document.getElementById('list');
|
||||
el.innerHTML=DEV.filter(d=>!f||(d.name||'').toLowerCase().includes(f)).slice(0,400)
|
||||
.map(d=>`<div class="item" onclick="addDevice('${esc(d.name)}','${esc(d.role||'')}')">
|
||||
${esc(d.name)}<div class="r">${esc(d.role||'')}</div></div>`).join('')
|
||||
|| '<div class="item">ничего не найдено</div>';
|
||||
}
|
||||
function esc(s){return String(s).replace(/[<>&"']/g,c=>({'<':'<','>':'>','&':'&','"':'"',"'":'''}[c]));}
|
||||
|
||||
function initCy(){
|
||||
cy=cytoscape({container:document.getElementById('cy'),
|
||||
style:[
|
||||
{selector:'node',style:{'background-color':'#161b22','border-width':2,
|
||||
'border-color':'#3fb950','label':'data(label)','color':'#e6edf3',
|
||||
'font-size':11,'text-wrap':'wrap','text-max-width':140,
|
||||
'width':150,'height':56,'shape':'round-rectangle','text-valign':'center'}},
|
||||
{selector:'node[role="codec"]',style:{'border-color':'#2f81f7','background-color':'#132239'}},
|
||||
{selector:'edge',style:{'width':1.6,'line-color':'#2f81f7','target-arrow-color':'#2f81f7',
|
||||
'target-arrow-shape':'triangle','curve-style':'bezier','label':'data(label)',
|
||||
'font-size':9,'color':'#8b9cb0','text-rotation':'autorotate'}},
|
||||
{selector:':selected',style:{'border-color':'#f0883e','line-color':'#f0883e',
|
||||
'target-arrow-color':'#f0883e'}}
|
||||
]});
|
||||
cy.on('dragfree','node',()=>{dirty=true;});
|
||||
cy.on('tap','node',e=>{
|
||||
if(!cable)return;
|
||||
const n=e.target;
|
||||
if(!pending){pending=n.id();n.select();st('выберите второй блок');return;}
|
||||
if(pending!==n.id()){
|
||||
cy.add({group:'edges',data:{id:'e'+Date.now(),source:pending,target:n.id(),label:'кабель'}});
|
||||
dirty=true;
|
||||
}
|
||||
cy.$(':selected').unselect();pending=null;cable=false;
|
||||
document.getElementById('bCable').classList.remove('on');
|
||||
st('кабель добавлен');
|
||||
});
|
||||
cy.on('dbltap','node',e=>{
|
||||
const n=e.target, v=prompt('Название блока:',n.data('label'));
|
||||
if(v!==null){n.data('label',v);dirty=true;}
|
||||
});
|
||||
cy.on('dbltap','edge',e=>{
|
||||
const ed=e.target, v=prompt('Подпись кабеля:',ed.data('label'));
|
||||
if(v!==null){ed.data('label',v);dirty=true;}
|
||||
});
|
||||
}
|
||||
function addDevice(name,role){addNode(name,role);}
|
||||
function addCustom(){
|
||||
const v=prompt('Название блока:'); if(!v)return; addNode(v,'');
|
||||
}
|
||||
function addNode(label,role){
|
||||
const n=cy.nodes().length;
|
||||
cy.add({group:'nodes',data:{id:'n'+Date.now(),label:label,role:role},
|
||||
position:{x:120+(n%5)*180,y:80+Math.floor(n/5)*120}});
|
||||
dirty=true;st('добавлено: '+label);
|
||||
}
|
||||
function toggleCable(){
|
||||
cable=!cable;pending=null;cy.$(':selected').unselect();
|
||||
document.getElementById('bCable').classList.toggle('on',cable);
|
||||
st(cable?'режим кабеля: ткните два блока':'обычный режим');
|
||||
}
|
||||
function delSel(){
|
||||
const s=cy.$(':selected'); if(!s.length){st('ничего не выбрано');return;}
|
||||
s.remove(); dirty=true; st('удалено: '+s.length);
|
||||
}
|
||||
function modelFromCy(){
|
||||
return {host:host,
|
||||
nodes:cy.nodes().map(n=>({id:n.id(),label:n.data('label'),role:n.data('role')||'',
|
||||
x:Math.round(n.position('x')),y:Math.round(n.position('y'))})),
|
||||
edges:cy.edges().map(e=>({source:e.data('source'),target:e.data('target'),
|
||||
label:e.data('label')||''}))};
|
||||
}
|
||||
function loadModel(m){
|
||||
cy.elements().remove();
|
||||
const els=[];
|
||||
(m.nodes||[]).forEach(n=>els.push({group:'nodes',data:n,position:{x:n.x||100,y:n.y||100}}));
|
||||
(m.edges||[]).forEach(e=>els.push({group:'edges',
|
||||
data:{id:'e'+Math.random().toString(36).slice(2),source:e.source,target:e.target,label:e.label||''}}));
|
||||
cy.add(els); cy.fit(null,40); dirty=false;
|
||||
st(m.saved?'сохранённая схема':'авто-схема из конструктора');
|
||||
}
|
||||
function loadAll(){
|
||||
fetch('/canvas/model?'+q.toString()).then(r=>r.json()).then(d=>{
|
||||
if(d.error){st(d.error);return;}
|
||||
loadModel(d);
|
||||
});
|
||||
}
|
||||
async function saveAll(){
|
||||
const tok=document.getElementById('tok').value;
|
||||
if(!tok){st('нужен X-Token');return;}
|
||||
const r=await fetch('/canvas/save',{method:'POST',
|
||||
headers:{'Content-Type':'application/json','X-Token':tok},
|
||||
body:JSON.stringify(modelFromCy())});
|
||||
const d=await r.json();
|
||||
st(d.ok?('сохранено: узлов '+d.nodes+', связей '+d.edges):(d.error||'ошибка'));
|
||||
}
|
||||
function autoLayout(){
|
||||
const nodes=cy.nodes();
|
||||
nodes.forEach((n,i)=>{n.position({x:140+(i%4)*220,y:100+Math.floor(i/4)*140});});
|
||||
cy.fit(null,40); dirty=true; st('авто-раскладка');
|
||||
}
|
||||
function exportPng(){
|
||||
const b64=cy.png({full:true,scale:2,bg:'#0a0e13'});
|
||||
const a=document.createElement('a');a.href=b64;
|
||||
a.download=(host||'schema')+'.png';a.click();
|
||||
}
|
||||
initCy(); loadAll();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
def canvas(q, body):
|
||||
return {"__html": PAGE}
|
||||
|
||||
|
||||
def cytoscape_js(q, body):
|
||||
return static(q, body, 'cytoscape.min.js')
|
||||
|
||||
serve({
|
||||
"/canvas": canvas,
|
||||
"/canvas/model": model,
|
||||
"/canvas/save": save,
|
||||
"/canvas/devices": devices,
|
||||
"/static/cytoscape.min.js": cytoscape_js,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8107, "canvas",
|
||||
before=C.reload_if_changed)
|
||||
#!/usr/bin/env python3
|
||||
"""Ручной редактор схем Комбайна (Cytoscape.js, полностью локально).
|
||||
|
||||
Возможности:
|
||||
* добавить устройство из каталога (поиск по названию) или произвольный блок;
|
||||
* соединить два блока кабелем (режим «кабель»);
|
||||
* переименовать блок/кабель, удалить выбранное;
|
||||
* двигать, панорамировать, масштабировать;
|
||||
* сохранить схему в проект, загрузить, экспорт PNG.
|
||||
|
||||
Данные: /opt/work-hub/compat/layouts/<хост>.model.json
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
sys.path.insert(0, "/root/buryan-infra/ops/work/web")
|
||||
from svc_base import serve # noqa: E402
|
||||
import combine_core as cc # noqa: E402
|
||||
|
||||
C = cc.Core()
|
||||
BASE = "/opt/work-hub/compat"
|
||||
LAY = os.path.join(BASE, "layouts")
|
||||
STATIC = "/root/buryan-infra/ops/work/web/static"
|
||||
os.makedirs(LAY, exist_ok=True)
|
||||
|
||||
|
||||
def items_of(q):
|
||||
out = []
|
||||
for raw in (q.get("item") or []):
|
||||
if ":" in raw:
|
||||
m, n = raw.rsplit(":", 1)
|
||||
try:
|
||||
out.append([m, int(n)])
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
out.append([raw, 1])
|
||||
return out
|
||||
|
||||
|
||||
def model_path(hk):
|
||||
return os.path.join(LAY, hk + ".model.json")
|
||||
|
||||
|
||||
def auto_model(q):
|
||||
"""Схема из port_plan + раскладка по ярусам (как на эталонном рисунке).
|
||||
|
||||
Ярусы: коммутаторы сверху, камера/презентация выше центра, терминал
|
||||
в центре, дисплеи слева, ПК справа, питание внизу.
|
||||
"""
|
||||
hk = cc.norm((q.get("host") or [""])[0])
|
||||
if hk not in C.devices:
|
||||
return {"error": "хост не найден"}
|
||||
plan = C.port_plan(hk, items_of(q))
|
||||
rows = plan["rows"]
|
||||
|
||||
def role_of(name):
|
||||
return (C.devices.get(cc.norm(name)) or {}).get("role")
|
||||
|
||||
tiers = {
|
||||
"switch": [], "hub": [], "terminal": [], "display": [],
|
||||
"pc": [], "power": [], "other": [],
|
||||
}
|
||||
for r in rows:
|
||||
role = role_of(r["device"])
|
||||
info = C.iface_map.get(cc.norm(r["device"])) or {}
|
||||
if info.get("poe_budget_w"):
|
||||
tiers["switch"].append(r)
|
||||
elif role in ("power", "charger"):
|
||||
tiers["power"].append(r)
|
||||
elif role == "display":
|
||||
tiers["display"].append(r)
|
||||
elif role == "pc":
|
||||
tiers["pc"].append(r)
|
||||
elif role in ("camera", "sharing_or_hub", "speaker"):
|
||||
tiers["hub"].append(r)
|
||||
else:
|
||||
tiers["other"].append(r)
|
||||
|
||||
nodes, edges = [], []
|
||||
W = 1400
|
||||
|
||||
# терминал — центр
|
||||
nodes.append({"id": "host", "label": plan["host"], "role": "codec",
|
||||
"x": W // 2, "y": 520})
|
||||
|
||||
pos = {}
|
||||
|
||||
def place(group, y, per_row=4, start_x=200, step=230):
|
||||
for i, r in enumerate(group):
|
||||
col = i % per_row
|
||||
row = i // per_row
|
||||
rid = "d%d" % rows.index(r)
|
||||
pos[id(r)] = rid
|
||||
nodes.append({"id": rid,
|
||||
"label": r["device"] + (" ×%s" % r["qty"] if r["qty"] > 1 else ""),
|
||||
"role": role_of(r["device"]) or "",
|
||||
"ok": bool(r["ok"]),
|
||||
"x": start_x + col * step, "y": y + row * 90})
|
||||
port = r.get("host_port") or ""
|
||||
port = port[4:] if str(port).startswith("out:") else port
|
||||
label = "%s%s" % (port or "?",
|
||||
" → " + str(r["needs_port"]) if r.get("needs_port") else "")
|
||||
if r.get("via"):
|
||||
# цепочка: линия от промежуточного устройства
|
||||
via_id = None
|
||||
for r2 in rows:
|
||||
if r2["device"] == r["via"]:
|
||||
via_id = pos.get(id(r2))
|
||||
break
|
||||
if via_id:
|
||||
edges.append({"source": via_id, "target": rid, "label": label})
|
||||
continue
|
||||
edges.append({"source": "host", "target": rid, "label": label})
|
||||
|
||||
place(tiers["switch"], 60, per_row=3, start_x=420, step=300)
|
||||
place(tiers["hub"], 170, per_row=4, start_x=140, step=280)
|
||||
place(tiers["display"], 380, per_row=2, start_x=120, step=260)
|
||||
place(tiers["pc"], 300, per_row=2, start_x=980, step=260)
|
||||
place(tiers["other"], 640, per_row=3, start_x=200, step=300)
|
||||
place(tiers["power"], 760, per_row=3, start_x=360, step=280)
|
||||
|
||||
return {"host": plan["host"], "hk": hk, "nodes": nodes, "edges": edges,
|
||||
"poe": plan.get("free_out"), "chains": plan.get("chains") or []}
|
||||
|
||||
|
||||
def model(q, body):
|
||||
hk = cc.norm((q.get("host") or [""])[0])
|
||||
if q.get("fresh"):
|
||||
m = auto_model(q)
|
||||
m["saved"] = False
|
||||
return m
|
||||
try:
|
||||
d = json.load(open(model_path(hk), encoding="utf-8"))
|
||||
d["saved"] = True
|
||||
return d
|
||||
except Exception:
|
||||
pass
|
||||
m = auto_model(q)
|
||||
m["saved"] = False
|
||||
return m
|
||||
|
||||
|
||||
def save(q, body):
|
||||
body = body or {}
|
||||
host = body.get("host") or ""
|
||||
if not host:
|
||||
return {"error": "нужен host"}
|
||||
hk = cc.norm(host)
|
||||
d = {"host": host, "nodes": body.get("nodes") or [],
|
||||
"edges": body.get("edges") or []}
|
||||
json.dump(d, open(model_path(hk), "w", encoding="utf-8"),
|
||||
ensure_ascii=False, indent=1)
|
||||
return {"ok": True, "saved": model_path(hk),
|
||||
"nodes": len(d["nodes"]), "edges": len(d["edges"])}
|
||||
|
||||
|
||||
def devices(q, body):
|
||||
out = []
|
||||
for k, v in C.devices.items():
|
||||
out.append({"key": k, "name": v.get("name"), "role": v.get("role")})
|
||||
return {"devices": sorted(out, key=lambda x: (x["name"] or "").lower())}
|
||||
|
||||
|
||||
def static(q, body, path=""):
|
||||
name = (path or "").split("?")[0].lstrip("/")
|
||||
if not name or "/" in name or ".." in name:
|
||||
return {"error": "not found"}
|
||||
full = os.path.join(STATIC, name)
|
||||
if not os.path.isfile(full):
|
||||
return {"error": "not found", "file": name}
|
||||
ctype = {"js": "application/javascript", "css": "text/css",
|
||||
"png": "image/png", "svg": "image/svg+xml"}.get(
|
||||
name.rsplit(".", 1)[-1], "application/octet-stream")
|
||||
return {"__file__": open(full, "rb").read(), "filename": name,
|
||||
"content_type": ctype}
|
||||
|
||||
|
||||
PAGE = r"""<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||||
<title>Схема — ручной редактор</title>
|
||||
<style>
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:#0a0e13;color:#e6edf3;font-family:Segoe UI,system-ui,sans-serif;
|
||||
display:flex;flex-direction:column;height:100vh}
|
||||
#top{display:flex;gap:8px;align-items:center;padding:8px 12px;background:#0d1117;
|
||||
border-bottom:1px solid #233040;flex-wrap:wrap;font-size:13px}
|
||||
#main{flex:1;display:flex;min-height:0}
|
||||
#side{width:260px;background:#0d1117;border-right:1px solid #233040;display:flex;
|
||||
flex-direction:column;min-height:0}
|
||||
#side h4{margin:10px 12px 6px;font-size:12px;color:#8b9cb0;text-transform:uppercase}
|
||||
#search{margin:0 12px 8px;padding:6px 8px;background:#0a0e13;border:1px solid #233040;
|
||||
color:#e6edf3;border-radius:6px;font-size:13px}
|
||||
#list{overflow:auto;flex:1;padding:0 8px 12px}
|
||||
.item{padding:6px 8px;border-radius:6px;cursor:pointer;font-size:12.5px;
|
||||
border:1px solid transparent}
|
||||
.item:hover{background:#161b22;border-color:#233040}
|
||||
.item .r{color:#8b9cb0;font-size:11px}
|
||||
#cy{flex:1;min-width:0}
|
||||
button{background:#21262d;color:#e6edf3;border:1px solid #30363d;border-radius:6px;
|
||||
padding:6px 10px;cursor:pointer;font-size:13px}
|
||||
button.pri{background:#238636;border-color:#2ea043}
|
||||
button.on{background:#1f6feb;border-color:#388bfd}
|
||||
input[type=password]{background:#0a0e13;border:1px solid #30363d;color:#e6edf3;
|
||||
border-radius:6px;padding:5px 8px;font-size:13px}
|
||||
#st{color:#8b9cb0;margin-left:auto;font-size:12px}
|
||||
</style></head><body>
|
||||
<div id="top">
|
||||
<b>Схема: ручной режим</b><span id="host"></span>
|
||||
<button id="bAdd" onclick="addCustom()">+ Блок</button>
|
||||
<button id="bCable" onclick="toggleCable()">+ Кабель</button>
|
||||
<button onclick="delSel()">Удалить</button>
|
||||
<button onclick="autoLayout()">Авто-раскладка</button>
|
||||
<button class="pri" onclick="saveAll()">Сохранить</button>
|
||||
<button onclick="loadAll()">Загрузить</button>
|
||||
<button onclick="exportPng()">PNG</button>
|
||||
<input id="tok" type="password" placeholder="X-Token" size="14">
|
||||
<span id="st"></span>
|
||||
</div>
|
||||
<div id="main">
|
||||
<div id="side">
|
||||
<h4>Устройства каталога</h4>
|
||||
<input id="search" placeholder="поиск…" oninput="renderList()">
|
||||
<div id="list"></div>
|
||||
</div>
|
||||
<div id="cy"></div>
|
||||
</div>
|
||||
<script src="/static/cytoscape.min.js"></script>
|
||||
<script>
|
||||
const q=new URLSearchParams(location.search);
|
||||
const host=q.get('host')||'';
|
||||
document.getElementById('host').textContent=host;
|
||||
let cy, DEV=[], cable=false, pending=null, dirty=false;
|
||||
|
||||
function st(t){document.getElementById('st').textContent=t;}
|
||||
|
||||
fetch('/canvas/devices').then(r=>r.json()).then(d=>{DEV=d.devices||[];renderList();});
|
||||
function renderList(){
|
||||
const f=(document.getElementById('search').value||'').toLowerCase();
|
||||
const el=document.getElementById('list');
|
||||
el.innerHTML=DEV.filter(d=>!f||(d.name||'').toLowerCase().includes(f)).slice(0,400)
|
||||
.map(d=>`<div class="item" onclick="addDevice('${esc(d.name)}','${esc(d.role||'')}')">
|
||||
${esc(d.name)}<div class="r">${esc(d.role||'')}</div></div>`).join('')
|
||||
|| '<div class="item">ничего не найдено</div>';
|
||||
}
|
||||
function esc(s){return String(s).replace(/[<>&"']/g,c=>({'<':'<','>':'>','&':'&','"':'"',"'":'''}[c]));}
|
||||
|
||||
function initCy(){
|
||||
cy=cytoscape({container:document.getElementById('cy'),
|
||||
style:[
|
||||
{selector:'node',style:{'background-color':'#161b22','border-width':2,
|
||||
'border-color':'#3fb950','label':'data(label)','color':'#e6edf3',
|
||||
'font-size':11,'text-wrap':'wrap','text-max-width':140,
|
||||
'width':150,'height':56,'shape':'round-rectangle','text-valign':'center'}},
|
||||
{selector:'node[role="codec"]',style:{'border-color':'#2f81f7','background-color':'#132239'}},
|
||||
{selector:'edge',style:{'width':1.6,'line-color':'#2f81f7','target-arrow-color':'#2f81f7',
|
||||
'target-arrow-shape':'triangle','curve-style':'bezier','label':'data(label)',
|
||||
'font-size':9,'color':'#8b9cb0','text-rotation':'autorotate'}},
|
||||
{selector:':selected',style:{'border-color':'#f0883e','line-color':'#f0883e',
|
||||
'target-arrow-color':'#f0883e'}}
|
||||
]});
|
||||
cy.on('dragfree','node',()=>{dirty=true;});
|
||||
cy.on('tap','node',e=>{
|
||||
if(!cable)return;
|
||||
const n=e.target;
|
||||
if(!pending){pending=n.id();n.select();st('выберите второй блок');return;}
|
||||
if(pending!==n.id()){
|
||||
cy.add({group:'edges',data:{id:'e'+Date.now(),source:pending,target:n.id(),label:'кабель'}});
|
||||
dirty=true;
|
||||
}
|
||||
cy.$(':selected').unselect();pending=null;cable=false;
|
||||
document.getElementById('bCable').classList.remove('on');
|
||||
st('кабель добавлен');
|
||||
});
|
||||
cy.on('dbltap','node',e=>{
|
||||
const n=e.target, v=prompt('Название блока:',n.data('label'));
|
||||
if(v!==null){n.data('label',v);dirty=true;}
|
||||
});
|
||||
cy.on('dbltap','edge',e=>{
|
||||
const ed=e.target, v=prompt('Подпись кабеля:',ed.data('label'));
|
||||
if(v!==null){ed.data('label',v);dirty=true;}
|
||||
});
|
||||
}
|
||||
function addDevice(name,role){addNode(name,role);}
|
||||
function addCustom(){
|
||||
const v=prompt('Название блока:'); if(!v)return; addNode(v,'');
|
||||
}
|
||||
function addNode(label,role){
|
||||
const n=cy.nodes().length;
|
||||
cy.add({group:'nodes',data:{id:'n'+Date.now(),label:label,role:role},
|
||||
position:{x:120+(n%5)*180,y:80+Math.floor(n/5)*120}});
|
||||
dirty=true;st('добавлено: '+label);
|
||||
}
|
||||
function toggleCable(){
|
||||
cable=!cable;pending=null;cy.$(':selected').unselect();
|
||||
document.getElementById('bCable').classList.toggle('on',cable);
|
||||
st(cable?'режим кабеля: ткните два блока':'обычный режим');
|
||||
}
|
||||
function delSel(){
|
||||
const s=cy.$(':selected'); if(!s.length){st('ничего не выбрано');return;}
|
||||
s.remove(); dirty=true; st('удалено: '+s.length);
|
||||
}
|
||||
function modelFromCy(){
|
||||
return {host:host,
|
||||
nodes:cy.nodes().map(n=>({id:n.id(),label:n.data('label'),role:n.data('role')||'',
|
||||
x:Math.round(n.position('x')),y:Math.round(n.position('y'))})),
|
||||
edges:cy.edges().map(e=>({source:e.data('source'),target:e.data('target'),
|
||||
label:e.data('label')||''}))};
|
||||
}
|
||||
function loadModel(m){
|
||||
cy.elements().remove();
|
||||
const els=[];
|
||||
(m.nodes||[]).forEach(n=>els.push({group:'nodes',data:n,position:{x:n.x||100,y:n.y||100}}));
|
||||
(m.edges||[]).forEach(e=>els.push({group:'edges',
|
||||
data:{id:'e'+Math.random().toString(36).slice(2),source:e.source,target:e.target,label:e.label||''}}));
|
||||
cy.add(els); cy.fit(null,40); dirty=false;
|
||||
st(m.saved?'сохранённая схема':'авто-схема из конструктора');
|
||||
}
|
||||
function loadAll(){
|
||||
fetch('/canvas/model?'+q.toString()).then(r=>r.json()).then(d=>{
|
||||
if(d.error){st(d.error);return;}
|
||||
loadModel(d);
|
||||
});
|
||||
}
|
||||
async function saveAll(){
|
||||
const tok=document.getElementById('tok').value;
|
||||
if(!tok){st('нужен X-Token');return;}
|
||||
const r=await fetch('/canvas/save',{method:'POST',
|
||||
headers:{'Content-Type':'application/json','X-Token':tok},
|
||||
body:JSON.stringify(modelFromCy())});
|
||||
const d=await r.json();
|
||||
st(d.ok?('сохранено: узлов '+d.nodes+', связей '+d.edges):(d.error||'ошибка'));
|
||||
}
|
||||
function autoLayout(){
|
||||
const nodes=cy.nodes();
|
||||
nodes.forEach((n,i)=>{n.position({x:140+(i%4)*220,y:100+Math.floor(i/4)*140});});
|
||||
cy.fit(null,40); dirty=true; st('авто-раскладка');
|
||||
}
|
||||
function exportPng(){
|
||||
const b64=cy.png({full:true,scale:2,bg:'#0a0e13'});
|
||||
const a=document.createElement('a');a.href=b64;
|
||||
a.download=(host||'schema')+'.png';a.click();
|
||||
}
|
||||
initCy(); loadAll();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
def canvas(q, body):
|
||||
return {"__html": PAGE}
|
||||
|
||||
|
||||
def cytoscape_js(q, body):
|
||||
return static(q, body, 'cytoscape.min.js')
|
||||
|
||||
serve({
|
||||
"/canvas": canvas,
|
||||
"/canvas/model": model,
|
||||
"/canvas/save": save,
|
||||
"/canvas/devices": devices,
|
||||
"/static/cytoscape.min.js": cytoscape_js,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8107, "canvas",
|
||||
before=C.reload_if_changed)
|
||||
Reference in new issue
Block a user