| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668 |
- const parseResponse = async (r) => {
- const contentType = r.headers.get('content-type') || '';
- if (contentType.includes('application/json')) {
- return r.json();
- }
- const text = await r.text();
- return text ? { text } : {};
- };
- const API = {
- get: async (url) => {
- const r = await fetch(url);
- if (!r.ok) {
- const text = await r.text();
- throw new Error(`${url}: ${r.status} ${text}`);
- }
- return parseResponse(r);
- },
- post: async (url, body = {}) => {
- const r = await fetch(url, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body)
- });
- if (!r.ok) {
- const text = await r.text();
- throw new Error(`${url}: ${r.status} ${text}`);
- }
- return parseResponse(r);
- },
- del: async (url) => {
- const r = await fetch(url, { method: 'DELETE' });
- if (!r.ok) {
- const text = await r.text();
- throw new Error(`${url}: ${r.status} ${text}`);
- }
- return parseResponse(r);
- }
- };
- let currentGroup = null;
- let scanPollInterval = null;
- let controlsGloballyDisabled = false;
- let tempPreview = null;
- let selectedSampleEl = null;
- function log(msg) {
- const panel = document.getElementById('log-panel');
- const line = document.createElement('div');
- line.textContent = `${new Date().toLocaleTimeString()} ${msg}`;
- panel.appendChild(line);
- while (panel.children.length > 200) {
- panel.removeChild(panel.firstChild);
- }
- panel.scrollTop = panel.scrollHeight;
- }
- function setStatus(msg) {
- document.getElementById('status').textContent = `状态:${msg}`;
- }
- function setControlsDisabled(disabled) {
- controlsGloballyDisabled = disabled;
- ['btn-scan', 'btn-poll-start', 'btn-poll-stop', 'btn-preview', 'btn-add'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.disabled = disabled;
- });
- ['inp-pan', 'inp-tilt', 'inp-zoom', 'inp-dwell'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.disabled = disabled;
- });
- }
- async function withDisabled(id, fn) {
- const el = document.getElementById(id);
- el.disabled = true;
- try {
- return await fn();
- } finally {
- if (!controlsGloballyDisabled) {
- el.disabled = false;
- }
- }
- }
- function parseStrictFloat(value, name) {
- const num = Number(value);
- if (!Number.isFinite(num)) {
- throw new Error(`${name} 必须是有效数字`);
- }
- return num;
- }
- function escapeHtml(text) {
- const div = document.createElement('div');
- div.textContent = text;
- return div.innerHTML;
- }
- function setSelectedPreview(url) {
- const img = document.getElementById('selected-preview');
- if (url) {
- img.src = url;
- img.style.display = 'block';
- } else {
- img.src = '';
- img.style.display = 'none';
- }
- }
- function selectSample(sample) {
- document.getElementById('inp-pan').value = sample.pan.toFixed(2);
- document.getElementById('inp-tilt').value = sample.tilt.toFixed(2);
- document.getElementById('inp-zoom').value = sample.zoom;
- tempPreview = { path: sample.thumbnail };
- setSelectedPreview(`/api/sample-image?path=${encodeURIComponent(sample.thumbnail)}`);
- if (sampleCanvas) sampleCanvas.setSelected(sample.pan, sample.tilt);
- }
- class SampleCanvas {
- constructor(canvasId, wrapperId) {
- this.canvas = document.getElementById(canvasId);
- this.wrapper = document.getElementById(wrapperId);
- this.ctx = this.canvas.getContext('2d');
- this.samples = [];
- this.pans = [];
- this.tilts = [];
- this.sampleMap = new Map();
- this.images = new Map();
- this.cellW = 160;
- this.cellH = 120;
- this.captionH = 20;
- this.scale = 1;
- this.offsetX = 0;
- this.offsetY = 0;
- this.selectedPan = null;
- this.selectedTilt = null;
- this.isDragging = false;
- this.dragStart = { x: 0, y: 0, ox: 0, oy: 0 };
- this.pendingDraw = false;
- this.resize();
- window.addEventListener('resize', () => this.resize());
- this.setupEvents();
- }
- resize() {
- const rect = this.wrapper.getBoundingClientRect();
- this.canvas.width = rect.width;
- this.canvas.height = rect.height;
- this.draw();
- }
- setSamples(samples) {
- this.samples = samples || [];
- this.pans = Array.from(new Set(this.samples.map(s => s.pan))).sort((a, b) => a - b);
- this.tilts = Array.from(new Set(this.samples.map(s => s.tilt))).sort((a, b) => b - a);
- this.sampleMap = new Map();
- this.samples.forEach(s => this.sampleMap.set(`${s.pan},${s.tilt}`, s));
- this.images = new Map();
- this.samples.forEach(s => {
- const img = new Image();
- img.crossOrigin = 'anonymous';
- img.src = `/api/sample-image?path=${encodeURIComponent(s.thumbnail)}`;
- img.onload = () => this.draw();
- this.images.set(`${s.pan},${s.tilt}`, img);
- });
- this.fitToView();
- this.draw();
- }
- contentWidth() {
- return this.pans.length * this.cellW;
- }
- contentHeight() {
- return this.tilts.length * (this.cellH + this.captionH);
- }
- fitToView() {
- const pw = this.canvas.width / this.contentWidth();
- const ph = this.canvas.height / this.contentHeight();
- this.scale = Math.min(pw, ph, 1);
- this.offsetX = (this.canvas.width - this.contentWidth() * this.scale) / 2;
- this.offsetY = (this.canvas.height - this.contentHeight() * this.scale) / 2;
- this.updateZoomLabel();
- }
- resetView() {
- this.fitToView();
- this.draw();
- }
- updateZoomLabel() {
- const label = document.getElementById('zoom-level');
- if (label) label.textContent = `${Math.round(this.scale * 100)}%`;
- }
- setupEvents() {
- this.canvas.addEventListener('wheel', (e) => {
- e.preventDefault();
- const rect = this.canvas.getBoundingClientRect();
- const mx = e.clientX - rect.left;
- const my = e.clientY - rect.top;
- const factor = e.deltaY < 0 ? 1.1 : 0.9;
- const newScale = Math.max(0.1, Math.min(5.0, this.scale * factor));
- this.offsetX = mx - (mx - this.offsetX) * (newScale / this.scale);
- this.offsetY = my - (my - this.offsetY) * (newScale / this.scale);
- this.scale = newScale;
- this.updateZoomLabel();
- this.draw();
- }, { passive: false });
- this.canvas.addEventListener('mousedown', (e) => {
- if (e.button !== 0) return;
- this.isDragging = true;
- this.dragStart = { x: e.clientX, y: e.clientY, ox: this.offsetX, oy: this.offsetY };
- this.wrapper.style.cursor = 'grabbing';
- });
- window.addEventListener('mousemove', (e) => {
- if (!this.isDragging) return;
- this.offsetX = this.dragStart.ox + (e.clientX - this.dragStart.x);
- this.offsetY = this.dragStart.oy + (e.clientY - this.dragStart.y);
- this.draw();
- });
- window.addEventListener('mouseup', () => {
- if (this.isDragging) {
- this.isDragging = false;
- this.wrapper.style.cursor = 'grab';
- }
- });
- this.canvas.addEventListener('click', (e) => {
- if (this.isDragging) return;
- const rect = this.canvas.getBoundingClientRect();
- const mx = e.clientX - rect.left;
- const my = e.clientY - rect.top;
- const worldX = (mx - this.offsetX) / this.scale;
- const worldY = (my - this.offsetY) / this.scale;
- const col = Math.floor(worldX / this.cellW);
- const row = Math.floor(worldY / (this.cellH + this.captionH));
- if (col < 0 || col >= this.pans.length || row < 0 || row >= this.tilts.length) return;
- const pan = this.pans[col];
- const tilt = this.tilts[row];
- const s = this.sampleMap.get(`${pan},${tilt}`);
- if (s) selectSample(s);
- });
- }
- setSelected(pan, tilt) {
- this.selectedPan = pan;
- this.selectedTilt = tilt;
- this.draw();
- }
- draw() {
- if (this.pendingDraw) return;
- this.pendingDraw = true;
- requestAnimationFrame(() => {
- this.pendingDraw = false;
- this._draw();
- });
- }
- _draw() {
- const ctx = this.ctx;
- const w = this.canvas.width;
- const h = this.canvas.height;
- ctx.clearRect(0, 0, w, h);
- if (this.samples.length === 0) {
- ctx.fillStyle = '#94a3b8';
- ctx.font = '14px sans-serif';
- ctx.fillText('暂无扫描样本,请先执行 360° 扫描', 20, 30);
- return;
- }
- const rowH = this.cellH + this.captionH;
- const startCol = Math.floor((-this.offsetX / this.scale) / this.cellW);
- const endCol = Math.ceil((w - this.offsetX) / this.scale / this.cellW);
- const startRow = Math.floor((-this.offsetY / this.scale) / rowH);
- const endRow = Math.ceil((h - this.offsetY) / this.scale / rowH);
- ctx.save();
- ctx.translate(this.offsetX, this.offsetY);
- ctx.scale(this.scale, this.scale);
- for (let r = Math.max(0, startRow); r <= Math.min(this.tilts.length - 1, endRow); r++) {
- for (let c = Math.max(0, startCol); c <= Math.min(this.pans.length - 1, endCol); c++) {
- const pan = this.pans[c];
- const tilt = this.tilts[r];
- const x = c * this.cellW;
- const y = r * rowH;
- const s = this.sampleMap.get(`${pan},${tilt}`);
- ctx.fillStyle = '#0f172a';
- ctx.fillRect(x, y, this.cellW, rowH);
- const img = this.images.get(`${pan},${tilt}`);
- if (img && img.complete && img.naturalWidth) {
- const sx = 0, sy = 0, sw = img.naturalWidth, sh = img.naturalHeight;
- const dw = this.cellW - 4;
- const dh = this.cellH - 4;
- const scale = Math.min(dw / sw, dh / sh);
- const iw = sw * scale;
- const ih = sh * scale;
- const ix = x + 2 + (dw - iw) / 2;
- const iy = y + 2 + (dh - ih) / 2;
- ctx.drawImage(img, ix, iy, iw, ih);
- } else {
- ctx.fillStyle = '#1e293b';
- ctx.fillRect(x + 2, y + 2, this.cellW - 4, this.cellH - 4);
- }
- ctx.fillStyle = '#cbd5e1';
- ctx.font = '11px sans-serif';
- ctx.textAlign = 'center';
- ctx.fillText(`P:${pan.toFixed(0)} T:${tilt.toFixed(0)}`, x + this.cellW / 2, y + this.cellH + 14);
- if (this.selectedPan === pan && this.selectedTilt === tilt) {
- ctx.strokeStyle = '#22c55e';
- ctx.lineWidth = 2;
- ctx.strokeRect(x + 1, y + 1, this.cellW - 2, rowH - 2);
- }
- }
- }
- ctx.restore();
- }
- }
- let sampleCanvas = null;
- async function loadSamples(groupId) {
- try {
- const data = await API.get(`/api/samples/${groupId}`);
- if (!sampleCanvas) {
- sampleCanvas = new SampleCanvas('sample-canvas', 'sample-grid-wrapper');
- }
- sampleCanvas.setSamples(data.samples || []);
- } catch (e) {
- log(`加载扫描样本失败: ${e.message}`);
- }
- }
- async function loadGroups() {
- try {
- const status = await API.get('/api/status');
- const select = document.getElementById('group-select');
- select.innerHTML = '';
- const gids = Object.keys(status.groups || {});
- gids.forEach(gid => {
- const opt = document.createElement('option');
- opt.value = gid;
- opt.textContent = gid;
- select.appendChild(opt);
- });
- if (gids.length === 0) {
- currentGroup = null;
- setStatus('未配置摄像头组');
- setControlsDisabled(true);
- return;
- }
- setControlsDisabled(false);
- if (gids.includes(currentGroup)) {
- select.value = currentGroup;
- } else {
- currentGroup = select.options[0].value;
- onGroupChange();
- }
- } catch (e) {
- log(`获取状态失败: ${e.message}`);
- }
- }
- function resetSampleZoom() {
- if (sampleCanvas) sampleCanvas.resetView();
- }
- function onGroupChange() {
- currentGroup = document.getElementById('group-select').value;
- selectedSampleEl = null;
- tempPreview = null;
- setSelectedPreview(null);
- resetSampleZoom();
- loadSamples(currentGroup);
- renderVideos(currentGroup);
- loadPoints(currentGroup);
- }
- function renderVideos(groupId) {
- const grid = document.getElementById('video-grid');
- grid.innerHTML = '';
- ['panorama', 'ptz'].forEach(cam => {
- const box = document.createElement('div');
- box.className = 'video-box';
- const title = document.createElement('div');
- title.className = 'title';
- title.textContent = `${cam} - ${groupId}`;
- const img = document.createElement('img');
- img.src = `/api/live/${cam}/${groupId}?marked=1&t=${Date.now()}`;
- img.alt = cam;
- box.appendChild(title);
- box.appendChild(img);
- grid.appendChild(box);
- });
- }
- async function loadPoints(groupId) {
- try {
- const data = await API.get(`/api/points/${groupId}`);
- const ul = document.getElementById('points');
- ul.innerHTML = '';
- data.points.forEach(p => {
- const li = document.createElement('li');
- const span = document.createElement('span');
- span.textContent = `P:${p.pan.toFixed(0)} T:${p.tilt.toFixed(0)}`;
- const previewBtn = document.createElement('button');
- previewBtn.textContent = '预览';
- previewBtn.onclick = async () => {
- document.getElementById('inp-pan').value = p.pan.toFixed(2);
- document.getElementById('inp-tilt').value = p.tilt.toFixed(2);
- document.getElementById('inp-zoom').value = p.zoom;
- await runPreview(groupId, p.pan, p.tilt, p.zoom, p.id);
- };
- const delBtn = document.createElement('button');
- delBtn.dataset.id = String(p.id);
- delBtn.textContent = '删除';
- delBtn.onclick = async () => {
- if (!currentGroup) {
- log('未选择摄像头组');
- return;
- }
- if (!confirm('确定删除该扫描点?')) return;
- delBtn.disabled = true;
- try {
- await API.del(`/api/points/${groupId}/${p.id}`);
- loadPoints(groupId);
- } catch (e) {
- log(`删除失败: ${e.message}`);
- delBtn.disabled = false;
- }
- };
- li.appendChild(span);
- li.appendChild(previewBtn);
- li.appendChild(delBtn);
- ul.appendChild(li);
- });
- } catch (e) {
- log(`加载扫描点失败: ${e.message}`);
- }
- }
- async function updateStatus() {
- if (!currentGroup) return;
- try {
- const status = await API.get('/api/status');
- const g = status.groups[currentGroup];
- if (g) {
- setStatus(g.polling_state);
- }
- } catch (e) {
- // ignore
- }
- }
- document.getElementById('group-select').addEventListener('change', onGroupChange);
- document.getElementById('btn-scan').addEventListener('click', async () => {
- if (!currentGroup) {
- log('未选择摄像头组');
- return;
- }
- if (scanPollInterval) return;
- const scannedGroup = currentGroup;
- const scanBtn = document.getElementById('btn-scan');
- scanBtn.disabled = true;
- setStatus('扫描中...');
- try {
- await API.post(`/api/scan/${scannedGroup}`);
- log(`开始扫描: ${scannedGroup}`);
- scanPollInterval = setInterval(async () => {
- try {
- const prog = await API.get(`/api/scan/${scannedGroup}/progress`);
- const progress = prog.total > 0 ? (prog.current / prog.total) * 100 : 0;
- if (prog.state === 'done' || prog.state === 'failed' || progress >= 100) {
- clearInterval(scanPollInterval);
- scanPollInterval = null;
- if (!controlsGloballyDisabled) scanBtn.disabled = false;
- if (prog.state === 'done') {
- log('扫描完成');
- resetSampleZoom();
- loadSamples(scannedGroup);
- loadPoints(scannedGroup);
- } else if (prog.state === 'failed') {
- log(`扫描失败: ${prog.error || 'unknown'}`);
- }
- } else {
- setStatus(`扫描中... ${progress.toFixed(0)}%`);
- }
- } catch (e) {
- clearInterval(scanPollInterval);
- scanPollInterval = null;
- if (!controlsGloballyDisabled) scanBtn.disabled = false;
- setStatus('扫描失败');
- log(`扫描进度获取失败: ${e.message}`);
- }
- }, 1000);
- } catch (e) {
- log(`扫描失败: ${e.message}`);
- if (!controlsGloballyDisabled) scanBtn.disabled = false;
- setStatus('扫描失败');
- }
- });
- document.getElementById('btn-poll-start').addEventListener('click', async () => {
- if (!currentGroup) {
- log('未选择摄像头组');
- return;
- }
- await withDisabled('btn-poll-start', async () => {
- try {
- await API.post(`/api/poll/${currentGroup}/start`);
- log(`开始轮询: ${currentGroup}`);
- } catch (e) {
- log(`轮询启动失败: ${e.message}`);
- }
- });
- });
- document.getElementById('btn-poll-stop').addEventListener('click', async () => {
- if (!currentGroup) {
- log('未选择摄像头组');
- return;
- }
- await withDisabled('btn-poll-stop', async () => {
- try {
- await API.post(`/api/poll/${currentGroup}/stop`);
- log(`停止轮询: ${currentGroup}`);
- } catch (e) {
- log(`停止失败: ${e.message}`);
- }
- });
- });
- async function runPreview(groupId, pan, tilt, zoom, pointId = null) {
- const payload = { pan, tilt, zoom };
- const result = await API.post(`/api/preview/${groupId}`, payload);
- log(`预览位置: P=${pan.toFixed(1)} T=${tilt.toFixed(1)} Z=${zoom}`);
- if (result.snapshot_url) {
- log(`预览抓拍已保存: ${result.snapshot_path}`);
- // 预览抓拍显示在右侧,但不更新保存点图片
- setSelectedPreview(result.snapshot_url);
- tempPreview = { path: result.snapshot_path };
- }
- return result;
- }
- document.getElementById('btn-preview').addEventListener('click', async () => {
- if (!currentGroup) {
- log('未选择摄像头组');
- return;
- }
- let pan, tilt, zoom;
- try {
- pan = parseStrictFloat(document.getElementById('inp-pan').value, 'pan');
- tilt = parseStrictFloat(document.getElementById('inp-tilt').value, 'tilt');
- zoom = Number(document.getElementById('inp-zoom').value);
- } catch (e) {
- log(`错误:${e.message}`);
- return;
- }
- if (!Number.isInteger(zoom) || zoom < 1) {
- log('错误:zoom 必须是大于等于 1 的整数');
- return;
- }
- await withDisabled('btn-preview', async () => {
- try {
- await runPreview(currentGroup, pan, tilt, zoom);
- } catch (e) {
- log(`预览失败: ${e.message}`);
- }
- });
- });
- document.getElementById('btn-add').addEventListener('click', async () => {
- if (!currentGroup) {
- log('未选择摄像头组');
- return;
- }
- await withDisabled('btn-add', async () => {
- let pan, tilt, zoom, dwellTime;
- try {
- pan = parseStrictFloat(document.getElementById('inp-pan').value, 'pan');
- tilt = parseStrictFloat(document.getElementById('inp-tilt').value, 'tilt');
- zoom = Number(document.getElementById('inp-zoom').value);
- dwellTime = parseStrictFloat(document.getElementById('inp-dwell').value, '停留时间');
- } catch (e) {
- log(`错误:${e.message}`);
- return;
- }
- if (pan < 0 || pan > 360) {
- log('错误:pan 必须是 0-360 之间的有限数值');
- return;
- }
- if (tilt < -90 || tilt > 90) {
- log('错误:tilt 必须是 -90-90 之间的有限数值');
- return;
- }
- if (!Number.isInteger(zoom) || zoom < 1) {
- log('错误:zoom 必须是大于等于 1 的整数');
- return;
- }
- if (dwellTime <= 0) {
- log('错误:停留时间必须是大于 0 的有限数值');
- return;
- }
- const payload = { pan, tilt, zoom, dwell_time: dwellTime };
- if (tempPreview) {
- payload.preview_image = tempPreview.path;
- }
- try {
- await API.post(`/api/points/${currentGroup}`, payload);
- log('扫描点已保存');
- selectedSampleEl = null;
- tempPreview = null;
- setSelectedPreview(null);
- loadPoints(currentGroup);
- } catch (e) {
- log(`保存失败: ${e.message}`);
- }
- });
- });
- document.getElementById('btn-zoom-in').addEventListener('click', () => {
- if (sampleCanvas) {
- sampleCanvas.scale = Math.min(5.0, sampleCanvas.scale * 1.2);
- sampleCanvas.updateZoomLabel();
- sampleCanvas.draw();
- }
- });
- document.getElementById('btn-zoom-out').addEventListener('click', () => {
- if (sampleCanvas) {
- sampleCanvas.scale = Math.max(0.1, sampleCanvas.scale / 1.2);
- sampleCanvas.updateZoomLabel();
- sampleCanvas.draw();
- }
- });
- document.getElementById('btn-zoom-reset').addEventListener('click', () => {
- resetSampleZoom();
- });
- setControlsDisabled(true);
- loadGroups();
- setInterval(updateStatus, 2000);
|