[WORK] План комнаты и тепловая карта покрытия, спецификация без цен (HTML), смоук-тесты сервисов (25 проверок)

This commit is contained in:
root committed 2026-11-06 18:32:41 +03:00
1 parent b90dd091d3
commit 2d462869fe
3 files changed
+254

No files matched your search

+118
View File
@@ -144,9 +144,127 @@ def ipplan(q, body):
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)}
serve({
"/diagram": diagram,
"/cables": cables,
"/rack": rack,
"/ipplan": ipplan,
"/layout": layout,
"/heatmap": heatmap,
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8104, "draw")
+60
View File
@@ -395,6 +395,65 @@ def ask(q, body):
"llm": bool(answer and "qwen" )}
def spec(q, body):
"""Спецификация проекта без цен: состав, кабели, проверки, комплектация."""
host = (q.get("host") or [""])[0]
seats = int((q.get("seats") or ["8"])[0])
items = _items(q)
if not items:
b = bom(q, body)
if b.get("error"):
return b
items = [[x["model"], x["qty"]] for x in b["bom"]
if not x["model"].startswith(("встроенный", "внешний"))]
hostname = C.devices.get(cc.norm(host), {}).get("name") or host
cab = C.cable_schedule(host, items)
cap = C.capacity(host, items, q.get("infra") or [])
sig = C.signal_chains(host, items)
rev = review({"host": [host], "item": ["%s:%d" % (i[0], i[1]) for i in items]}, None)
def row(*cells):
return "<tr>" + "".join("<td>%s</td>" % c for c in cells) + "</tr>"
h = ["<html><head><meta charset='utf-8'><title>Спецификация</title>",
"<style>body{font:13px Arial;margin:24px}h2{margin:18px 0 8px}"
"table{border-collapse:collapse;width:100%;margin-bottom:14px}"
"td,th{border:1px solid #999;padding:5px 7px;text-align:left;font-size:12px}"
"th{background:#eee}.warn{color:#a15c00}.bad{color:#a11}</style></head><body>",
"<h1>Спецификация оборудования</h1>",
"<p>Комплекс: %s · мест: %d · режим: без цен</p>" % (hostname, seats),
"<h2>1. Состав</h2><table><tr><th>№</th><th>Модель</th><th>Кол</th></tr>"]
for i, r in enumerate(items, 1):
h.append(row(str(i), r[0], str(r[1])))
h.append("</table><h2>2. Кабельный журнал</h2><table>"
"<tr><th>От</th><th>Порт</th><th>К</th><th>Порт</th><th>Тип</th><th>Примечание</th></tr>")
for c in cab["cables"]:
h.append(row(c["from"], c["from_port"], c["to"], c["to_port"], c["type"],
c.get("note") or ""))
h.append("</table><h2>3. Проверки</h2><table><tr><th>Проверка</th><th>Результат</th></tr>")
h.append(row("порты VCH", "%s у хоста, %s устройств" % (cap["vch_ports"], cap["vch_users"])))
h.append(row("порты коммутаторов", "%s (каскад, коммутаторов %s)"
% (cap["extra_ports"], cap["n_switches"])))
h.append(row("питание", "%.1f Вт потребление · %.1f Вт доп. бюджет"
% (cap["total_power_w"], cap["extra_budget_w"])))
h.append(row("сигнальные цепочки", "%s из %s корректны" % (sig["ok"], sig["total"])))
for i in cap["issues"]:
h.append(row("проблема", "<span class='bad'>%s</span>" % i))
h.append("</table><h2>4. Комплектация</h2><table><tr><th>Устройство</th><th>В комплекте</th></tr>")
for r in items:
p = C.package(r[0])
if p["items"]:
h.append(row(r[0], " · ".join(p["items"])))
h.append("</table><h2>5. Ревью</h2><table><tr><th>Готовность</th><th>Значение</th></tr>")
h.append(row("блокеров", str(rev["blockers"])))
h.append(row("предупреждений", str(rev["warnings"])))
h.append(row("готов к закупке", "да" if rev["ready"] else "нет"))
h.append("</table></body></html>")
html = "".join(h)
return {"__file__": html.encode(), "filename": "spec-%s.html" % cc.norm(hostname)[:18],
"content_type": "text/html; charset=utf-8"}
serve({
"/groups": groups,
"/check": check,
@@ -410,5 +469,6 @@ serve({
"/review": review,
"/vendors": vendors,
"/ask": ask,
"/spec": spec,
"/xlsx": xlsx,
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8102, "engine")
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Смоук-тесты сервисов комбайна: все эндпойнты отвечают и данные не пустые."""
import json
import sys
import urllib.request
SVC = {
"catalog": "http://127.0.0.1:8101",
"engine": "http://127.0.0.1:8102",
"project": "http://127.0.0.1:8103",
"draw": "http://127.0.0.1:8104",
"docs": "http://127.0.0.1:8105",
}
HOST = "meetingbara50"
ITEMS = "item=UVC86&item=CTP25&item=MeetingDisplay"
def get(url, timeout=60):
with urllib.request.urlopen(url, timeout=timeout) as r:
return r.status, r.read()
CHECKS = [
("catalog", "/hosts", lambda b: len(json.loads(b).get("hosts") or []) > 10),
("catalog", "/matrix", lambda b: len(json.loads(b).get("rows") or []) > 10),
("catalog", "/vendors", lambda b: len(json.loads(b).get("vendors") or []) >= 1),
("catalog", "/port-objects?name=UVC86", lambda b: len(json.loads(b).get("ports") or []) > 0),
("engine", "/groups?host=%s" % HOST, lambda b: len(json.loads(b).get("groups") or []) > 3),
("engine", "/autofill?host=%s&seats=10" % HOST,
lambda b: len(json.loads(b).get("items") or []) >= 3),
("engine", "/checklist?host=%s&%s" % (HOST, ITEMS),
lambda b: json.loads(b).get("total", 0) >= 5),
("engine", "/signals?host=%s&%s" % (HOST, ITEMS),
lambda b: json.loads(b).get("total", 0) >= 1),
("engine", "/cables?host=%s&%s" % (HOST, ITEMS),
lambda b: "cables" in json.loads(b)),
("engine", "/ports?host=%s&%s" % (HOST, ITEMS),
lambda b: "free_in" in json.loads(b)),
("engine", "/capacity?host=%s&%s" % (HOST, ITEMS),
lambda b: "vch_ports" in json.loads(b)),
("engine", "/review?host=%s&%s" % (HOST, ITEMS),
lambda b: "issues" in json.loads(b)),
("engine", "/check?host=meetingeye500&device=VCM36-W",
lambda b: json.loads(b).get("supported") is False),
("engine", "/accessory?device=WPP30",
lambda b: json.loads(b).get("count", 0) > 5),
("engine", "/bom?host=%s&seats=10" % HOST, lambda b: len(json.loads(b).get("bom") or []) > 2),
("engine", "/xlsx?host=%s&seats=10" % HOST, lambda b: len(b) > 3000),
("engine", "/spec?host=%s&seats=10" % HOST, lambda b: len(b) > 500),
("engine", "/ask?q=MeetingEye+500+%2B+VCM38", lambda b: bool(json.loads(b).get("answer"))),
("project", "/list", lambda b: "projects" in json.loads(b)),
("draw", "/diagram?host=%s&%s" % (HOST, ITEMS),
lambda b: b"<svg" in b and len(b) > 800),
("draw", "/layout?host=%s&w=8&l=10&%s" % (HOST, ITEMS), lambda b: b"<svg" in b),
("draw", "/heatmap?host=%s&w=8&l=10&%s" % (HOST, ITEMS), lambda b: b"<svg" in b),
("draw", "/rack?item=MCore&item=AP08", lambda b: b"<svg" in b),
("draw", "/ipplan?item=MCore&item=AP08", lambda b: json.loads(b).get("count", 0) >= 1),
("docs", "/docs?device=UVC86", lambda b: "docs" in json.loads(b)),
]
fails = 0
for svc, path, check in CHECKS:
url = SVC[svc] + path
try:
code, body = get(url)
ok = code == 200 and check(body)
print("%s %-6s %-52s %s (%.0f Б)" % ("✓" if ok else "✗", svc, path[:52],
"ok" if ok else "ПРОВАЛ", len(body)))
if not ok:
fails += 1
except Exception as e:
print("✗ %-6s %-52s ошибка: %s" % (svc, path[:52], str(e)[:80]))
fails += 1
print("\nпроверок: %d, провалов: %d" % (len(CHECKS), fails))
sys.exit(1 if fails else 0)