create sidebar
Browse filesFiles changed (2)
- README.md+9-5
- index.html+1700-19
12345678910---title: Undefinedemoji: 💻colorFrom: pinkcolorTo: redsdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314---title: undefinedcolorFrom: graycolorTo: blueemoji: 🐳sdk: staticpinned: falsetags:- deepsite-v3---# Welcome to your new DeepSite project!This project was created with [DeepSite](https://deepsite.hf.co).
12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Real-time RTLS Tracking</title><link rel="stylesheet" href="{{ url_for('static', filename='css/all.min.css') }}"><style>/* Màu nền chung */:root {--color-bg-main: #333;--color-bg-panel: #444;--color-bg-card: #555;--color-text: white;--color-accent: #4CAF50;--color-danger: #d9534f;--color-progress-bg: #666; /* Màu nền thanh tiến trình */--color-progress-fill: var(--color-accent); /* Màu lấp đầy thanh tiến trình */}body {margin: 0;padding: 0;background-color: var(--color-bg-main);color: var(--color-text);font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;display: flex;flex-direction: column;align-items: center;height: 100vh;}/* -------------------------------------- *//* Cấu trúc 3 cột chính *//* -------------------------------------- */.main-container {display: flex;justify-content: center;align-items: stretch;gap: 10px;padding: 10px 10px 0 10px;width: 100%;height: 98vh;max-width: none;box-sizing: border-box;}.panel {background-color: var(--color-bg-panel);border-radius: 12px;padding: 10px;box-sizing: border-box;box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);display: flex;flex-direction: column;overflow: hidden;}/* Tiêu đề cột */.panel-title {font-size: 1.2em;text-align: center;margin-bottom: 8px;color: var(--color-accent);}.panel-title2 {/* font-size: 1.0em; */margin-bottom: 8px;margin-top: 0px;color: var(--color-accent);}/* Cột Camera */.video-column {width: 22%;min-width: 180px;max-width: 22%;overflow-y: hidden; /* QUAN TRỌNG: Ngăn cuộn tổng thể ở đây *//* gap: 10px; Bỏ gap để dễ kiểm soát layout */padding-top: 5px;padding-bottom: 0; /* Đảm bảo không có padding dưới để nút vừa khít *//* CẤU HÌNH MỚI: Dùng flex để xếp chồng nội dung và nút */display: flex;flex-direction: column;}/* TẠO KHU VỰC CUỘN RIÊNG CHO CÁC VIDEO */.video-column-content {overflow-y: auto;/* flex-grow: 1; *//* padding: 0 5px 0 0; Padding phải để thanh cuộn không dính sát */}/* FIX: Layout Section - CĂN GIỮA THEO CHIỀU DỌC */.video-layout-section {width: 63%;padding: 10px;overflow-y: auto;/* justify-content: center; FIX: Căn giữa nội dung theo chiều dọc */align-items: center; /* Căn giữa nội dung theo chiều ngang */}/* Cột Controls - KHÔNG SỬA */.control-column {width: 15%;min-width: 160px;max-width: 15%;padding-top: 5px;}/* -------------------------------------- *//* Cột Camera (16:9 và Cuộn) - KHÔNG SỬA *//* -------------------------------------- */.video-box {position: relative;display: flex;flex-direction: column;align-items: center;background-color: var(--color-bg-card);border-radius: 8px;padding: 5px;margin-bottom: 8px;transition: transform 0.2s, box-shadow 0.2s;overflow: hidden;width: 100%;flex-shrink: 0;}/* Wrapper 16:9 */.video-aspect-ratio-container {width: 100%;padding-top: 56.25%;position: relative;}/* Tên Camera */.video-box h2 {position: absolute;top: 3px;left: 50%;transform: translateX(-50%);z-index: 12;padding: 2px 6px;font-size: 0.8em;color: var(--color-text);background-color: rgba(0, 0, 0, 0.5);border-radius: 4px;margin: 0;text-transform: uppercase;}/* Video element */.video-box video {position: absolute;top: 0;left: 0;width: 98%;height: 100%;border: 2px solid var(--color-accent);border-radius: 6px;background-color: black;display: block;}.video-controls {position: absolute;top: 0;left: 0;width: 100%;height: 100%;z-index: 10;display: flex;justify-content: center;align-items: center;}/* Nút Play/Stop - KHÔNG SỬA */.video-controls .play-control-button {position: relative;background-color: rgba(0, 0, 0, 0.7);border: 2px solid var(--color-accent);color: var(--color-text);font-size: 1.3em;padding: 7px 11px;border-radius: 50%;opacity: 0;transition: opacity 0.3s;cursor: pointer;}.video-box.stopped .play-control-button {opacity: 1;}.video-box.stopped .play-control-button i.fa-play {display: inline;}.video-box.stopped .play-control-button i.fa-stop {display: none;}.video-box:not(.stopped) .play-control-button i.fa-play {display: none;}.video-box:not(.stopped) .play-control-button i.fa-stop {display: inline;}.video-box:hover .play-control-button {opacity: 1;}/* Nút Fullscreen - KHÔNG SỬA */.full-screen-btn {position: absolute;right: 10px;bottom: 10px;top: unset;transform: none;z-index: 11;opacity: 0;transition: opacity 0.3s;font-size: 1em !important;background-color: rgba(0, 0, 0, 0.7);border: none;padding: 5px 8px;border-radius: 50%;}.video-box:hover .full-screen-btn {opacity: 1;}/* -------------------------------------- *//* Layout Canvas (Giữ tỷ lệ) - KHÔNG SỬA *//* -------------------------------------- */.video-layout-section header {display: flex;justify-content: space-between;align-items: center;width: 100%;margin-bottom: 8px;}.video-layout-title {font-size: 1.5em;margin: 0;}#timestamp-display,#count-display {font-size: 0.8em;padding: 4px 7px;border-radius: 4px;background-color: rgba(255, 255, 255, 0.1);color: white;}/* Layout Wrapper chịu trách nhiệm giữ tỷ lệ */.layout-aspect-ratio-wrapper {width: 100%;padding-top: 57.72%;position: relative;margin-bottom: 8px;flex-shrink: 0;margin: 0 auto 8px auto;}/* Canvas chiếm trọn wrapper (tỷ lệ đã được cố định) */.layout-aspect-ratio-wrapper canvas {position: absolute;top: 0;left: 0;width: 100%;height: 100%;border: 1px solid var(--color-accent);}/* Style cho container nút cố định ở cuối cột Camera */.main-controls-fixed {/* Đảm bảo chiều rộng bằng với cột */width: 100%;padding: 10px; /* Thêm padding để nút không bị dính vào mép */box-sizing: border-box;background-color: var(--color-bg-panel); /* Màu nền giống cột */border-top: 1px solid #555; /* Đường phân cách *//* Giữ nguyên style flex cho nút bên trong */display: flex;justify-content: center;gap: 15px;flex-shrink: 0; /* Không co lại khi cuộn */}/* Tinh chỉnh lại style nút để phù hợp hơn với cột hẹp */.main-controls-fixed button {background-color: var(--color-accent);color: white;border: none;padding: 8px 15px;text-align: center;font-size: 0.9em;cursor: pointer;border-radius: 20px;transition: background-color 0.3s, transform 0.2s;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);}.main-controls-fixed button#stopAllBtn {background-color: var(--color-danger);}.main-controls-fixed button#stopAllBtn:hover {background-color: #c9302c;}.main-controls-fixed button:hover {background-color: #3e8e41;transform: scale(1.05);}/* Scrollbar (Đã tinh chỉnh: Nhỏ và Tinh tế hơn) *//* Bao gồm các khu vực cuộn cũ và khu vực 50/50 mới */.video-column-content::-webkit-scrollbar,.video-layout-section::-webkit-scrollbar,.scrollable-half::-webkit-scrollbar,#event-list-scroll::-webkit-scrollbar { /* THÊM .scrollable-half */width: 4px;height: 4px;}/* Thay đổi màu thumb (thanh kéo) */.video-column-content::-webkit-scrollbar-thumb,.video-layout-section::-webkit-scrollbar-thumb,.scrollable-half::-webkit-scrollbar-thumb,#event-list-scroll::-webkit-scrollbar { /* THÊM .scrollable-half */background: rgba(119, 119, 119, 0.2); /* Mặc định mờ */border-radius: 10px;}/* Thay đổi màu thumb khi hover */.video-column-content::-webkit-scrollbar-thumb:hover,.video-layout-section::-webkit-scrollbar-thumb:hover,.scrollable-half::-webkit-scrollbar-thumb:hover,#event-list-scroll::-webkit-scrollbar { /* THÊM .scrollable-half */background: rgba(153, 153, 153, 0.7); /* Rõ hơn khi hover */}/* Giữ track trong suốt */.video-column-content::-webkit-scrollbar-track,.video-layout-section::-webkit-scrollbar-track,.scrollable-half::-webkit-scrollbar-track,#event-list-scroll::-webkit-scrollbar { /* THÊM .scrollable-half */background: transparent;}/* CÁC STYLE CHO CONTROL COLUMN ĐƠN GIẢN HÓA */.tab-content { display: flex; flex-grow: 1; overflow-y: hidden; padding: 0; height: 100%; flex-direction: column; }.video-box2 {flex-grow: 1;min-height: 0;overflow: hidden; /* Quan trọng: Ngăn cuộn tổng thể ở đây */background-color: var(--color-bg-card);padding: 10px;border-radius: 8px;border: none;display: flex;flex-direction: column;gap: 10px; /* Khoảng cách giữa 2 khu vực 50/50 */}/* KHU VỰC 50/50 */.scrollable-half {height: 50%; /* Chia đôi không gian còn lại */min-height: 0; /* Cho phép flex item co lại mà vẫn giữ được cuộn */overflow-y: auto; /* CUỘN RIÊNG */padding-right: 5px; /* Thêm padding để cuộn không bị dính sát mép */box-sizing: border-box;background-color: var(--color-bg-card); /* Màu nền riêng cho mỗi phần */border-radius: 8px;padding: 8px;}/* Loại bỏ padding và background cho video-box2 nếu đã áp dụng cho scrollable-half */.control-column .video-box2 {padding: 0;background-color: transparent;border-radius: 0;}#personList { list-style: none; padding: 0; margin: 0;}.video-all-section { display: none !important; }/* ************************************** *//* STYLE CHO SYSTEM INFO (ĐÃ TINH CHỈNH) *//* ************************************** *//* Thêm đường viền hoặc nền nhẹ để phân tách 2 khu vực rõ ràng hơn */#tracking-content {border-bottom: 2px solid var(--color-bg-panel);margin-bottom: 10px;}/* Giảm padding cho khu vực scrollable, vì padding đã có trong .scrollable-half */.system-info {font-size: 0.9em;padding-top: 0;}.system-info p {font-size: 13px;/* margin: 8px 0; */margin-top: 12px;padding: 5px 0;border-top: 1px solid #444;}.system-info h4 {font-size: 1.1em;margin-top: 10px;margin-bottom: 5px;color: var(--color-accent);border-bottom: 1px dashed #777;padding-bottom: 3px;}/* Style cho Thanh tiến trình */.progress-bar-container {height: 10px;width: 100%;background-color: var(--color-progress-bg);border-radius: 3px;overflow: hidden;margin-top: 3px;display: flex;align-items: center;box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);}.progress-bar {height: 100%;background-color: var(--color-progress-fill);width: 0%;transition: width 0.5s ease-out;}.progress-bar.danger {background-color: var(--color-danger);}/* Cấu trúc cho các dòng không có progress bar */.system-info p:not(:has(.progress-bar-container)) {display: flex;justify-content: space-between;align-items: center;}/* --- VỊ TRÍ MỚI: Thêm vào cuối thẻ <style> --- *//* Cấu trúc cho Event Panel */.video-container {/* height: 74vh; */flex-direction: column;display: flex;width: 100%;}.event-container {background-color: var(--color-bg-card);border-radius: 12px;padding: 10px;box-sizing: border-box;box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);display: flex;flex-direction: column;overflow: hidden;height: 25vh;width: 100%;flex-grow: 1;}/* Event List */#event-list-scroll {flex-grow: 1;overflow-y: auto; /* CUỘN CHO DANH SÁCH CẢNH BÁO */padding-right: 5px;margin-top: 5px;}#event-list {list-style: none;padding: 0;margin: 0;}/* Vị trí cũ: .event-item */.event-item {padding: 6px 8px;margin-top: 1px;margin-bottom: 4px;border-radius: 6px;font-size: 0.9em;transition: background-color 0.3s;/* 📌 SỬA ĐỔI: BỐ CỤC CHÍNH (Một dòng ngang) */display: flex;flex-direction: row; /* Xếp ngang (Mặc định, nhưng ghi rõ) */align-items: center; /* Căn giữa theo chiều dọc */line-height: 1.3;/* width: 100%; Chiếm hết chiều ngang *//* NGĂN CHẶN TOÀN BỘ NỘI DUNG CUỘN XUỐNG DÒNG */white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}.alert-message {flex-shrink: 1; /* Cho phép co lại nếu cần */margin-right: 10px;overflow: hidden;text-overflow: ellipsis;/* Giữ lại white-space: nowrap */}.status-icon {margin-right: 8px;}.person-id, .status-text {flex-shrink: 0; /* Đảm bảo Person ID và Status không bao giờ bị cắt/ẩn */font-weight: bold;margin-right: 25px;}/* 📌 CÁC THÔNG TIN THỜI GIAN/THỜI LƯỢNG (Phải luôn hiển thị) */.alert-time, .alert-duration {flex-shrink: 0; /* KHÔNG BAO GIỜ CHO PHÉP CO */margin-left: 5px;font-size: 0.8em;color: #ccc;}/* Đảm bảo thời gian không bị co lại */.alert-time, .alert-duration {flex-shrink: 0;margin-left: 10px;}/* Màu cho cảnh báo DEPARTED */.event-item.departed {background-color: rgba(217, 83, 79, 0.2); /* Đỏ nhạt */border-left: 5px solid var(--color-danger);}/* Màu cho thông báo RETURNED */.event-item.returned {background-color: rgba(76, 175, 80, 0.2); /* Xanh lá nhạt */border-left: 5px solid var(--color-accent);}.event-item.ongoing {background-color: rgba(255, 165, 0, 0.3); /* Nền cam nhạt */border-left: 5px solid orange; /* Đường viền cam */box-shadow: 0 0 5px orange; /* Hiệu ứng nhẹ */}@keyframes alert-flash {0% {background-color: var(--color-danger); /* Bắt đầu bằng màu đỏ đậm */opacity: 1;}50% {background-color: rgba(255, 255, 255, 0.2); /* Chuyển sang màu nền nhẹ */opacity: 0.9;}100% {background-color: rgba(217, 83, 79, 0.2); /* Quay về màu nền Alert thông thường */opacity: 1;}}/* 2. Áp dụng hiệu ứng và đảm bảo nó chạy hết và dừng lại */.event-item.new-alert {animation: alert-flash 0.2s ease-out 4; /* Chạy 1.5 giây và chỉ 1 lần */}</style></head><body><div class="main-container"><div class="panel video-column"><h3 class="panel-title">CAMERA FEEDS</h3><div class="video-column-content"><div class="video-box stopped" id="cam-box-d15"><h2>CAMERA D15</h2><div class="video-aspect-ratio-container"><video id="video-d15" muted></video><div class="video-controls"><button class="play-control-button" onclick="toggleVideo('d15', 'video-d15')"><i class="fas fa-play"></i><i class="fas fa-stop"></i></button><button class="full-screen-btn" onclick="toggleFullScreen('video-d15')"><i class="fas fa-expand"></i></button></div></div></div><div class="video-box stopped" id="cam-box-d19"><h2>CAMERA D19</h2><div class="video-aspect-ratio-container"><video id="video-d19" muted></video><div class="video-controls"><button class="play-control-button" onclick="toggleVideo('d19', 'video-d19')"><i class="fas fa-play"></i><i class="fas fa-stop"></i></button><button class="full-screen-btn" onclick="toggleFullScreen('video-d19')"><i class="fas fa-expand"></i></button></div></div></div><div class="video-box stopped" id="cam-box-d28"><h2>CAMERA D28</h2><div class="video-aspect-ratio-container"><video id="video-d28" muted></video><div class="video-controls"><button class="play-control-button" onclick="toggleVideo('d28', 'video-d28')"><i class="fas fa-play"></i><i class="fas fa-stop"></i></button><button class="full-screen-btn" onclick="toggleFullScreen('video-d28')"><i class="fas fa-expand"></i></button></div></div></div><div class="video-box stopped" id="cam-box-d25"><h2>CAMERA D25</h2><div class="video-aspect-ratio-container"><video id="video-d25" muted></video><div class="video-controls"><button class="play-control-button" onclick="toggleVideo('d25', 'video-d25')"><i class="fas fa-play"></i><i class="fas fa-stop"></i></button><button class="full-screen-btn" onclick="toggleFullScreen('video-d25')"><i class="fas fa-expand"></i></button></div></div></div><div class="video-box stopped" id="cam-box-d58"><h2>CAMERA D58</h2><div class="video-aspect-ratio-container"><video id="video-d58" muted></video><div class="video-controls"><button class="play-control-button" onclick="toggleVideo('d58', 'video-d58')"><i class="fas fa-play"></i><i class="fas fa-stop"></i></button><button class="full-screen-btn" onclick="toggleFullScreen('video-d58')"><i class="fas fa-expand"></i></button></div></div></div><div class="video-box stopped" id="cam-box-d39"><h2>CAMERA D39</h2><div class="video-aspect-ratio-container"><video id="video-d39" muted></video><div class="video-controls"><button class="play-control-button" onclick="toggleVideo('d39', 'video-d39')"><i class="fas fa-play"></i><i class="fas fa-stop"></i></button><button class="full-screen-btn" onclick="toggleFullScreen('video-d39')"><i class="fas fa-expand"></i></button></div></div></div></div><div class="main-controls-fixed"><button id="viewAllBtn" onclick="viewAllCameras()"><i class="fas fa-play"></i> View Cameras</button><button id="stopAllBtn" onclick="stopAllCameras()"><i class="fas fa-stop"></i> Stop Cameras</button></div></div><div class="panel video-layout-section"><div class="video-container"><header><h3 class="video-layout-title">LINE LAYOUT</h3><div><a id="count-display">--</a><a id="timestamp-display">--</a></div></header><div class="layout-aspect-ratio-wrapper"><canvas id="layoutCanvas" class="video-layout-canvas" width="1920" height="1280"></canvas></div></div><div class="event-container"><h4 class="panel-title2" style="margin-bottom: 0; color: white;">EVENTS / ALERTS</h4><div id="event-list-scroll"><ul id="event-list"></ul></div></div></div><div class="panel control-column"><h3 class="panel-title">CONTROLS / SYSTEM</h3><div id="control-content" class="tab-content active"><div class="video-box2"><div id="tracking-content" class="scrollable-half"><h4>Tracked Subjects</h4><select id="timeSelector" style="margin-bottom:10px; width: 100%; padding: 5px; border-radius: 5px; background-color: var(--color-bg-panel); color: var(--color-text); border: none;"><option value="1">1 minute ago</option><option value="3" selected>3 minutes ago</option><option value="5">5 minutes ago</option><option value="10">10 minutes ago</option><option value="30">30 minutes ago</option><option value="60">1 hour ago</option></select><button onclick="enableLiveMode()" style="margin-bottom:10px; background-color: var(--color-danger); border-radius: 5px; padding: 8px; width: 100%; border: none; color: white; cursor: pointer;">🔴 Live Mode</button><ul id="personList"></ul></div><div id="system-content" class="scrollable-half"><h4>System Health</h4><div class="system-info"><p>CPU Usage<span id="cpu-percent-text">-- %</span><div class="progress-bar-container"><div class="progress-bar" id="cpu-percent-bar"></div></div></p><p>RAM Usage<span id="ram-percent-text">-- %</span><div class="progress-bar-container"><div class="progress-bar" id="ram-percent-bar"></div></div></p><h4>GPU Metrics</h4><p>GPU Name<span id="gpu-name">--</span></p><!-- <p>GPU Usage<span id="gpu-percent-text">-- %</span><div class="progress-bar-container"><div class="progress-bar" id="gpu-percent-bar"></div></div></p> --><p>GPU Usage<span><span id="gpu-mem-used">-- GB</span> / <span id="gpu-mem-total">-- GB</span> (<span id="gpu-mem-percent-text">-- %</span>)</span><div class="progress-bar-container"><div class="progress-bar" id="gpu-mem-percent-bar"></div></div></p></div></div></div></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>
README.md+9-5
index.html+1700-19