Files
buryan-infra/ops/work/web/services/svc_draw.py
T

295 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Сервис СХЕМА и КАБЕЛИ (8104): interconnect-diagram + кабельный журнал."""
import sys
sys.path.insert(0, "/root/buryan-infra/ops/work/web")
from svc_base import serve # noqa
import combine_core as cc # noqa
C = cc.Core()
COLOR = {"HDMI": "#2f81f7", "USB": "#3fb950", "USB-C": "#3fb950", "VCH": "#a371f7",
"LAN": "#d29922", "3.5mm": "#8b949e", "DP": "#a371f7", "RJ-9": "#8b949e",
"—": "#484f58"}
def _items(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 _esc(s):
return str(s).replace("<", "&lt;").replace(">", "&gt;").replace("&", "&amp;")
def diagram(q, body):
"""SVG-схема: порты хоста слева/справа, устройства вокруг, связи по разъёмам."""
hk = cc.norm((q.get("host") or [""])[0])
if hk not in C.devices:
return {"error": "хост не найден"}
host = C.devices[hk]["name"]
items = _items(q)
plan = C.port_plan(hk, items)
W, H = 1100, 620
cx, cy, bw, bh = 550, 310, 210, 110
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" '
f'width="{W}" height="{H}" style="background:#0a0e13">']
# хост
parts.append(f'<rect x="{cx-bw//2}" y="{cy-bh//2}" width="{bw}" height="{bh}" rx="12" '
f'fill="#132239" stroke="#2f81f7" stroke-width="2"/>')
parts.append(f'<text x="{cx-bw//2+14}" y="{cy-bh//2+24}" fill="#e6edf3" '
f'font-size="14" font-weight="600">{_esc(host)[:26]}</text>')
parts.append(f'<text x="{cx-bw//2+14}" y="{cy-bh//2+40}" fill="#8b949e" '
f'font-size="10">ports: {plan["source"]}</text>')
for i, p in enumerate(plan["host_in"][:5]):
y = cy - bh//2 + 60 + i*14
used = "•" if p in plan["used_in"] else "○"
parts.append(f'<text x="{cx-bw//2+14}" y="{y}" fill="{COLOR.get(p,"#8b949e")}" '
f'font-size="10">in {_esc(p)} {used}</text>')
for i, p in enumerate(plan["host_out"][:5]):
y = cy - bh//2 + 60 + i*14
used = "•" if p in plan["used_out"] else "○"
parts.append(f'<text x="{cx+bw//2-14}" y="{y}" fill="{COLOR.get(p,"#8b949e")}" '
f'font-size="10" text-anchor="end">{used} out {_esc(p)}</text>')
# устройства
rows = [r for r in plan["rows"] if r["device"] not in ("", None)]
n = max(len(rows), 1)
for i, r in enumerate(rows):
a_top = 60
step = (H - 120) / n
y = a_top + step * i + step/2
x = 175 if i % 2 == 0 else 925
col = COLOR.get(r["needs_port"], "#484f58") if r["ok"] else "#f85149"
dash = "" if r["ok"] else ' stroke-dasharray="6 4"'
parts.append(f'<path d="M {cx} {cy} L {x} {y}" stroke="{col}" stroke-width="2" '
f'opacity="0.75"{dash} fill="none"/>')
parts.append(f'<rect x="{x-105}" y="{y-30}" width="210" height="60" rx="10" '
f'fill="#161b22" stroke="{col}" stroke-width="1.4"/>')
parts.append(f'<text x="{x}" y="{y-8}" text-anchor="middle" fill="#e6edf3" '
f'font-size="12" font-weight="600">{_esc(r["device"])[:24]}</text>')
parts.append(f'<text x="{x}" y="{y+8}" text-anchor="middle" fill="#8b949e" '
f'font-size="9.5">{("→ "+_esc(r["host_port"])) if r["ok"] else "нет порта"}'
f'{" ×"+str(r["qty"]) if r["qty"]>1 else ""}</text>')
parts.append(f'<text x="{x}" y="{y+21}" text-anchor="middle" fill="#8b949e" '
f'font-size="9">{_esc(r["needs_port"] or "?")}</text>')
parts.append("</svg>")
return {"host": host, "svg": "".join(parts),
"unresolved": plan["unresolved"],
"free_in": plan["free_in"], "free_out": plan["free_out"]}
def cables(q, body):
return C.cable_schedule((q.get("host") or [""])[0], _items(q))
def rack(q, body):
"""Чертёж стойки (EIA-310: 1U = 44.45 мм)."""
items = _items(q)
U = 44.45
u = 1
rows = []
for r in items:
h = 1
name = r[0]
if any(x in name.lower() for x in ("mcore", "codec", "dsp", "ap08")):
h = 1
rows.append({"device": name, "qty": r[1], "u": h, "start_u": u})
u += h * r[1]
total_u = u + 1
W, px = 420, 70
H = int(total_u * px + 80)
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">',
f'<rect x="0" y="0" width="{W}" height="{H}" fill="#0a0e13"/>',
f'<text x="14" y="24" fill="#e6edf3" font-size="13" font-weight="600">'
f'Стойка: {total_u}U (EIA-310, 1U=44.45 мм)</text>']
for r in rows:
y = 60 + (r["start_u"] - 1) * px
for n in range(r["qty"]):
yy = y + n * r["u"] * px
parts.append(f'<rect x="24" y="{yy}" width="{W-48}" height="{px-4}" rx="4" '
f'fill="#161b22" stroke="#2e4a6b"/>')
parts.append(f'<text x="34" y="{yy+26}" fill="#e6edf3" font-size="12">'
f'{_esc(r["device"])[:38]}</text>')
parts.append(f'<text x="{W-34}" y="{yy+26}" fill="#8b949e" font-size="10" '
f'text-anchor="end">U{r["start_u"]+n}</text>')
parts.append("</svg>")
return {"svg": "".join(parts), "total_u": total_u,
"height_mm": round(total_u * U, 1)}
def ipplan(q, body):
"""IP-план: выдаёт адреса по порядку для сетевых устройств."""
base = (q.get("net") or ["10.10.20."])[0]
start = int((q.get("start") or ["10"])[0])
items = _items(q)
rows, n = [], start
for r in items:
name, qty = r[0], r[1]
ins, outs, src = C.ports(name)
if "LAN" not in (ins + outs):
continue
for _ in range(qty):
rows.append({"device": name, "ip": "%s%d" % (base, n),
"purpose": "управление", "vlan": (q.get("vlan") or ["20"])[0]})
n += 1
return {"base": base, "rows": rows, "count": len(rows)}
def _room(q):
try:
w = float((q.get("w") or ["8"])[0])
l = float((q.get("l") or ["10"])[0])
except ValueError:
w, l = 8.0, 10.0
return max(3.0, min(40.0, w)), max(3.0, min(60.0, l))
def layout(q, body):
"""План комнаты сверху: хост, микрофоны на столе, камера у стены, дисплей."""
w, l = _room(q)
items = _items(q)
scale = 60 # px на метр
W = int(w * scale) + 120
H = int(l * scale) + 120
ox, oy = 60, 60
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">',
f'<rect width="{W}" height="{H}" fill="#0a0e13"/>',
f'<rect x="{ox}" y="{oy}" width="{w*scale}" height="{l*scale}" '
f'fill="#0f1620" stroke="#2e4a6b" stroke-width="2"/>',
f'<text x="{ox}" y="{oy-10}" fill="#8b949e" font-size="11">'
f'{w:.1f} × {l:.1f} м (масштаб 1 м = {scale} px)</text>']
def place(name, role, cx, cy, color, wpx=110, hpx=70):
return (f'<rect x="{cx-wpx//2}" y="{cy-hpx//2}" width="{wpx}" height="{hpx}" rx="8" '
f'fill="#161b22" stroke="{color}" stroke-width="1.6"/>'
f'<text x="{cx}" y="{cy-2}" text-anchor="middle" fill="#e6edf3" '
f'font-size="11" font-weight="600">{_esc(name)[:18]}</text>'
f'<text x="{cx}" y="{cy+14}" text-anchor="middle" fill="#8b949e" '
f'font-size="9">{_esc(role)}</text>')
cx = ox + int(w * scale / 2)
# камера у дальней стены
parts.append(place("камера", "у стены", cx, oy + 45, "#2f81f7"))
# дисплей на стене
parts.append(place("дисплей", "на стене", cx, oy + 15, "#a371f7", 160, 34))
# стол по центру
t_y = oy + int(l * scale * 0.55)
parts.append(f'<rect x="{ox+40}" y="{t_y}" width="{w*scale-80}" height="90" rx="12" '
f'fill="#132239" stroke="#30363d"/>')
parts.append(f'<text x="{ox+50}" y="{t_y+16}" fill="#8b949e" font-size="10">стол</text>')
# микрофоны на столе
mics = [r for r in items if r[0].lower().startswith(("vcm", "cm", "cs", "cp"))]
n = max(1, sum(r[1] for r in mics))
for i in range(n):
mx = ox + 90 + int(i * (w * scale - 180) / max(n - 1, 1))
parts.append(f'<circle cx="{mx}" cy="{t_y+60}" r="9" fill="#3fb950"/>')
parts.append(f'<text x="{mx}" y="{t_y+82}" text-anchor="middle" fill="#8b949e" '
f'font-size="8">mic</text>')
# остальные устройства в правом углу
others = [r for r in items if not r[0].lower().startswith(("vcm", "cm", "cs", "cp"))]
for i, r in enumerate(others[:5]):
parts.append(place(r[0], "оборудование", ox + int(w * scale) - 80,
oy + int(l * scale) - 40 - i * 34, "#8b949e", 140, 28))
parts.append("</svg>")
return {"svg": "".join(parts), "width_m": w, "length_m": l,
"area_m2": round(w * l, 1)}
def heatmap(q, body):
"""Тепловая карта покрытия: микрофоны (радиус захвата) и камера (FOV)."""
w, l = _room(q)
items = _items(q)
scale = 45
W = int(w * scale) + 120
H = int(l * scale) + 120
ox, oy = 60, 60
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">',
f'<defs><radialGradient id="g"><stop offset="0%" stop-color="#3fb950" '
f'stop-opacity="0.55"/><stop offset="70%" stop-color="#d29922" '
f'stop-opacity="0.25"/><stop offset="100%" stop-color="#f85149" '
f'stop-opacity="0.05"/></radialGradient></defs>',
f'<rect width="{W}" height="{H}" fill="#0a0e13"/>',
f'<rect x="{ox}" y="{oy}" width="{w*scale}" height="{l*scale}" '
f'fill="#0f1620" stroke="#2e4a6b"/>']
# микрофоны: круги захвата
mics = [r for r in items if r[0].lower().startswith(("vcm", "cm", "cs", "cp"))]
total = max(1, sum(r[1] for r in mics))
tx = ox + int(w * scale / 2)
ty = oy + int(l * scale * 0.55)
idx = 0
for r in mics:
radius = C.attrs.get(cc.norm(r[0]), {}).get("audio.pickup_m") or 4
for _ in range(r[1]):
mx = ox + 90 + int(idx * (w * scale - 180) / max(total - 1, 1))
rad = radius * scale
parts.append(f'<circle cx="{mx}" cy="{ty}" r="{rad}" fill="url(#g)"/>')
parts.append(f'<circle cx="{mx}" cy="{ty}" r="7" fill="#3fb950"/>')
parts.append(f'<text x="{mx}" y="{ty+rad+12}" text-anchor="middle" '
f'fill="#8b949e" font-size="9">{_esc(r[0])} {radius} м</text>')
idx += 1
if not mics:
parts.append(f'<text x="{ox+12}" y="{oy+20}" fill="#d29922" font-size="11">'
f'микрофоны не выбраны — покрытие не рассчитано</text>')
# камера: конус FOV
cams = [r for r in items if r[0].lower().startswith(("uvc", "smartvision"))]
if cams:
fov = C.attrs.get(cc.norm(cams[0][0]), {}).get("camera.fov_h") or 80
import math
cx2, cy2 = tx, oy + 30
length = l * scale * 0.8
a1 = math.radians(90 - fov / 2)
a2 = math.radians(90 + fov / 2)
x1 = cx2 + length * math.cos(a1)
y1 = cy2 + length * math.sin(a1)
x2 = cx2 + length * math.cos(a2)
y2 = cy2 + length * math.sin(a2)
parts.append(f'<path d="M {cx2} {cy2} L {x1:.0f} {y1:.0f} A {length:.0f} {length:.0f} 0 0 1 '
f'{x2:.0f} {y2:.0f} Z" fill="#2f81f7" opacity="0.18" stroke="#2f81f7"/>')
parts.append(f'<text x="{cx2}" y="{cy2-8}" text-anchor="middle" fill="#79c0ff" '
f'font-size="9">{_esc(cams[0][0])} FOV {fov:.0f}°</text>')
parts.append("</svg>")
return {"svg": "".join(parts), "mics": total, "cams": len(cams)}
def plan(q, body):
"""Данные плана: устройства с типом установки и начальными координатами."""
w, l = _room(q)
items = _items(q)
devices, x, y = [], 0.15, 0.15
for r in items:
model, qty = r[0], r[1]
mount = C.mount_class(model)
cov = C.coverage(model)
for n in range(qty):
devices.append({"model": model, "mount": mount,
"x": round(x, 3), "y": round(0.15 + 0.12 * n, 3),
"pickup_m": cov["pickup_m"], "fov_h": cov["fov_h"]})
x = x + 0.12 if x < 0.8 else 0.15
return {"w": w, "l": l, "devices": devices,
"legend": {"ceiling": "потолочный", "table": "настольный",
"wall": "настенный", "rack": "стойка", "other": "прочее"}}
def _fresh():
C.reload_if_changed()
serve({
"/diagram": diagram,
"/cables": cables,
"/rack": rack,
"/ipplan": ipplan,
"/layout": layout,
"/plan": plan,
"/heatmap": heatmap,
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8104, "draw", before=C.reload_if_changed)