Spaces:
Runtime error
Runtime error
File size: 10,255 Bytes
c3383a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | // ==============================================================================
// DriveSafe HUD Dashboard JavaScript
// Establishes real-time EventSource connection, draws Chart.js EKG, and manages HUD state.
// ==============================================================================
let earChart;
const maxChartPoints = 40;
let chartData = Array(maxChartPoints).fill(0.3);
let chartLabels = Array(maxChartPoints).fill("");
let renderedChatLogsCount = 0;
// --- Initialize Chart.js on DOM Load ---
document.addEventListener("DOMContentLoaded", () => {
const ctx = document.getElementById('earChart').getContext('2d');
// Create futuristic neon line chart
earChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartLabels,
datasets: [{
label: 'Eye Aspect Ratio (EAR)',
data: chartData,
borderColor: '#00bfff',
borderWidth: 2,
pointRadius: 0,
fill: true,
backgroundColor: 'rgba(0, 191, 255, 0.05)',
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false }
},
scales: {
x: { display: false },
y: {
min: 0.0,
max: 0.45,
grid: { color: 'rgba(255, 255, 255, 0.03)' },
ticks: {
color: '#64748b',
font: { family: 'Share Tech Mono', size: 10 }
}
}
},
animation: { duration: 0 } // Disable default anims for absolute high-speed rendering
}
});
// Initialize Telemetry EventSource listener
initTelemetry();
});
// --- Server-Sent Events (SSE) Telemetry Listener ---
function initTelemetry() {
const sse = new EventSource('/telemetry');
sse.onmessage = (event) => {
const data = JSON.parse(event.data);
// 1. Update Core Readouts
updateMetrics(data);
// 2. Shift EAR Graph Data
updateChart(data.ear);
// 3. Update Conversation Chat Logs
updateChat(data.chat_history);
// 4. Update HUD panel glowing states
updateStateOverlays(data.state, data.alert_message);
};
sse.onerror = (err) => {
console.error("SSE connection dropped:", err);
};
}
// --- Update Circular Gauge & Numeric Metrics ---
function updateMetrics(data) {
// Current numeric readout
document.getElementById("ear-val").innerText = data.ear.toFixed(2);
// Circular radial progress math
const gauge = document.getElementById("ear-gauge");
const radius = gauge.r.baseVal.value;
const circumference = 2 * Math.PI * radius;
// EAR bounds are normally between 0.10 (fully closed) and 0.35 (wide open)
// Normalize EAR to 0% - 100% range
let percentage = (data.ear - 0.10) / (0.35 - 0.10);
percentage = Math.max(0, Math.min(1, percentage)); // Clamp between 0 and 1
const offset = circumference - (percentage * circumference);
gauge.style.strokeDashoffset = offset;
// Change gauge color relative to EAR thresholds
const warnThreshold = 0.23;
const closedThreshold = 0.20;
if (data.ear <= closedThreshold) {
gauge.style.stroke = "var(--danger-color)";
} else if (data.ear <= warnThreshold) {
gauge.style.stroke = "var(--warn-color)";
} else {
gauge.style.stroke = "var(--safe-color)";
}
// Update Drowsiness Count
const countElement = document.getElementById("drowsiness-count");
countElement.innerText = data.drowsiness_count;
if (data.drowsiness_count > 0) {
countElement.style.color = "var(--danger-color)";
countElement.style.textShadow = "0 0 10px rgba(255, 40, 80, 0.4)";
} else {
countElement.style.color = "var(--safe-color)";
countElement.style.textShadow = "none";
}
// Update Engine FPS
document.getElementById("engine-fps").innerText = `${data.fps} FPS`;
// Update Tracking active button toggle
const trackingBtn = document.getElementById("toggle-tracking-btn");
const label = trackingBtn.querySelector("span");
if (data.detection_active) {
trackingBtn.classList.add("active");
label.innerText = "ACTIVE TRACKING";
} else {
trackingBtn.classList.remove("active");
label.innerText = "TRACKING PAUSED";
}
}
// --- EKG EAR Waveform Chart Shifter ---
function updateChart(newEar) {
chartData.push(newEar);
chartData.shift();
// Swap graph colors based on EAR values
if (newEar < 0.20) {
earChart.data.datasets[0].borderColor = "#ff2850";
earChart.data.datasets[0].backgroundColor = "rgba(255, 40, 80, 0.05)";
} else if (newEar < 0.23) {
earChart.data.datasets[0].borderColor = "#ffaa00";
earChart.data.datasets[0].backgroundColor = "rgba(255, 170, 0, 0.05)";
} else {
earChart.data.datasets[0].borderColor = "#00ff80";
earChart.data.datasets[0].backgroundColor = "rgba(0, 255, 128, 0.05)";
}
earChart.update();
}
// --- Dynamic Conversational Chat Logs renderer ---
function updateChat(history) {
if (history.length === renderedChatLogsCount) return;
const chatBox = document.getElementById("chat-box");
// Render only new logs added since last pass
for (let i = renderedChatLogsCount; i < history.length; i++) {
const log = history[i];
// System logs represent state announcements
if (log.speaker === "System") {
const systemDiv = document.createElement("div");
systemDiv.className = "chat-bubble system-bubble";
systemDiv.innerText = log.message;
chatBox.appendChild(systemDiv);
} else {
// User query
if (log.query) {
const userDiv = document.createElement("div");
userDiv.className = "chat-bubble driver-bubble";
userDiv.innerHTML = `<span class="bubble-label">Driver</span>${escapeHTML(log.query)}`;
chatBox.appendChild(userDiv);
}
// AI response
if (log.message) {
const aiDiv = document.createElement("div");
aiDiv.className = "chat-bubble slm-bubble";
aiDiv.innerHTML = `<span class="bubble-label">DriveSafe SLM</span>${escapeHTML(log.message)}`;
chatBox.appendChild(aiDiv);
}
}
}
renderedChatLogsCount = history.length;
// Auto-scroll chat box down with a short delay for fluid rendering
setTimeout(() => {
chatBox.scrollTop = chatBox.scrollHeight;
}, 50);
}
// --- Toggle HUD Glowing Cockpit States ---
function updateStateOverlays(state, alertMsg) {
const mainPanel = document.getElementById("main-panel");
const badge = document.getElementById("hud-state-badge");
const slmIndicator = document.getElementById("slm-indicator");
// Clean current state classes
mainPanel.className = "glass-panel video-panel";
if (state === "NORMAL") {
mainPanel.classList.add("state-normal");
badge.innerText = alertMsg ? alertMsg : "NORMAL";
badge.style.borderColor = "var(--safe-color)";
badge.style.color = "var(--safe-color)";
badge.style.boxShadow = "0 0 10px rgba(0, 255, 128, 0.2)";
slmIndicator.innerText = "SLM STANDBY";
slmIndicator.style.color = "var(--safe-color)";
}
else if (state === "CLOSED_3S") {
mainPanel.classList.add("state-warn");
badge.innerText = alertMsg ? alertMsg : "EYES CLOSED (3-5s)";
badge.style.borderColor = "var(--warn-color)";
badge.style.color = "var(--warn-color)";
badge.style.boxShadow = "0 0 15px rgba(255, 170, 0, 0.3)";
}
else if (state === "CLOSED_5S" || state === "WAITING_REST_RESPONSE" || state === "WAITING_SONG_RESPONSE") {
mainPanel.classList.add("state-danger");
badge.innerText = alertMsg ? alertMsg : "CRITICAL WARNING";
badge.style.borderColor = "var(--danger-color)";
badge.style.color = "var(--danger-color)";
badge.style.boxShadow = "0 0 25px rgba(255, 40, 80, 0.5)";
if (state.startsWith("WAITING")) {
slmIndicator.innerText = "SLM ACTIVE DIALOGUE";
slmIndicator.style.color = "var(--accent-color)";
}
}
else if (state === "PLAYING_MUSIC") {
mainPanel.classList.add("state-normal");
badge.innerText = "BEATS PLAYING";
badge.style.borderColor = "var(--accent-color)";
badge.style.color = "var(--accent-color)";
badge.style.boxShadow = "0 0 10px rgba(0, 191, 255, 0.2)";
}
}
// --- Control Desk AJAX REST Bridge ---
function toggleTracking() {
fetch('/api/toggle_detection', { method: 'POST' })
.then(response => response.json())
.then(data => {
console.log("Tracking toggled, active state:", data.detection_active);
})
.catch(err => console.error("Error toggling tracking:", err));
}
function triggerReset() {
fetch('/api/reset', { method: 'POST' })
.then(response => response.json())
.then(data => {
console.log("System reset:", data.message);
})
.catch(err => console.error("Error triggering reset:", err));
}
function triggerMusic() {
fetch('/api/trigger_music', { method: 'POST' })
.then(response => response.json())
.then(data => {
console.log("Music play request sent:", data.message);
})
.catch(err => console.error("Error playing energetic beats:", err));
}
// --- Helper Functions ---
function escapeHTML(str) {
return str.replace(/[&<>'"]/g,
tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);
}
|