refactor code
Browse files736 unmodified lines73773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700736 unmodified lines</div></div></div><script src="{{ url_for('static', filename='js/socket.io.js') }}"></script><script src="{{ url_for('static', filename='js/reader.js') }}"></script><script src="{{ url_for('static', filename='js/hls.min.js') }}"></script><script>let calibrationData = null;const CAMERA_SIZE = 15;// --- KHAI BÁO CÁC BIẾN (GIỮ NGUYÊN) ---// const WEBRTC_STREAMS = {// 'd15': "http://10.62.162.104:3003/d15/whep",// 'd19': "http://10.62.162.104:3003/d19/whep",// 'd25': "http://10.62.162.104:3003/d25/whep",// 'd50': "http://10.62.162.104:3003/D50/whep",// 'd58': "http://10.62.162.104:3003/d58/whep",// 'd39': "http://10.62.162.104:3003/D39/whep",// };const WEBRTC_STREAMS = {'d15': "http://10.62.162.104:3003/D15/whep",'d19': "http://10.62.162.104:3003/D19/whep",'d25': "http://10.62.162.104:3003/D25/whep",'d28': "http://10.62.162.104:3003/D28/whep",'d58': "http://10.62.162.104:3003/D58/whep",};const socket = io();const canvas = document.getElementById('layoutCanvas');const ctx = canvas.getContext('2d');const layoutImage = new Image();layoutImage.src = "{{ url_for('static', filename='cua5.png') }}";// const originalWidth = 1166;// const originalHeight = 673;const originalWidth = 1920;const originalHeight = 1280;const webrtcPlayers = {};const cameraIDs = Object.keys(WEBRTC_STREAMS);let liveMode = true;const timeSelector = document.getElementById('timeSelector');const timestampDisplay = document.getElementById('timestamp-display');const countDisplay = document.getElementById('count-display');const eventList = document.getElementById('event-list');const MAX_EVENTS = 100// ----------------------------------------function calculate_distance(p1, p2) {// Giả định p1 và p2 là mảng [x, y]if (!p1 || !p2 || p1.length < 2 || p2.length < 2) return 0;return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2));}// --- CÁC HÀM KHÁC (GIỮ NGUYÊN) ---const updateCanvasSize = () => {const wrapper = canvas.closest('.layout-aspect-ratio-wrapper');if (!wrapper) return;canvas.width = wrapper.clientWidth;canvas.height = wrapper.clientHeight;const currentWidth = canvas.width;const currentHeight = canvas.height;const widthRatio = currentWidth / originalWidth;const heightRatio = currentHeight / originalHeight;if (layoutImage.complete) {ctx.drawImage(layoutImage, 0, 0, canvas.width, canvas.height);}if (calibrationData) {drawCameras();drawRulers(ctx, currentWidth, currentHeight, widthRatio, heightRatio);}};function drawCameras() {// Đảm bảo dữ liệu đã được tảiif (!calibrationData) {console.warn("Dữ liệu hiệu chuẩn (calibrationData) chưa sẵn sàng.");return;}const currentWidth = canvas.width;const currentHeight = canvas.height;const widthRatio = currentWidth / originalWidth;const heightRatio = currentHeight / originalHeight;// --- KHAI BÁO THÔNG SỐ ICON ---const ICON_FONT = '900'; // Dùng Font Awesome solidconst ICON_SIZE = 25 * widthRatio; // Kích thước icon (lớn hơn CAMERA_SIZE cũ)const ICON_TEXT = '\uf030'; // Mã Unicode cho icon camera solid (fas fa-camera)// 🚨 LẶP TRỰC TIẾP QUA CÁC SENSOR TỪ FILE HIỆU CHUẨNcalibrationData.sensors.forEach(sensor => {ctx.font = `${ICON_FONT} ${ICON_SIZE}px "Font Awesome 5 Free"`; // Font Awesomectx.textAlign = 'center';ctx.textBaseline = 'middle';// --- CẤU HÌNH FONT CHO ID CAMERA ---ctx.fontId = `bold ${16 * widthRatio}px Arial`;ctx.textAlignId = 'left';ctx.textBaselineId = 'middle';const coord = sensor.coordinates;const x = coord.x * widthRatio;const y = currentHeight - (coord.y * heightRatio);// 1. VẼ BIỂU TƯỢNG CAMERA (ICON)// Đặt màu nền cho icon (Màu vàng)ctx.fillStyle = 'white';// Vẽ hình chữ nhật nhỏ làm nền (tùy chọn: giúp icon dễ nhìn hơn)ctx.fillRect(x - ICON_SIZE / 2, y - ICON_SIZE / 2, ICON_SIZE, ICON_SIZE);// Vẽ ICON (Màu icon là màu trắng)ctx.fillStyle = '#8e02d9';ctx.fillText(ICON_TEXT, x, y);// 2. VẼ ID CAMERA (VỊ TRÍ BÊN PHẢI ICON)// Đặt lại font và màu cho IDctx.font = ctx.fontId;ctx.textAlign = ctx.textAlignId;ctx.textBaseline = ctx.textBaselineId;// Vị trí ID: Lệch sang phải 5px so với mép phải của iconctx.fillText(sensor.id, x + (ICON_SIZE / 2) + 5, y);});}function drawRulers(ctx, currentWidth, currentHeight, widthRatio, heightRatio) {// const RULER_SIZE = 10; // Chiều rộng/cao của khu vực thước (tính bằng pixel)// const TICK_INTERVAL = 200; // Khoảng cách giữa các vạch lớn (theo đơn vị gốc: 1166x673)// const FINE_TICK_INTERVAL = 100; // Khoảng cách giữa các vạch nhỏ// const LABEL_INTERVAL = 200; // Khoảng cách giữa các nhãn số// // Cấu hình thước// ctx.lineWidth = 1;// ctx.strokeStyle = 'red';// ctx.fillStyle = 'red';// ctx.font = '8px Arial';// ctx.textAlign = 'center';// ctx.textBaseline = 'middle';// // Tắt Shadow (vì chúng ta đang vẽ thước)// ctx.shadowBlur = 0;// ctx.shadowColor = 'transparent';// // --- 1. VẼ THƯỚC NGANG (X-axis - TOP) ---// const yTop = 0; // Vị trí trên cùng của Canvas// for (let unit = 0; unit <= originalWidth; unit += FINE_TICK_INTERVAL) {// const x = unit * widthRatio;// let tickHeight = 3;// let drawLabel = false;// if (unit % TICK_INTERVAL === 0) {// tickHeight = 75// }// if (unit % LABEL_INTERVAL === 0) {// tickHeight = 5;// drawLabel = true;// }// // Vẽ vạch// ctx.beginPath();// ctx.moveTo(x, yTop);// ctx.lineTo(x, yTop + tickHeight);// ctx.stroke();// // Vẽ nhãn// if (drawLabel) {// ctx.fillText(unit, x, yTop + tickHeight + 5);// }// }// // --- 2. VẼ THƯỚC DỌC (Y-axis - LEFT) ---// const xLeft = 0; // Vị trí bên trái của Canvas// ctx.textAlign = 'left';// // Lưu ý: Y-axis của bạn được vẽ từ DƯỚI LÊN (currentHeight - y * ratio)// for (let unit = 0; unit <= originalHeight; unit += FINE_TICK_INTERVAL) {// const yOriginal = originalHeight - unit; // Chuyển đổi đơn vị gốc (0 là dưới cùng)// const y = yOriginal * heightRatio;// let tickWidth = 5;// let drawLabel = false;// if (unit % TICK_INTERVAL === 0) {// tickWidth = 10;// }// if (unit % LABEL_INTERVAL === 0) {// tickWidth = 15;// drawLabel = true;// }// // Vẽ vạch// ctx.beginPath();// ctx.moveTo(xLeft, y);// ctx.lineTo(xLeft + tickWidth, y);// ctx.stroke();// // Vẽ nhãn// if (drawLabel) {// ctx.textAlign = 'center';// ctx.fillText(unit, xLeft + tickWidth + 10, y);// ctx.textAlign = 'left';// }// }}// Hàm định dạng thời gian cho Event Listconst formatAlertTime = (isoTime) => {const date = new Date(isoTime);if (isNaN(date.getTime())) return "--";return date.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });}layoutImage.onload = updateCanvasSize;window.onresize = updateCanvasSize;document.addEventListener('DOMContentLoaded', updateCanvasSize);function toggleVideo(streamId, videoId) {const videoElement = document.getElementById(videoId);const videoBox = videoElement.closest('.video-box');const webrtcProxyUrl = WEBRTC_STREAMS[streamId];if (videoBox.classList.contains('stopped')) {console.log(`Bắt đầu kết nối WebRTC cho stream: ${streamId} qua proxy Flask tại ${webrtcProxyUrl}`);if (webrtcPlayers[streamId]) {webrtcPlayers[streamId].close();delete webrtcPlayers[streamId];videoElement.srcObject = null;}try {const reader = new MediaMTXWebRTCReader({url: new URL(webrtcProxyUrl),onError: (err) => {console.error(`Lỗi WebRTC cho ${streamId}:`, err);console.error('Chi tiết lỗi:', err.message, err.stack);stopWebRTCInternal(streamId, videoElement, videoBox);},onTrack: (evt) => {console.log(`Đã nhận track video cho ${streamId} thành công`);console.log('Tracks received:', evt.streams[0].getTracks());videoElement.srcObject = evt.streams[0];console.log('🔍 Reader sessionUrl:', reader.sessionUrl);videoElement.play().catch(e => console.error(`Lỗi play video ${streamId}:`, e));},});webrtcPlayers[streamId] = reader;videoBox.classList.remove('stopped');fetch(`/stream_control/${streamId}/start`);} catch (error) {console.error(`Lỗi khi khởi tạo WebRTCReader cho ${streamId}:`, error);alert(`Không thể khởi tạo WebRTC cho Camera ${streamId}. Vui lòng kiểm tra server MediaMTX và cấu hình proxy.`);stopWebRTCInternal(streamId, videoElement, videoBox);}} else {console.log(`Dừng kết nối WebRTC cho stream: ${streamId}`);stopWebRTCInternal(streamId, videoElement, videoBox);fetch(`/stream_control/${streamId}/stop`);}}function stopWebRTCInternal(streamId, videoElement, videoBox) {if (webrtcPlayers[streamId]) {webrtcPlayers[streamId].close();delete webrtcPlayers[streamId];}videoElement.srcObject = null;videoBox.classList.add('stopped');}function viewAllCameras() {cameraIDs.forEach(streamId => {const videoId = `video-${streamId}`;const videoBox = document.getElementById(videoId).closest('.video-box');if (videoBox.classList.contains('stopped')) {toggleVideo(streamId, videoId);}});}function stopAllCameras() {cameraIDs.forEach(streamId => {const videoId = `video-${streamId}`;const videoBox = document.getElementById(videoId).closest('.video-box');if (!videoBox.classList.contains('stopped')) {toggleVideo(streamId, videoId);}});}async function fetchPersonList() {const minutes = timeSelector.value;try {const res = await fetch(`/person_list?time=${minutes}`);const data = await res.json();const listElement = document.getElementById('personList');listElement.innerHTML = '';data.forEach(person => {const li = document.createElement('li');const minutes = Math.floor(person.duration / 60);const seconds = person.duration % 60;const formattedDuration = `${minutes}:${seconds.toString().padStart(2, '0')}`;li.textContent = `Person ${person.person_id} - ${formattedDuration}`;li.style.cursor = 'pointer';li.style.padding = '8px 10px';li.style.border = '1px solid #777';li.style.marginBottom = '5px';li.style.borderRadius = '5px';li.style.backgroundColor = '#666';li.style.transition = 'background-color 0.2s';li.onmouseover = () => li.style.backgroundColor = '#777';li.onmouseout = () => li.style.backgroundColor = '#666';li.addEventListener('click', () => showHistory(person.person_id));listElement.appendChild(li);});} catch (err) {console.error('Lỗi khi lấy danh sách person:', err);}}async function fetchPersonListLoop() {try {await fetchPersonList();} catch (err) {console.error('Lỗi khi gọi fetchPersonList:', err);} finally {setTimeout(fetchPersonListLoop, 15000);}}timeSelector.addEventListener('change', () => {fetchPersonList();});const formatTime = (isoTime) => {const t = new Date(isoTime);if (isNaN(t.getTime())) return "Invalid";return t.toTimeString().split(' ')[0];};async function showHistory(personId) {liveMode = false;try {const minutes = parseInt(timeSelector.value);const res = await fetch(`/history/${personId}?minutes=${minutes}`);const data = await res.json();if (!Array.isArray(data) || data.length === 0) return;updateCanvasSize();const currentWidth = canvas.width;const currentHeight = canvas.height;const widthRatio = currentWidth / originalWidth;const heightRatio = currentHeight / originalHeight;ctx.clearRect(0, 0, currentWidth, currentHeight);ctx.drawImage(layoutImage, 0, 0, currentWidth, currentHeight);ctx.beginPath();ctx.strokeStyle = 'red';ctx.lineWidth = 2 * widthRatio;const [first, ...rest] = data;ctx.moveTo(first.location[0] * widthRatio, currentHeight - first.location[1] * heightRatio);rest.forEach(point => {ctx.lineTo(point.location[0] * widthRatio, currentHeight - point.location[1] * heightRatio);});ctx.stroke();const importantPoints = [];importantPoints.push({ ...first, label: formatTime(first.timestamp) });const seenSlots = new Set();data.forEach(d => {const t = new Date(d.timestamp);if (isNaN(t.getTime())) return;const slot = `${t.getHours()}:${t.getMinutes()}`;if (!seenSlots.has(slot)) {seenSlots.add(slot);importantPoints.push({ ...d, label: formatTime(d.timestamp) });}});const last = data[data.length - 1];importantPoints.forEach(p => {const x = p.location[0] * widthRatio;const y = currentHeight - p.location[1] * heightRatio;ctx.beginPath();ctx.arc(x, y, 5 * widthRatio, 0, 2 * Math.PI);ctx.fillStyle = 'yellow';ctx.fill();ctx.fillStyle = 'blue';ctx.font = `${15 * widthRatio}px Arial`;ctx.fillText(p.label, x + 8, y - 4);});const x = last.location[0] * widthRatio;const y = currentHeight - last.location[1] * heightRatio;ctx.beginPath();ctx.arc(x, y, 8 * widthRatio, 0, 2 * Math.PI);ctx.fillStyle = 'red';ctx.fill();ctx.fillStyle = 'blue';ctx.font = `bold ${20 * widthRatio}px Arial`;ctx.fillText(`Person ${personId} - ${formatTime(last.timestamp)}`, x + 15, y - 15);} catch (err) {console.error('L���i khi lấy lịch sử:', err);}}// Thêm hàm này vào phần JavaScriptfunction drawAlertHistory(historyData, anchorLocation, departPoint, startTimeStr, endTimeStr, personId, isOngoing) {// Thước đoupdateCanvasSize();const currentWidth = canvas.width;const currentHeight = canvas.height;const widthRatio = currentWidth / originalWidth;const heightRatio = currentHeight / originalHeight;// Xóa Canvas và Vẽ lại Layout/Rulersctx.clearRect(0, 0, currentWidth, currentHeight);ctx.drawImage(layoutImage, 0, 0, currentWidth, currentHeight);drawRulers(ctx, currentWidth, currentHeight, widthRatio, heightRatio);// Chuyển mốc thời gian string sang Dateconst startTime = new Date(startTimeStr);const endTime = new Date(endTimeStr);// Vị trí Neo (Anchor)const anchorX = anchorLocation[0] * widthRatio;const anchorY = currentHeight - (anchorLocation[1] * heightRatio);// --- 1. VẼ ĐƯỜNG ĐI (BUFFER VÀ HIGHLIGHT) ---if (historyData.length > 0) {let prevX = null;let prevY = null;historyData.forEach(point => {const pointTime = new Date(point.timestamp);const x = point.location[0] * widthRatio;const y = currentHeight - (point.location[1] * heightRatio);// Kiểm tra xem điểm này có nằm TRONG khoảng thời gian cảnh báo không// Khoảng cảnh báo: [startTime, endTime]const isAlertSegment = (pointTime >= startTime && pointTime <= endTime);if (prevX !== null) {ctx.stroke(); // Kết thúc đường đi trước (đường cũ)ctx.beginPath();ctx.moveTo(prevX, prevY); // Bắt đầu từ điểm trước đóctx.lineTo(x, y); // Vẽ đến điểm hiện tạiif (isAlertSegment) {ctx.strokeStyle = 'orange'; // Đỏ cảnh báoctx.lineWidth = 4 * widthRatio; // Dày hơn} else {ctx.strokeStyle = 'green'; // Xám mờ (Buffer)ctx.lineWidth = 2 * widthRatio; // Mỏng}ctx.stroke();}// Lưu lại tọa độ hiện tại cho lần lặp tiếp theoprevX = x;prevY = y;});}// --- 2. VẼ VỊ TRÍ NEO VÀ ĐIỂM KÍCH HOẠT ---// Vị trí Neo (Hình vuông màu xám đậm)ctx.fillStyle = 'rgba(100, 100, 100, 0.8)';ctx.fillRect(anchorX - 10 * widthRatio, anchorY - 10 * heightRatio, 20 * widthRatio, 20 * heightRatio);ctx.fillStyle = 'blue';ctx.font = `${18 * widthRatio}px Arial`;ctx.fillText('NEO', anchorX, anchorY);// --- 3. VẼ ĐIỂM ĐẦU, ĐIỂM CUỐI VÀ CÁC MỐC THỜI GIAN (Lấy từ logic showHistory) ---if (historyData.length > 0) {const first = historyData[0];const last = historyData[historyData.length - 1];const importantPoints = [];// 1. Lưu điểm đầu tiênimportantPoints.push({...first,label: formatTime(first.timestamp),type: 'start'});// 2. Lọc các mốc thời gian quan trọng (ví dụ: mỗi phút)const seenSlots = new Set();historyData.forEach(d => {const t = new Date(d.timestamp);if (isNaN(t.getTime())) return;const slot = `${t.getHours()}:${t.getMinutes()}`;if (!seenSlots.has(slot)) {seenSlots.add(slot);// Chỉ thêm nếu không phải là điểm đầu/cuối và không quá gần NeoimportantPoints.push({...d,label: formatTime(d.timestamp),type: 'mid'});}});// Loại bỏ điểm trùng lặpimportantPoints.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));// --- VẼ CÁC ĐIỂM TRUNG GIAN/ĐẦU/CUỐI ---importantPoints.forEach(p => {const x = p.location[0] * widthRatio;const y = currentHeight - p.location[1] * heightRatio;// Cấu hình vẽ tùy theo loại điểmlet dotColor = 'yellow'; // Vàng cho điểm trung gianlet dotRadius = 5 * widthRatio;let labelColor = 'blue';if (p.type === 'start') {// Điểm bắt đầu (trong buffer)dotColor = 'rgb(0, 255, 255)'; // Xanh ngọc cho Start}// Vẽ hình trònctx.beginPath();ctx.arc(x, y, dotRadius, 0, 2 * Math.PI);ctx.fillStyle = dotColor;ctx.fill();// Vẽ nhãnctx.fillStyle = labelColor;ctx.font = `${15 * widthRatio}px Arial`;ctx.fillText(p.label, x + 8, y - 4);});// --- VẼ ĐIỂM CUỐI CÙNG (LAST POINT) ---const xLast = last.location[0] * widthRatio;const yLast = currentHeight - last.location[1] * heightRatio;// Hình tròn lớn cho điểm cuối cùng (tại thời điểm kết thúc cửa sổ điều tra)ctx.beginPath();ctx.arc(xLast, yLast, 10 * widthRatio, 0, 2 * Math.PI);ctx.fillStyle = 'red'; // Màu đỏ/cam tùy trạng tháictx.shadowColor = 'red';ctx.shadowBlur = 15;ctx.fill();ctx.shadowBlur = 0; // Tắt shadow// Nhãn điểm cuốictx.fillStyle = 'blue'; // Màu trắng cho nhãn điểm cuốictx.font = `bold ${20 * widthRatio}px Arial`;ctx.fillText(`END (${formatTime(last.timestamp)})`, xLast + 15, yLast - 15);}// Vị trí Kích hoạt Alert (Hình tròn lớn, tại thời điểm DEPARTED)const departX = departPoint[0] * widthRatio;const departY = currentHeight - (departPoint[1] * heightRatio);ctx.beginPath();ctx.arc(departX, departY, 10 * widthRatio, 0, 2 * Math.PI);ctx.fillStyle = 'orange';ctx.shadowColor = 'orange';ctx.shadowBlur = 20;ctx.fill();ctx.shadowBlur = 0;// Chú thích IDctx.fillStyle = 'red';ctx.font = `bold ${20 * widthRatio}px Arial`;ctx.fillText(`Alert`, departX + 20, departY + 5);}// Thay thế hàm showAlertDialog cũasync function showAlertTrack(alertData) {liveMode = false; // Tắt chế độ Live Mode// 1. Lấy dữ liệu thời gian và vị tríconst startTime = alertData.start_time;const endTime = alertData.end_time || new Date().toISOString(); // Sử dụng thời điểm hiện tại nếu đang Ongoingconst anchor = alertData.anchor_location;const departPoint = alertData.depart_location;// 2. Tải lịch sử di chuyển (bao gồm buffer 2 phút)try {// Gọi API /history/ đã được mở rộng để nhận start_time/end_timeconst historyRes = await fetch(`/history/${alertData.person_id}?start_time=${startTime}&end_time=${endTime}`);const historyData = await historyRes.json();if (!Array.isArray(historyData) || historyData.length === 0 || historyData.status === 'error') {console.warn(`Không tìm thấy lịch sử di chuyển cho Person ${alertData.person_id} trong cửa sổ điều tra.`);}// 3. VẼ TRỰC QUAN HÓA LỊCH SỬ CẢNH BÁOdrawAlertHistory(historyData.history_data || historyData, // Xử lý cả hai kiểu trả về nếu cóanchor,departPoint,startTime,endTime,alertData.person_id,alertData.is_ongoing);} catch (err) {console.error("Lỗi khi tải và vẽ lịch sử Alert:", err);}}function enableLiveMode() {liveMode = true;}socket.on('update_positions', (data) => {if (!liveMode) return;updateCanvasSize();const currentWidth = canvas.width;const currentHeight = canvas.height;const widthRatio = currentWidth / originalWidth;const heightRatio = currentHeight / originalHeight;ctx.clearRect(0, 0, currentWidth, currentHeight);ctx.drawImage(layoutImage, 0, 0, currentWidth, currentHeight);if (data.current_time) {const date = new Date(data.current_time);timestampDisplay.textContent = date.toLocaleString();}if (data.objects) {const len = data.objects.length;countDisplay.textContent = "People detected: " + len;}drawCameras();drawRulers(ctx, currentWidth, currentHeight, widthRatio, heightRatio);data.objects.forEach(obj => {const locations = obj.locations;const color = `rgb(${obj.color[0]}, ${obj.color[1]}, ${obj.color[2]})`;if (locations.length > 1) {ctx.beginPath();ctx.strokeStyle = color;ctx.lineWidth = 2 * widthRatio;ctx.moveTo(locations[0][0] * widthRatio, currentHeight - (locations[0][1] * heightRatio));for(let i = 1; i < locations.length; i++) {ctx.lineTo(locations[i][0] * widthRatio, currentHeight - (locations[i][1] * heightRatio));}ctx.stroke();}if (locations.length > 0) {const lastLocation = locations[locations.length - 1];const x = lastLocation[0] * widthRatio;const y = currentHeight - (lastLocation[1] * heightRatio);const color = `rgb(${obj.color[0]}, ${obj.color[1]}, ${obj.color[2]})`;// --- CẤU HÌNH HÌNH TRÒN ĐỒNG TÂM ---const R_OUTER = 12 * widthRatio; // Bán kính ngoài cùng (có shadow)const R_MIDDLE = 10 * widthRatio; // Bán kính giữa (màu trắng)const R_INNER = 6 * widthRatio; // Bán kính trung tâm (màu chủ đạo)// 1. Hình tròn ngoài cùng (Màu chủ đạo + Shadow)ctx.beginPath();ctx.arc(x, y, R_OUTER, 0, 2 * Math.PI);// Thêm hiệu ứng Shadowctx.shadowColor = color;ctx.shadowBlur = 5 * widthRatio; // Độ mờ của bóngctx.shadowOffsetX = 0;ctx.shadowOffsetY = 0;ctx.fillStyle = color; // Màu chủ đạoctx.fill();// Tắt Shadow cho các hình tròn còn lại và chữctx.shadowBlur = 0;// 2. Hình tròn ở giữa (Màu trắng)ctx.beginPath();ctx.arc(x, y, R_MIDDLE, 0, 2 * Math.PI);ctx.fillStyle = 'white';ctx.fill();// 3. Hình tròn trung tâm (Màu chủ đạo)ctx.beginPath();ctx.arc(x, y, R_INNER, 0, 2 * Math.PI);ctx.fillStyle = color; // Màu chủ đạoctx.fill();// --- VẼ CHỮ VÀ TRẠNG THÁI ---// IDctx.font = `bold ${20 * widthRatio}px Arial`;ctx.fillText(obj.id, x + R_OUTER + 3, y + 5);const idWidth = ctx.measureText(obj.id).width;// State (Để tránh bị lỗi nếu trạng thái chưa có)if (obj.state) {let stateColor;let stateText = `(${obj.state})`;// Xác định màu dựa trên trạng tháiswitch (obj.state) {case 'ALERTING':stateColor = 'rgb(255, 0, 0)'; // Đỏ sáng (Rất dễ thấy)break;case 'STATIONARY':stateColor = 'rgb(23, 184, 2)'; // Xanh lá (Làm việc/Đứng yên)break;case 'MOVING':stateColor = 'rgb(237, 171, 2)'; // Vàng/Vàng kim (Di chuyển)break;default:stateColor = 'rgb(200, 200, 200)'; // Xám (Mặc định)}// Đặt màu chữ cho trạng tháictx.fillStyle = stateColor;ctx.font = `bold ${18 * widthRatio}px Arial`;// Vị trí vẽ trạng thái (ngay sau ID)ctx.fillText(stateText, x + R_OUTER + 2 + idWidth + 5, y + 5);}}});});function toggleFullScreen(videoId) {const videoElement = document.getElementById(videoId);if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {if (videoElement.requestFullscreen) {videoElement.requestFullscreen();} else if (videoElement.mozRequestFullScreen) {videoElement.mozRequestFullScreen();} else if (videoElement.webkitRequestFullscreen) {videoElement.webkitRequestFullscreen();} else if (videoElement.msRequestFullscreen) {videoElement.msRequestFullscreen();}} else {if (document.exitFullscreen) {document.exitFullscreen();} else if (document.mozCancelFullScreen) {document.mozCancelFullScreen();} else if (document.webkitExitFullscreen) {document.webkitExitFullscreen();} else if (document.msExitFullscreen) {document.msExitFullscreen();}}}// --- LOGIC CẬP NHẬT HỆ THỐNG VÀ THANH PROGRESS (GIỮ NGUYÊN) ---let lastNetworkBytes = 0;const formatRate = (bytesPerSecond) => {if (bytesPerSecond < 1024) return `${bytesPerSecond.toFixed(2)} B/s`;const k = 1024;const sizes = ['KB/s', 'MB/s', 'GB/s'];const i = Math.floor(Math.log(bytesPerSecond) / Math.log(k));return parseFloat((bytesPerSecond / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];};function updateProgressBar(barId, textId, percent, dangerThreshold = 80) {const bar = document.getElementById(barId);const text = document.getElementById(textId);if (!bar || !text) return;text.textContent = `${percent} %`;bar.style.width = `${percent}%`;if (percent >= dangerThreshold) {bar.classList.add('danger');} else {bar.classList.remove('danger');}}async function loadCalibrationData() {console.log("Đang tải dữ liệu hiệu chuẩn...");try {// Thay đổi URL này thành endpoint API thực tế trả về file JSONconst res = await fetch('/static/calibration.json');if (!res.ok) {throw new Error(`Lỗi HTTP: ${res.status}`);}const data = await res.json();calibrationData = data;console.log("Đã tải dữ liệu hiệu chuẩn thành công.", calibrationData);updateCanvasSize(); // Vẽ lại canvas sau khi tải dữ liệu} catch (err) {console.error('Lỗi khi tải dữ liệu hiệu chuẩn:', err);}}async function loadInitialAlerts(limit=0) {try {const res = await fetch(`recent_alerts?minutes=60&limit=${limit}`);if (!res.ok) {console.error('Không thể tải lịch sử cảnh báo:', res.statusText);return;}const data = await res.json();// Đảo ngược danh sách nếu API không sắp xếp theo desc: true// Nếu API đã sắp xếp: data.reverse() không cần thiếtdata.reverse();data.forEach(alert => {// Tái sử dụng hàm hiển thị cảnh báodisplayAlert(alert, true); // true báo hiệu là tải ban đầu});// Giới hạn lại danh sách nếu có quá nhiều phần tử ban đầulimitEventList();} catch (error) {console.error('Lỗi khi tải lịch sử cảnh báo:', error);}}// VỊ TRÍ MỚI: Thêm hàm giới hạn danh sáchfunction limitEventList() {while (eventList.children.length > MAX_EVENTS) {eventList.removeChild(eventList.lastChild);}}// VỊ TRÍ MỚI: Hàm hiển thị cảnh báofunction displayAlert(data, isHistorical = false) {const li = document.createElement('li');li.classList.add('event-item'); // Bắt đầu với class cơ bảnli.style.cursor = 'pointer';// 📌 GỌI HÀM TRỰC QUAN HÓAli.addEventListener('click', () => showAlertTrack(data));if (eventList.firstChild) {eventList.insertBefore(li, eventList.firstChild);} else {eventList.appendChild(li);}let icon = '';let statusText = '';let timeInfo = '';let duration = '';// // --- 1. XỬ LÝ TRẠNG THÁI (DEPARTED và ONGOING) ---// if (data.is_ongoing) {// // Cảnh báo đang mở (Đang xảy ra)// li.classList.add('departed', 'ongoing'); // Thêm class 'ongoing' để highlight CSS// icon = '<i class="fas fa-exclamation-triangle fa-shake"></i>'; // Thêm hiệu ứng rung lắc// statusText = 'ONGOING ALERT';// timeInfo = `Start: ${formatAlertTime(data.start_time)}`;// duration = `Duration: ${Math.floor(data.duration_seconds / 60)}m ${Math.floor(data.duration_seconds % 60)}s`;// } else {// }// Cảnh báo đã kết thúc/Lịch sửli.classList.add('departed');icon = '<i class="fas fa-times-circle"></i>';statusText = 'ALERT';timeInfo = `-`;duration = `-`;if(data.end_time){timeInfo = `${formatAlertTime(data.start_time)} - ${formatAlertTime(data.end_time)}`;duration = `(Duration: ${Math.floor(data.duration_seconds / 60)}m ${Math.floor(data.duration_seconds % 60)}s)`;}else{timeInfo = `${formatAlertTime(data.start_time)}`;}// --- 2. XÂY DỰNG NỘI DUNG HTML ---const mainContent = `<span class="status-icon">${icon}</span><span class="status-text">${statusText}</span><span class="person-id">Person ${data.person_id}</span><span class="alert-message">${data.message}</span><span class="alert-time">${timeInfo}</span><span class="alert-duration">${duration}</span>`;// Gán nội dung vào lili.innerHTML = mainContent;// --- 4. CHÈN VÀO DANH SÁCH ---if (eventList.firstChild) {eventList.insertBefore(li, eventList.firstChild);} else {eventList.appendChild(li);}// Nếu không phải dữ liệu lịch sử, giới hạn danh sách và cuộn lênif (!isHistorical) {li.classList.add('new-alert');// Loại bỏ class sau 1.5 giây (để hiệu ứng không lặp lại)setTimeout(() => {li.classList.remove('new-alert');}, 1500);limitEventList();document.getElementById('event-list-scroll').scrollTop = 0;}}socket.on('system_update', (data) => {// 1. CPUupdateProgressBar('cpu-percent-bar', 'cpu-percent-text', data.cpu_percent);// 2. RAMupdateProgressBar('ram-percent-bar', 'ram-percent-text', data.ram_percent);// 3. GPUdocument.getElementById('gpu-name').textContent = data.gpu_name;updateProgressBar('gpu-percent-bar', 'gpu-percent-text', data.gpu_percent);// 4. GPU Memory (Cần tính phần trăm sử dụng)const gpuUsed = data.gpu_memory_used_gb;const gpuTotal = data.gpu_memory_total_gb;let gpuPercent = 0;if (gpuTotal > 0) {gpuPercent = ((gpuUsed / gpuTotal) * 100).toFixed(0);}document.getElementById('gpu-mem-used').textContent = `${gpuUsed.toFixed(2)} GB`;document.getElementById('gpu-mem-total').textContent = `${gpuTotal.toFixed(2)} GB`;// Cập nhật text % cho GPU Memorydocument.getElementById('gpu-mem-percent-text').textContent = `${gpuPercent} %`;updateProgressBar('gpu-mem-percent-bar', 'gpu-mem-percent-text', gpuPercent);});// socket.on('geofence_alert', (data) => {// displayAlert(data, false);// });socket.on('update_alerts_list', (data) => {// Xóa sạch danh sách cũ trên giao diệneventList.innerHTML = '';// Đảo ngược thứ tự trước khi hiển thị nếu cần (API đã sắp xếp mới nhất lên đầu)// Nếu API đã trả về [Mới nhất, ..., Cũ nhất]data.reverse();const lastIndex = data.length - 1;let currentIndex = 0;// Điền toàn bộ danh sách 10 cảnh báo mới vàodata.forEach(alert => {const isHistorical = (currentIndex != lastIndex);displayAlert(alert, isHistorical);currentIndex++;});// Cuộn lên trên cùng (hoặc không cuộn nếu danh sách đầy)document.getElementById('event-list-scroll').scrollTop = 0;});// -------------------------------------------------------------window.onload = () => {loadCalibrationData();fetchPersonListLoop();loadInitialAlerts(limit=10);};</script></body></html>736 unmodified lines737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806736 unmodified lines</div></div></div><script src="{{ url_for('static', filename='js/socket.io.js') }}">// Initialize socket listenersapp.socket.on('update_positions', UI.handlePositionUpdates);app.socket.on('system_update', System.handleSystemUpdate);app.socket.on('update_alerts_list', Alerts.handleAlertsUpdate);</script><script src="{{ url_for('static', filename='js/reader.js') }}"></script><script src="{{ url_for('static', filename='js/hls.min.js') }}"></script><script src="{{ url_for('static', filename='js/main.js') }}"></script><script src="{{ url_for('static', filename='js/ui.js') }}"></script><script src="{{ url_for('static', filename='js/alerts.js') }}"></script><script src="{{ url_for('static', filename='js/system.js') }}"></script><script src="{{ url_for('static', filename='js/webrtc.js') }}"></script><script>// Configuration constantsconst CONFIG = {WEBRTC_STREAMS: {'d15': "http://10.62.162.104:3003/D15/whep",'d19': "http://10.62.162.104:3003/D19/whep",'d25': "http://10.62.162.104:3003/D25/whep",'d28': "http://10.62.162.104:3003/D28/whep",'d58': "http://10.62.162.104:3003/D58/whep"},LAYOUT_IMAGE: "{{ url_for('static', filename='cua5.png') }}",ORIGINAL_WIDTH: 1920,ORIGINAL_HEIGHT: 1280,MAX_EVENTS: 100,CALIBRATION_FILE: '/static/calibration.json'};// Initialize core modulesconst app = {init: function() {this.socket = io();this.canvas = document.getElementById('layoutCanvas');this.ctx = this.canvas.getContext('2d');this.layoutImage = new Image();this.layoutImage.src = CONFIG.LAYOUT_IMAGE;this.webrtcPlayers = {};this.cameraIDs = Object.keys(CONFIG.WEBRTC_STREAMS);this.liveMode = true;// Initialize modulesUI.init(this);WebRTC.init(this);Alerts.init(this);System.init(this);// Load initial datathis.loadInitialData();},loadInitialData: function() {UI.loadCalibrationData(CONFIG.CALIBRATION_FILE);Alerts.loadInitialAlerts(10);System.startMonitoring();}};// Start the applicationdocument.addEventListener('DOMContentLoaded', function() {app.init();});</script></body></html>
index.html+54-948