index.html 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. <!doctype html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <title>线架模拟器 · 3D</title>
  7. <style>
  8. :root {
  9. --bg: #0d1117;
  10. --panel: rgba(22, 27, 34, 0.92);
  11. --border: #30363d;
  12. --text: #e6edf3;
  13. --muted: #8b949e;
  14. --green: #52c41a;
  15. --grey: #d9d9d9;
  16. --red: #ff4d4f;
  17. --blue: #1890ff;
  18. }
  19. * { box-sizing: border-box; }
  20. html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text);
  21. font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
  22. #scene { position: fixed; inset: 0; }
  23. #scene canvas { display: block; }
  24. .panel-label {
  25. padding: 4px 10px; border-radius: 6px; background: rgba(13, 17, 23, 0.82);
  26. border: 1px solid var(--border); color: var(--text); font-size: 12px; white-space: nowrap;
  27. pointer-events: none; text-align: center; line-height: 1.35;
  28. }
  29. .panel-label b { font-size: 13px; }
  30. .panel-label span { color: var(--muted); display: block; font-size: 11px; }
  31. .panel-label.offline { border-color: #6e7681; color: var(--muted); }
  32. .panel-label.offline span { color: #f85149; }
  33. #topbar {
  34. position: fixed; top: 12px; left: 50%; transform: translateX(-50%);
  35. display: flex; align-items: center; gap: 16px; padding: 8px 16px;
  36. background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
  37. backdrop-filter: blur(8px); white-space: nowrap; z-index: 10;
  38. }
  39. #topbar h1 { font-size: 14px; margin: 0; font-weight: 600; }
  40. #topbar .stat { color: var(--muted); font-size: 12px; }
  41. #topbar code { color: #79c0ff; font-size: 12px; }
  42. #side {
  43. position: fixed; top: 12px; left: 12px; width: 268px; max-height: calc(100vh - 24px);
  44. overflow: auto; padding: 12px; background: var(--panel); border: 1px solid var(--border);
  45. border-radius: 10px; backdrop-filter: blur(8px); z-index: 10;
  46. }
  47. #side h2 { margin: 0 0 10px; font-size: 13px; font-weight: 600; color: var(--muted); }
  48. .row { display: flex; align-items: center; gap: 8px; padding: 7px 8px; border-radius: 7px;
  49. border: 1px solid transparent; cursor: pointer; }
  50. .row:hover { background: rgba(110, 118, 129, 0.12); }
  51. .row.selected { border-color: #1f6feb; background: rgba(31, 111, 235, 0.12); }
  52. .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: var(--grey); }
  53. .dot.on { background: var(--green); box-shadow: 0 0 6px var(--green); }
  54. .dot.off { background: #f85149; }
  55. .row .name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  56. .row .addr { color: var(--muted); font-variant-numeric: tabular-nums; }
  57. .row button, .btn {
  58. background: #21262d; color: var(--text); border: 1px solid var(--border); border-radius: 6px;
  59. padding: 3px 7px; font-size: 11px; cursor: pointer;
  60. }
  61. .row button:hover, .btn:hover { border-color: #8b949e; }
  62. .btn.primary { background: #1f6feb; border-color: #1f6feb; }
  63. .btn.danger:hover { border-color: #f85149; color: #f85149; }
  64. #add { width: 100%; margin-top: 10px; padding: 7px; }
  65. #takeCard { width: 100%; margin-top: 6px; padding: 7px; }
  66. #cardInfo { margin-top: 8px; font-size: 11px; color: var(--muted); line-height: 1.5; word-break: break-all; }
  67. .legend { margin-top: 12px; display: grid; grid-template-columns: 1fr 1fr; gap: 4px 10px;
  68. color: var(--muted); font-size: 11px; }
  69. .legend i { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 5px; }
  70. #hint {
  71. position: fixed; bottom: 12px; left: 50%; transform: translateX(-50%);
  72. padding: 7px 14px; background: var(--panel); border: 1px solid var(--border);
  73. border-radius: 8px; color: var(--muted); font-size: 12px; z-index: 10; white-space: nowrap;
  74. }
  75. #hint b { color: var(--text); font-weight: 600; }
  76. #tooltip {
  77. position: fixed; pointer-events: none; padding: 6px 10px; border-radius: 7px; font-size: 12px;
  78. background: rgba(13, 17, 23, 0.95); border: 1px solid var(--border); display: none; z-index: 20;
  79. white-space: pre; line-height: 1.5;
  80. }
  81. #toast {
  82. position: fixed; bottom: 60px; left: 50%; transform: translateX(-50%);
  83. padding: 8px 14px; border-radius: 8px; background: #da3633; color: #fff; font-size: 12px;
  84. display: none; z-index: 30;
  85. }
  86. </style>
  87. <script type="importmap">
  88. {
  89. "imports": {
  90. "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
  91. "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
  92. }
  93. }
  94. </script>
  95. </head>
  96. <body>
  97. <div id="scene"></div>
  98. <div id="topbar">
  99. <h1>线架模拟器</h1>
  100. <span class="stat">虚拟串口 <code id="transport">—</code></span>
  101. <span class="stat">帧 <span id="stats">0 / 0</span></span>
  102. </div>
  103. <div id="side">
  104. <h2>线架列表</h2>
  105. <div id="list"></div>
  106. <button class="btn primary" id="add">+ 新增线架</button>
  107. <button class="btn" id="takeCard">拿卡靠近 · 模拟识别</button>
  108. <div id="cardInfo" style="display:none"></div>
  109. <div class="legend">
  110. <div><i style="background:var(--green)"></i>已连接</div>
  111. <div><i style="background:var(--grey)"></i>未连接</div>
  112. <div><i style="background:var(--red)"></i>非法插入</div>
  113. <div><i style="background:var(--blue)"></i>非法拔出</div>
  114. </div>
  115. </div>
  116. <div id="hint">点击端口 <b>插/拔卡</b> Shift+点击插入 <b>期望卡</b> 点「拿卡靠近」后把卡移到端口上方停 <b>0.5s</b> 自动识别 拖动旋转 / 滚轮缩放</div>
  117. <div id="tooltip"></div>
  118. <div id="toast"></div>
  119. <script type="module">
  120. import * as THREE from 'three';
  121. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  122. import { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
  123. const STATE_COLOR = {
  124. CONNECTED: 0x52c41a,
  125. DISCONNECTED: 0x8b949e,
  126. ILLEGAL_CONNECT: 0xff4d4f,
  127. ILLEGAL_DISCONNECT: 0x1890ff,
  128. };
  129. const STATE_TEXT = {
  130. CONNECTED: '已连接',
  131. DISCONNECTED: '未连接',
  132. ILLEGAL_CONNECT: '非法插入',
  133. ILLEGAL_DISCONNECT: '非法拔出',
  134. };
  135. const HEX = '0123456789ABCDEF';
  136. const randomCard = () => Array.from({ length: 12 }, () => HEX[Math.floor(Math.random() * 16)]).join('');
  137. /* ---------- Three.js 基础 ---------- */
  138. const container = document.getElementById('scene');
  139. const scene = new THREE.Scene();
  140. scene.background = new THREE.Color(0x0d1117);
  141. scene.fog = new THREE.Fog(0x0d1117, 30, 90);
  142. const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 300);
  143. camera.position.set(0, 5.2, 10.5);
  144. const renderer = new THREE.WebGLRenderer({ antialias: true });
  145. renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
  146. renderer.setSize(innerWidth, innerHeight);
  147. renderer.shadowMap.enabled = true;
  148. renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  149. container.appendChild(renderer.domElement);
  150. const labelRenderer = new CSS2DRenderer();
  151. labelRenderer.setSize(innerWidth, innerHeight);
  152. Object.assign(labelRenderer.domElement.style, { position: 'fixed', inset: '0', pointerEvents: 'none' });
  153. container.appendChild(labelRenderer.domElement);
  154. const controls = new OrbitControls(camera, renderer.domElement);
  155. controls.target.set(0, 1.4, 0);
  156. controls.enableDamping = true;
  157. controls.dampingFactor = 0.08;
  158. controls.maxPolarAngle = Math.PI * 0.52;
  159. controls.minDistance = 3;
  160. controls.maxDistance = 80;
  161. scene.add(new THREE.AmbientLight(0x8fa3bf, 0.75));
  162. const key = new THREE.DirectionalLight(0xffffff, 1.5);
  163. key.position.set(6, 14, 10);
  164. key.castShadow = true;
  165. key.shadow.mapSize.set(2048, 2048);
  166. key.shadow.camera.left = -30;
  167. key.shadow.camera.right = 30;
  168. key.shadow.camera.top = 30;
  169. key.shadow.camera.bottom = -30;
  170. scene.add(key);
  171. scene.add(new THREE.DirectionalLight(0x3b82f6, 0.35).translateX(-8).translateY(6).translateZ(-6));
  172. const floor = new THREE.Mesh(
  173. new THREE.PlaneGeometry(200, 200),
  174. new THREE.MeshStandardMaterial({ color: 0x0b0f14, roughness: 1, metalness: 0 }),
  175. );
  176. floor.rotation.x = -Math.PI / 2;
  177. floor.receiveShadow = true;
  178. scene.add(floor);
  179. const grid = new THREE.GridHelper(120, 120, 0x1f6feb, 0x1b222c);
  180. grid.position.y = 0.002;
  181. grid.material.opacity = 0.35;
  182. grid.material.transparent = true;
  183. scene.add(grid);
  184. /* ---------- 线架 3D 构造 ---------- */
  185. const PANEL_W = 3.0, PANEL_H = 1.0, PANEL_D = 0.26;
  186. const COLS_PER_ROW = 6;
  187. const SPACING_X = 3.7, SPACING_Z = 2.3;
  188. const BASE_Y = 1.35;
  189. const bodyGeo = new THREE.BoxGeometry(PANEL_W, PANEL_H, PANEL_D);
  190. const faceGeo = new THREE.BoxGeometry(PANEL_W - 0.05, PANEL_H - 0.05, 0.02);
  191. const portGeo = new THREE.CylinderGeometry(0.09, 0.09, 0.04, 20);
  192. portGeo.rotateX(Math.PI / 2);
  193. const panelObjects = new Map(); // id -> { group, body, face, ports: [{mesh, port}] }
  194. const pickables = []; // 射线拾取(端口 + 面板实体)
  195. let selectedId = null;
  196. let state = { panels: [], transport: '', stats: { rx: 0, tx: 0 } };
  197. function portStateOf(panel, port) {
  198. if (!panel.online) return 'OFFLINE';
  199. const card = panel.cards[String(port)] || null;
  200. const expected = panel.expected[String(port)] || null;
  201. if (card && expected && card !== expected) return 'ILLEGAL_CONNECT';
  202. if (card) return 'CONNECTED';
  203. if (expected) return 'ILLEGAL_DISCONNECT';
  204. return 'DISCONNECTED';
  205. }
  206. function createPanelObject(panel) {
  207. const group = new THREE.Group();
  208. group.userData = { type: 'panel', id: panel.id };
  209. const bodyMat = new THREE.MeshStandardMaterial({ color: 0x1c2533, metalness: 0.55, roughness: 0.45 });
  210. const body = new THREE.Mesh(bodyGeo, bodyMat);
  211. body.castShadow = true;
  212. body.receiveShadow = true;
  213. body.userData = { type: 'panel', id: panel.id };
  214. group.add(body);
  215. const faceMat = new THREE.MeshStandardMaterial({ color: 0x25344a, metalness: 0.25, roughness: 0.75 });
  216. const face = new THREE.Mesh(faceGeo, faceMat);
  217. face.position.z = PANEL_D / 2 + 0.005;
  218. face.userData = { type: 'panel', id: panel.id };
  219. group.add(face);
  220. const ports = [];
  221. const x0 = -(PANEL_W / 2) + 0.25;
  222. const dx = (PANEL_W - 0.50) / 11;
  223. const rows = [0.21, -0.21];
  224. for (let r = 0; r < 2; r++) {
  225. for (let c = 0; c < 12; c++) {
  226. const port = r * 12 + c + 1;
  227. const mat = new THREE.MeshStandardMaterial({ color: STATE_COLOR.DISCONNECTED, emissive: 0x000000 });
  228. const mesh = new THREE.Mesh(portGeo, mat);
  229. mesh.position.set(x0 + c * dx, rows[r], PANEL_D / 2 + 0.03);
  230. mesh.userData = { type: 'port', id: panel.id, port };
  231. group.add(mesh);
  232. ports.push({ mesh, port });
  233. pickables.push(mesh);
  234. }
  235. }
  236. const el = document.createElement('div');
  237. el.className = 'panel-label';
  238. const label = new CSS2DObject(el);
  239. label.position.set(0, PANEL_H / 2 + 0.42, 0);
  240. group.add(label);
  241. group.userData.parts = { body, face, ports, label, el };
  242. pickables.push(body, face);
  243. scene.add(group);
  244. return group;
  245. }
  246. function removePanelObject(id) {
  247. const obj = panelObjects.get(id);
  248. if (!obj) return;
  249. const parts = obj.userData.parts;
  250. for (const { mesh } of parts.ports) {
  251. const i = pickables.indexOf(mesh);
  252. if (i >= 0) pickables.splice(i, 1);
  253. mesh.material.dispose();
  254. }
  255. for (const m of [parts.body, parts.face]) {
  256. const i = pickables.indexOf(m);
  257. if (i >= 0) pickables.splice(i, 1);
  258. }
  259. parts.body.material.dispose();
  260. parts.face.material.dispose();
  261. parts.label.element.remove();
  262. scene.remove(obj);
  263. panelObjects.delete(id);
  264. }
  265. function layout(panel, index) {
  266. const col = index % COLS_PER_ROW;
  267. const row = Math.floor(index / COLS_PER_ROW);
  268. const totalCols = Math.min(COLS_PER_ROW, Math.max(1, state.panels.length));
  269. const x = (col - (totalCols - 1) / 2) * SPACING_X;
  270. const z = row * SPACING_Z;
  271. return { x, z };
  272. }
  273. /* ---------- 拿卡靠近识别 ---------- */
  274. const DETECT_MS = 500; // 停留多久判定识别
  275. const DETECT_RADIUS = 0.11; // 距端口中心的识别半径(线架局部坐标)
  276. const cardGroup = new THREE.Group();
  277. const cardBody = new THREE.Mesh(
  278. new THREE.BoxGeometry(0.5, 0.32, 0.022),
  279. new THREE.MeshStandardMaterial({ color: 0xe6edf3, metalness: 0.15, roughness: 0.55, emissive: 0x1f6feb, emissiveIntensity: 0.25 }),
  280. );
  281. const cardChip = new THREE.Mesh(
  282. new THREE.BoxGeometry(0.15, 0.11, 0.008),
  283. new THREE.MeshStandardMaterial({ color: 0xd4a017, metalness: 0.85, roughness: 0.3, emissive: 0x6b4b00, emissiveIntensity: 0.3 }),
  284. );
  285. cardChip.position.set(-0.12, 0.03, 0.015);
  286. const cardEdge = new THREE.LineSegments(
  287. new THREE.EdgesGeometry(new THREE.BoxGeometry(0.5, 0.32, 0.022)),
  288. new THREE.LineBasicMaterial({ color: 0x58a6ff }),
  289. );
  290. cardGroup.add(cardBody, cardChip, cardEdge);
  291. cardGroup.visible = false;
  292. cardGroup.renderOrder = 5;
  293. scene.add(cardGroup);
  294. const ringMat = new THREE.MeshBasicMaterial({ color: 0x58a6ff, transparent: true, opacity: 0.8, side: THREE.DoubleSide });
  295. const targetRing = new THREE.Mesh(new THREE.TorusGeometry(0.115, 0.013, 8, 40), ringMat);
  296. targetRing.visible = false;
  297. targetRing.renderOrder = 6;
  298. scene.add(targetRing);
  299. let cardMode = false;
  300. let heldUid = null;
  301. let hover = null; // { id, port, mesh }
  302. let hoverSince = 0;
  303. const flashes = []; // 识别成功的端口闪光
  304. function cardInfoEl() { return document.getElementById('cardInfo'); }
  305. function setCardMode(on) {
  306. cardMode = on;
  307. const btn = document.getElementById('takeCard');
  308. btn.classList.toggle('primary', on);
  309. btn.textContent = on ? '放回卡 · 取消持卡' : '拿卡靠近 · 模拟识别';
  310. const info = cardInfoEl();
  311. if (on) {
  312. heldUid = randomCard();
  313. cardGroup.visible = false;
  314. targetRing.visible = false;
  315. hover = null;
  316. info.style.display = 'block';
  317. info.textContent = `持卡中 ${heldUid} —— 移到端口上方停留 0.5s 会被识别(Esc 取消)`;
  318. } else {
  319. heldUid = null;
  320. cardGroup.visible = false;
  321. targetRing.visible = false;
  322. hover = null;
  323. info.style.display = 'none';
  324. }
  325. }
  326. function moveCard(e) {
  327. const hits = pickAt(e.clientX, e.clientY);
  328. const hit = hits.find(h => h.object.userData && (h.object.userData.type === 'port' || h.object.userData.type === 'panel'));
  329. if (!hit) {
  330. cardGroup.visible = false;
  331. targetRing.visible = false;
  332. hover = null;
  333. return;
  334. }
  335. const id = hit.object.userData.id;
  336. const obj = panelObjects.get(id);
  337. if (!obj) return;
  338. cardGroup.position.copy(hit.point).add(new THREE.Vector3(0, 0.08, 0.3));
  339. cardGroup.rotation.z = Math.sin(performance.now() / 320) * 0.05;
  340. cardGroup.visible = true;
  341. // 找线架局部坐标里最近的端口
  342. const local = obj.worldToLocal(cardGroup.position.clone());
  343. let best = null;
  344. let bestD = Infinity;
  345. for (const item of obj.userData.parts.ports) {
  346. const d = Math.hypot(local.x - item.mesh.position.x, local.y - item.mesh.position.y);
  347. if (d < bestD) { bestD = d; best = item; }
  348. }
  349. if (best && bestD <= DETECT_RADIUS) {
  350. if (!hover || hover.id !== id || hover.port !== best.port) {
  351. hover = { id, port: best.port, mesh: best.mesh };
  352. hoverSince = performance.now();
  353. }
  354. const wp = new THREE.Vector3();
  355. best.mesh.getWorldPosition(wp);
  356. targetRing.position.copy(wp).add(new THREE.Vector3(0, 0, 0.035));
  357. targetRing.scale.setScalar(0.8);
  358. targetRing.visible = true;
  359. } else {
  360. hover = null;
  361. targetRing.visible = false;
  362. }
  363. }
  364. async function recognizeCard() {
  365. if (!hover || !cardMode) return;
  366. const { id, port } = hover;
  367. const panel = state.panels.find(p => p.id === id);
  368. hover = null;
  369. targetRing.visible = false;
  370. if (!panel) return;
  371. if (panel.cards[String(port)]) {
  372. toast(`端口 ${port} 已有卡,未识别`);
  373. return;
  374. }
  375. const uid = heldUid;
  376. setCardMode(false);
  377. await api('/api/port/set', { id, port, card_uid: uid });
  378. flashPort(id, port);
  379. toast(`已识别 ${uid} → 线架 #${id} 端口 ${port}`);
  380. pollOnce();
  381. }
  382. function flashPort(id, port) {
  383. const obj = panelObjects.get(id);
  384. const item = obj?.userData.parts.ports.find(p => p.port === port);
  385. if (item) flashes.push({ mesh: item.mesh, t0: performance.now() });
  386. }
  387. function updateFlashes(now) {
  388. for (let i = flashes.length - 1; i >= 0; i--) {
  389. const f = flashes[i];
  390. const t = (now - f.t0) / 650;
  391. if (t >= 1) {
  392. f.mesh.scale.setScalar(1);
  393. flashes.splice(i, 1);
  394. continue;
  395. }
  396. f.mesh.scale.setScalar(1 + Math.sin(t * Math.PI) * 0.9);
  397. }
  398. }
  399. /* ---------- 渲染状态 ---------- */
  400. function render() {
  401. const ids = new Set(state.panels.map(p => p.id));
  402. for (const id of [...panelObjects.keys()]) {
  403. if (!ids.has(id)) removePanelObject(id);
  404. }
  405. state.panels.forEach((panel, index) => {
  406. let obj = panelObjects.get(panel.id);
  407. if (!obj) {
  408. obj = createPanelObject(panel);
  409. panelObjects.set(panel.id, obj);
  410. }
  411. const { x, z } = layout(panel, index);
  412. obj.position.set(x, BASE_Y, z);
  413. const parts = obj.userData.parts;
  414. parts.el.innerHTML = `<b>${'线架'} #${panel.id}</b><span>地址 ${panel.address} · ${panel.online ? '在线' : '已断联'}</span>`;
  415. parts.el.className = 'panel-label' + (panel.online ? '' : ' offline');
  416. const selected = panel.id === selectedId;
  417. parts.body.material.color.setHex(selected ? 0x2b4a7a : 0x1c2533);
  418. parts.body.material.emissive.setHex(selected ? 0x0b2c4d : 0x000000);
  419. parts.face.material.color.setHex(panel.online ? 0x25344a : 0x1a1e24);
  420. for (const { mesh, port } of parts.ports) {
  421. const st = portStateOf(panel, port);
  422. if (st === 'OFFLINE') {
  423. mesh.material.color.setHex(0x3a3f46);
  424. mesh.material.emissive.setHex(0x000000);
  425. mesh.material.emissiveIntensity = 0;
  426. continue;
  427. }
  428. const color = STATE_COLOR[st] ?? STATE_COLOR.DISCONNECTED;
  429. mesh.material.color.setHex(color);
  430. mesh.material.emissive.setHex(color);
  431. mesh.material.emissiveIntensity = st === 'DISCONNECTED' ? 0.05 : 0.85;
  432. }
  433. });
  434. // 侧边列表
  435. const list = document.getElementById('list');
  436. list.innerHTML = state.panels.map(p => `
  437. <div class="row${p.id === selectedId ? ' selected' : ''}" data-id="${p.id}">
  438. <span class="dot ${p.online ? 'on' : 'off'}"></span>
  439. <span class="name">#${p.id} <span class="addr">地址 ${p.address}</span></span>
  440. <button data-act="toggle">${p.online ? '断联' : '恢复'}</button>
  441. <button data-act="addr">改址</button>
  442. <button data-act="del" class="danger">删</button>
  443. </div>`).join('') || '<div style="color:var(--muted)">暂无(点下面新增)</div>';
  444. document.getElementById('transport').textContent = state.transport || '—';
  445. document.getElementById('stats').textContent = `${state.stats.rx} / ${state.stats.tx}`;
  446. }
  447. /* ---------- API ---------- */
  448. async function api(path, body) {
  449. const res = await fetch(path, {
  450. method: body === undefined ? 'GET' : 'POST',
  451. headers: { 'Content-Type': 'application/json' },
  452. body: body === undefined ? undefined : JSON.stringify(body),
  453. });
  454. const data = await res.json().catch(() => ({}));
  455. if (!res.ok || data.success === false) {
  456. toast(data.message || `请求失败 (${res.status})`);
  457. }
  458. return data;
  459. }
  460. let toastTimer = null;
  461. function toast(msg) {
  462. const el = document.getElementById('toast');
  463. el.textContent = msg;
  464. el.style.display = 'block';
  465. clearTimeout(toastTimer);
  466. toastTimer = setTimeout(() => { el.style.display = 'none'; }, 2600);
  467. }
  468. async function poll() {
  469. try {
  470. const res = await fetch('/api/state', { cache: 'no-store' });
  471. const data = await res.json();
  472. if (data.success) {
  473. state = data;
  474. render();
  475. }
  476. } catch (e) {
  477. document.getElementById('transport').textContent = '连接模拟器失败';
  478. }
  479. setTimeout(poll, 400);
  480. }
  481. /* ---------- 交互 ---------- */
  482. const raycaster = new THREE.Raycaster();
  483. const pointer = new THREE.Vector2();
  484. const tooltip = document.getElementById('tooltip');
  485. function pickAt(clientX, clientY) {
  486. const rect = renderer.domElement.getBoundingClientRect();
  487. pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
  488. pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
  489. raycaster.setFromCamera(pointer, camera);
  490. return raycaster.intersectObjects(pickables, false);
  491. }
  492. let downAt = null;
  493. renderer.domElement.addEventListener('pointerdown', (e) => {
  494. if (e.button !== 0) return;
  495. downAt = { x: e.clientX, y: e.clientY };
  496. });
  497. renderer.domElement.addEventListener('pointerup', async (e) => {
  498. if (e.button !== 0 || !downAt) return;
  499. const moved = Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y);
  500. downAt = null;
  501. if (cardMode) return; // 持卡模式:点击不插拔,靠靠近识别
  502. if (moved > 6) return; // 拖动视角,不算点击
  503. const hits = pickAt(e.clientX, e.clientY);
  504. if (!hits.length) return;
  505. const hit = hits[0].object;
  506. const { type, id, port } = hit.userData || {};
  507. if (type === 'port') {
  508. const panel = state.panels.find(p => p.id === id);
  509. if (!panel) return;
  510. const current = panel.cards[String(port)] || null;
  511. const expected = panel.expected[String(port)] || null;
  512. let card = null;
  513. if (e.shiftKey && expected) card = expected;
  514. else if (!current) card = randomCard();
  515. await api('/api/port/set', { id, port, card_uid: card });
  516. pollOnce();
  517. } else if (type === 'panel') {
  518. selectedId = id;
  519. render();
  520. }
  521. });
  522. renderer.domElement.addEventListener('pointermove', (e) => {
  523. if (cardMode) {
  524. tooltip.style.display = 'none';
  525. moveCard(e);
  526. return;
  527. }
  528. const hits = pickAt(e.clientX, e.clientY);
  529. if (!hits.length) {
  530. tooltip.style.display = 'none';
  531. return;
  532. }
  533. const { type, id, port } = hits[0].object.userData || {};
  534. if (type !== 'port') {
  535. tooltip.style.display = 'none';
  536. return;
  537. }
  538. const panel = state.panels.find(p => p.id === id);
  539. if (!panel) return;
  540. const st = portStateOf(panel, port);
  541. const card = panel.cards[String(port)] || '—';
  542. const expected = panel.expected[String(port)] || '—';
  543. tooltip.textContent = `线架 #${panel.id} · 端口 ${port}\n状态:${st === 'OFFLINE' ? '已断联' : (STATE_TEXT[st] || st)}\n卡号:${card}\n期望:${expected}`;
  544. tooltip.style.display = 'block';
  545. tooltip.style.left = `${e.clientX + 14}px`;
  546. tooltip.style.top = `${e.clientY + 14}px`;
  547. });
  548. renderer.domElement.addEventListener('pointerleave', () => {
  549. if (!cardMode) return;
  550. cardGroup.visible = false;
  551. targetRing.visible = false;
  552. hover = null;
  553. });
  554. document.getElementById('list').addEventListener('click', async (e) => {
  555. const btn = e.target.closest('button');
  556. const row = e.target.closest('.row');
  557. if (!row) return;
  558. const id = Number(row.dataset.id);
  559. const panel = state.panels.find(p => p.id === id);
  560. if (!panel) return;
  561. if (!btn) {
  562. selectedId = id;
  563. render();
  564. return;
  565. }
  566. const act = btn.dataset.act;
  567. if (act === 'toggle') {
  568. await api('/api/panel/update', { id, online: !panel.online });
  569. } else if (act === 'addr') {
  570. const input = prompt('设置线架地址(1-247)', String(panel.address));
  571. if (input === null) return;
  572. const address = parseInt(input, 10);
  573. if (!Number.isFinite(address)) return toast('地址必须是数字');
  574. await api('/api/panel/update', { id, address });
  575. } else if (act === 'del') {
  576. if (!confirm(`删除线架 #${id}(地址 ${panel.address})?`)) return;
  577. await api('/api/panel/delete', { id });
  578. if (selectedId === id) selectedId = null;
  579. }
  580. pollOnce();
  581. });
  582. document.getElementById('add').addEventListener('click', async () => {
  583. const input = prompt('新线架地址(留空=自动分配)', '');
  584. if (input === null) return;
  585. const address = input.trim() === '' ? undefined : parseInt(input, 10);
  586. if (address !== undefined && !Number.isFinite(address)) return toast('地址必须是数字');
  587. const data = await api('/api/panel/add', { address });
  588. if (data.success) selectedId = data.id;
  589. pollOnce();
  590. });
  591. document.getElementById('takeCard').addEventListener('click', () => setCardMode(!cardMode));
  592. addEventListener('keydown', (e) => {
  593. if (e.key === 'Escape' && cardMode) setCardMode(false);
  594. });
  595. async function pollOnce() {
  596. try {
  597. const res = await fetch('/api/state', { cache: 'no-store' });
  598. const data = await res.json();
  599. if (data.success) { state = data; render(); }
  600. } catch (_) { /* 忽略 */ }
  601. }
  602. addEventListener('resize', () => {
  603. camera.aspect = innerWidth / innerHeight;
  604. camera.updateProjectionMatrix();
  605. renderer.setSize(innerWidth, innerHeight);
  606. labelRenderer.setSize(innerWidth, innerHeight);
  607. });
  608. /* ---------- 主循环 ---------- */
  609. function animate() {
  610. requestAnimationFrame(animate);
  611. controls.update();
  612. const now = performance.now();
  613. if (cardMode && hover) {
  614. const p = Math.min(1, (now - hoverSince) / DETECT_MS);
  615. ringMat.opacity = 0.35 + 0.6 * p;
  616. const s = 0.75 + 0.55 * p;
  617. targetRing.scale.set(s, s, 1);
  618. if (p >= 1) recognizeCard();
  619. }
  620. updateFlashes(now);
  621. renderer.render(scene, camera);
  622. labelRenderer.render(scene, camera);
  623. }
  624. animate();
  625. poll();
  626. </script>
  627. </body>
  628. </html>