Spaces:
Paused
Paused
File size: 32,887 Bytes
8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 034681f 8ef2178 | 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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 | /* ============================================================================
๐ฅ FORGE INTELLIGENCE v3.0 - MAIN.JS (PRODUCTION FINAL)
Complete Frontend with Real-Time Socket.IO & Dynamic Dashboard Updates
Quantum ML Predictions, Anomaly Detection, AI Chat Interface
Author: Quantum AI Engineering Team
Date: 2025
License: MIT
Version: 3.0 (Production Final)
============================================================================ */
// ============================================================================
// 1. GLOBAL STATE & CONFIGURATION
// ============================================================================
const AppState = {
// Connection
socket: null,
isConnected: false,
// Temperature Data (Dynamic)
tempHistory: [],
currentTemp: 1420.0,
predictedTemp: 1420.0,
lastUpdate: null,
// Energy Data (Dynamic)
energyHistory: [],
currentEnergy: 450.0,
energySavings: 1.8,
annualROI: 2700,
// Anomaly Data (Dynamic)
anomalyRisk: 0.02,
isAnomaly: false,
pourReadiness: 85,
// Chat
chatHistory: [],
// Charts
charts: {},
// Configuration
maxDataPoints: 100,
updateIntervals: {
temperature: 5000,
prediction: 10000,
energy: 20000,
anomaly: 15000,
},
// UI
isDarkMode: true,
isMobile: window.innerWidth <= 768,
};
// API Endpoints
const API_ENDPOINTS = {
chat: '/api/chat',
chatStream: '/api/chat/stream',
predict: '/api/predict',
predictStream: '/api/predict/stream',
anomaly: '/api/anomaly',
energy: '/api/energy_status',
status: '/api/status',
};
// Streaming prediction connection
let predictionEventSource = null;
// ============================================================================
// 2. INITIALIZATION - DOCUMENT READY
// ============================================================================
document.addEventListener('DOMContentLoaded', () => {
console.log('๐ฑ Initializing Forge Intelligence v3.0...');
// Initialize Socket.IO
initializeSocket();
// Setup event listeners
setupEventListeners();
// Initialize charts
initializeCharts();
// Start live update intervals
startLiveUpdates();
console.log('โ
Forge Intelligence initialized successfully');
});
// ============================================================================
// 3. SOCKET.IO CONNECTION & REAL-TIME UPDATES
// ============================================================================
function initializeSocket() {
console.log('๐ Connecting to Socket.IO server...');
AppState.socket = io({
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 10,
});
// ===== CONNECTION EVENTS =====
AppState.socket.on('connect', handleConnect);
AppState.socket.on('disconnect', handleDisconnect);
AppState.socket.on('connect_error', handleConnectError);
// ===== DATA EVENTS =====
AppState.socket.on('temp_update', handleTempUpdate);
AppState.socket.on('system_status', handleSystemStatus);
AppState.socket.on('connection_status', handleConnectionStatus);
}
function handleConnect() {
console.log('โ
Connected to Forge Intelligence backend');
AppState.isConnected = true;
updateConnectionStatus(true);
AppState.socket.emit('request_status');
showNotification('Connected to Quantum ML Engine', 'success');
}
function handleDisconnect() {
console.log('โ Disconnected from backend');
AppState.isConnected = false;
updateConnectionStatus(false);
showNotification('Disconnected - Attempting to reconnect...', 'warning');
}
function handleConnectError(error) {
console.error('โ Connection error:', error);
showNotification('Connection error - Reconnecting...', 'danger');
}
// ===== REAL-TIME TEMPERATURE UPDATES =====
function handleTempUpdate(data) {
console.log('๐ Temperature update:', data);
const temp = parseFloat(data.temp);
const timestamp = data.timestamp;
const isAnomaly = data.anomaly || false;
const quantumRisk = parseFloat(data.quantum_risk) || 0;
// Update global state
AppState.currentTemp = temp;
AppState.lastUpdate = timestamp;
AppState.anomalyRisk = quantumRisk;
AppState.isAnomaly = isAnomaly;
// Keep history
AppState.tempHistory.push(temp);
if (AppState.tempHistory.length > AppState.maxDataPoints) {
AppState.tempHistory.shift();
}
// ๐ฅ LIVE DOM UPDATES
updateTemperatureDisplay(temp, timestamp);
updateTemperatureStatus(temp);
updateQuantumRiskMeter(quantumRisk);
updateAnomalyIndicator(isAnomaly, quantumRisk);
updateTemperatureChart();
// Alerts
if (isAnomaly || quantumRisk > 0.7) {
showQuantumAlert(temp, quantumRisk);
}
}
function handleSystemStatus(data) {
console.log('๐ System status:', data);
const clientsEl = document.getElementById('status-clients');
const modelsEl = document.getElementById('status-models');
const riskEl = document.getElementById('quantum-risk-display');
if (clientsEl) clientsEl.textContent = data.connected_clients || 0;
if (modelsEl) modelsEl.textContent = data.models_trained ? 'โ
Trained' : 'โณ Training';
if (riskEl) riskEl.textContent = (data.quantum_risk * 100).toFixed(1) + '%';
}
function handleConnectionStatus(data) {
console.log('๐ Connection status:', data.message);
}
// ============================================================================
// 4. TEMPERATURE DISPLAY UPDATES
// ============================================================================
function updateTemperatureDisplay(temp, timestamp) {
// Current temperature
const tempEl = document.getElementById('current-temp');
if (tempEl) {
const rounded = Math.round(temp * 10) / 10;
tempEl.textContent = rounded + 'ยฐC';
tempEl.style.animation = 'none';
setTimeout(() => {
tempEl.style.animation = 'pulse-glow 0.6s ease';
}, 10);
}
// Timestamp
const timeEl = document.getElementById('temp-timestamp');
if (timeEl) {
timeEl.textContent = timestamp || new Date().toLocaleTimeString();
}
}
function updateTemperatureStatus(temp) {
const statusEl = document.getElementById('temp-status');
if (!statusEl) return;
const OPTIMAL_LOW = 1410;
const OPTIMAL_HIGH = 1430;
const CRITICAL = 1480;
let status = '';
let color = '';
let emoji = '';
if (temp >= OPTIMAL_LOW && temp <= OPTIMAL_HIGH) {
status = 'OPTIMAL - READY TO POUR';
color = '#39FF14';
emoji = '๐ข';
} else if (temp > CRITICAL) {
status = 'CRITICAL - EMERGENCY';
color = '#DC143C';
emoji = '๐ด';
} else if (temp > OPTIMAL_HIGH) {
status = 'WARM - WAIT FOR COOLDOWN';
color = '#FFD700';
emoji = '๐ก';
} else {
status = 'COOL - WAIT FOR HEATING';
color = '#00BFFF';
emoji = '๐ต';
}
statusEl.innerHTML = `${emoji} ${status}`;
statusEl.style.color = color;
}
function updateQuantumRiskMeter(risk) {
const meterEl = document.getElementById('quantum-risk-meter');
if (meterEl) {
const percentage = Math.min(risk * 100, 100);
meterEl.style.width = percentage + '%';
if (risk > 0.7) {
meterEl.style.backgroundColor = '#DC143C';
} else if (risk > 0.4) {
meterEl.style.backgroundColor = '#FFD700';
} else {
meterEl.style.backgroundColor = '#39FF14';
}
}
// Risk percentage text
const riskTextEl = document.getElementById('quantum-risk');
if (riskTextEl) {
riskTextEl.textContent = (risk * 100).toFixed(1) + '%';
riskTextEl.style.color = risk > 0.7 ? '#DC143C' : risk > 0.4 ? '#FFD700' : '#39FF14';
}
}
function updateAnomalyIndicator(isAnomaly, quantumRisk) {
const indicator = document.getElementById('anomaly-indicator');
if (indicator) {
if (isAnomaly || quantumRisk > 0.7) {
indicator.innerHTML = '๐จ';
indicator.style.animation = 'pulse 0.5s infinite';
indicator.style.color = '#DC143C';
} else {
indicator.innerHTML = 'โ
';
indicator.style.animation = 'none';
indicator.style.color = '#39FF14';
}
}
}
// ============================================================================
// 5. PREDICTION DISPLAY UPDATES
// ============================================================================
async function fetchAndUpdatePredictions() {
if (!AppState.isConnected) return;
try {
console.log('๐ฎ Fetching quantum predictions...');
const response = await fetch(API_ENDPOINTS.predict, {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
});
if (!response.ok) throw new Error('Prediction failed');
const data = await response.json();
const predictedTemp = parseFloat(data.predicted_temp);
const confidence = parseFloat(data.confidence);
console.log(`๐ Predicted: ${predictedTemp}ยฐC (${(confidence*100).toFixed(1)}%)`);
// Update state
AppState.predictedTemp = predictedTemp;
// ๐ฅ UPDATE DOM
updatePredictionDisplay(predictedTemp, confidence);
calculateAndUpdatePourReadiness();
} catch (error) {
console.error('โ Prediction error:', error);
}
}
function updatePredictionDisplay(predictedTemp, confidence) {
// Next 30 min prediction
const predEl = document.getElementById('predicted-temp');
if (predEl) {
const rounded = Math.round(predictedTemp * 10) / 10;
predEl.textContent = rounded + 'ยฐC';
predEl.style.animation = 'pulse-glow 1s ease';
}
// Confidence
const confEl = document.getElementById('prediction-confidence');
if (confEl) {
confEl.textContent = (confidence * 100).toFixed(1) + '%';
}
// Prediction model
const modelEl = document.getElementById('prediction-model');
if (modelEl) {
modelEl.textContent = 'Quantum Superposition Ensemble';
}
}
function calculateAndUpdatePourReadiness() {
const OPTIMAL_LOW = 1410;
const OPTIMAL_HIGH = 1430;
let readiness = 0;
if (AppState.currentTemp >= OPTIMAL_LOW && AppState.currentTemp <= OPTIMAL_HIGH) {
readiness = 95; // Almost ready now
} else if (AppState.predictedTemp >= OPTIMAL_LOW && AppState.predictedTemp <= OPTIMAL_HIGH) {
readiness = 80; // Will be ready soon
} else if (AppState.currentTemp > OPTIMAL_HIGH) {
readiness = 50; // Wait for cooldown
} else {
readiness = 20; // Need heating
}
AppState.pourReadiness = readiness;
updatePourReadinessDisplay(readiness);
}
function updatePourReadinessDisplay(readiness) {
const el = document.getElementById('pour-readiness');
if (el) {
el.textContent = readiness + '%';
el.style.animation = 'pulse-glow 1s ease';
// Color coding
if (readiness >= 90) {
el.style.color = '#39FF14';
} else if (readiness >= 70) {
el.style.color = '#FFD700';
} else {
el.style.color = '#DC143C';
}
}
}
// ============================================================================
// 6. ENERGY DISPLAY UPDATES
// ============================================================================
async function fetchAndUpdateEnergy() {
if (!AppState.isConnected) return;
try {
console.log('โก Fetching energy status...');
const response = await fetch(API_ENDPOINTS.energy);
if (!response.ok) throw new Error('Energy fetch failed');
const data = await response.json();
const energy = parseFloat(data.current_energy);
const savings = parseFloat(data.savings_pct);
const roi = parseInt(data.roi_annual);
console.log(`โก Energy: ${energy} kWh | Savings: ${savings}%`);
// Update state
AppState.currentEnergy = energy;
AppState.energySavings = savings;
AppState.annualROI = roi;
// ๐ฅ UPDATE DOM
updateEnergyDisplay(energy, savings, roi);
} catch (error) {
console.error('โ Energy error:', error);
}
}
function updateEnergyDisplay(energy, savings, roi) {
// Current energy
const energyEl = document.getElementById('current-energy');
if (energyEl) {
energyEl.textContent = Math.round(energy) + ' kWh';
}
// Savings percentage
const savingsEl = document.getElementById('energy-savings');
if (savingsEl) {
savingsEl.textContent = savings.toFixed(1) + '%';
// Color coding
if (savings > 15) {
savingsEl.style.color = '#39FF14';
} else if (savings > 10) {
savingsEl.style.color = '#FFD700';
} else {
savingsEl.style.color = '#DC143C';
}
}
// Annual ROI
const roiEl = document.getElementById('annual-roi');
if (roiEl) {
roiEl.textContent = '$' + Math.round(roi) + 'K';
}
}
// ============================================================================
// 7. ANOMALY DETECTION UPDATES
// ============================================================================
async function fetchAndUpdateAnomalies() {
if (!AppState.isConnected) return;
try {
console.log('๐จ Checking for anomalies...');
const response = await fetch(API_ENDPOINTS.anomaly);
if (!response.ok) throw new Error('Anomaly check failed');
const data = await response.json();
const score = parseFloat(data.anomaly_score);
const isAnomaly = data.is_anomaly;
const risk = parseFloat(data.quantum_risk);
console.log(`๐จ Anomaly Risk: ${(risk*100).toFixed(1)}%`);
// Update state
AppState.anomalyRisk = risk;
AppState.isAnomaly = isAnomaly;
// ๐ฅ UPDATE DOM
updateAnomalyStatus(isAnomaly, score, risk);
} catch (error) {
console.error('โ Anomaly error:', error);
}
}
function updateAnomalyStatus(isAnomaly, score, risk) {
const statusEl = document.getElementById('anomaly-status');
if (statusEl) {
if (isAnomaly || risk > 0.7) {
statusEl.textContent = '๐จ ANOMALY DETECTED';
statusEl.style.color = '#DC143C';
} else {
statusEl.textContent = '๐ข NORMAL';
statusEl.style.color = '#39FF14';
}
}
}
// ============================================================================
// 8. CHART INITIALIZATION & UPDATES
// ============================================================================
function initializeCharts() {
console.log('๐ Initializing charts...');
initTemperatureChart();
initEnergyChart();
}
function initTemperatureChart() {
const ctx = document.getElementById('tempChart');
if (!ctx) return;
AppState.charts.tempChart = new Chart(ctx, {
type: 'line',
data: {
labels: Array.from({ length: AppState.maxDataPoints }, (_, i) => i),
datasets: [{
label: 'Temperature (ยฐC)',
data: AppState.tempHistory,
borderColor: '#FF4500',
backgroundColor: 'rgba(255, 69, 0, 0.1)',
borderWidth: 3,
tension: 0.4,
fill: true,
pointRadius: 0,
pointHoverRadius: 8,
pointBackgroundColor: '#FF4500',
pointBorderColor: '#FFD700',
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
interaction: { intersect: false, mode: 'index' },
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: 'rgba(0,0,0,0.9)',
titleColor: '#FF4500',
bodyColor: 'rgba(255,255,255,0.9)',
borderColor: '#FF4500',
borderWidth: 2,
}
},
scales: {
y: {
min: 1350,
max: 1550,
grid: { color: 'rgba(255, 255, 255, 0.1)' },
ticks: { color: 'rgba(248, 249, 250, 0.7)' }
},
x: {
grid: { display: false },
ticks: { color: 'rgba(248, 249, 250, 0.7)' }
}
}
}
});
console.log('โ
Temperature chart initialized');
}
function initEnergyChart() {
const ctx = document.getElementById('energyChart');
if (!ctx) return;
AppState.charts.energyChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [{
label: 'Energy Saved (kWh)',
data: [12, 15, 10, 18, 14, 24, 16],
backgroundColor: [
'rgba(255, 69, 0, 0.75)',
'rgba(255, 69, 0, 0.75)',
'rgba(255, 69, 0, 0.75)',
'rgba(255, 69, 0, 0.75)',
'rgba(255, 69, 0, 0.75)',
'rgba(255, 69, 0, 0.85)',
'rgba(255, 69, 0, 0.75)'
],
borderColor: '#FF4500',
borderWidth: 2,
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: { display: false },
},
scales: {
y: {
beginAtZero: true,
grid: { color: 'rgba(255, 255, 255, 0.1)' },
ticks: { color: 'rgba(248, 249, 250, 0.7)' }
},
x: {
grid: { display: false },
ticks: { color: 'rgba(248, 249, 250, 0.7)' }
}
}
}
});
console.log('โ
Energy chart initialized');
}
function updateTemperatureChart() {
if (AppState.charts.tempChart && AppState.tempHistory.length > 0) {
AppState.charts.tempChart.data.datasets[0].data = AppState.tempHistory.slice(-AppState.maxDataPoints);
AppState.charts.tempChart.update('none');
}
}
// ============================================================================
// 9. CHAT FUNCTIONALITY
// ============================================================================
async function sendChatMessage() {
const input = document.getElementById('chat-input');
const message = input.value.trim();
if (!message) {
showNotification('Please enter a message', 'warning');
return;
}
// Show user message
addChatMessage('user', message);
input.value = '';
// Disable send button
const sendBtn = document.querySelector('.btn-send');
if (sendBtn) {
sendBtn.disabled = true;
sendBtn.textContent = 'โณ Thinking...';
}
// Create streaming bot message container
const botMessageId = 'bot-msg-' + Date.now();
addStreamingMessage(botMessageId);
try {
console.log('๐ฌ Starting streaming chat...');
const response = await fetch('/api/chat/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: message })
});
if (!response.ok) throw new Error('Chat stream failed');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
if (data.chunk) {
fullResponse += data.chunk;
updateStreamingMessage(botMessageId, fullResponse);
}
if (data.done) {
console.log('โ
Stream complete');
}
} catch (e) {
// Skip invalid JSON
}
}
}
}
console.log(`๐ค Response: ${fullResponse}`);
} catch (error) {
console.error('โ Chat error:', error);
updateStreamingMessage(botMessageId, 'โ Error processing request. Please try again.');
showNotification('Failed to send message', 'danger');
} finally {
if (sendBtn) {
sendBtn.disabled = false;
sendBtn.textContent = 'Send';
}
input.focus();
}
}
function addStreamingMessage(messageId) {
const container = document.getElementById('chat-messages');
if (!container) return;
const messageDiv = document.createElement('div');
messageDiv.className = 'message agent';
messageDiv.id = messageId;
messageDiv.innerHTML = `<strong>๐ค Forge AI:</strong><br><span class="streaming-text"><span class="cursor">โ</span></span>`;
container.appendChild(messageDiv);
container.scrollTop = container.scrollHeight;
}
function updateStreamingMessage(messageId, text) {
const messageDiv = document.getElementById(messageId);
if (!messageDiv) return;
// Replace newlines with <br> for HTML display
const htmlText = text.replace(/\n/g, '<br>').replace(/โข/g, '•');
messageDiv.innerHTML = `<strong>๐ค Forge AI:</strong><br><span class="streaming-text">${htmlText}<span class="cursor">โ</span></span>`;
const container = document.getElementById('chat-messages');
if (container) {
container.scrollTop = container.scrollHeight;
}
}
function addChatMessage(type, text) {
const container = document.getElementById('chat-messages');
if (!container) return;
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
const sender = type === 'user' ? '๐ค You' : '๐ค Forge AI';
messageDiv.innerHTML = `<strong>${sender}:</strong><br>${text}`;
container.appendChild(messageDiv);
container.scrollTop = container.scrollHeight;
// Limit chat history
const messages = container.querySelectorAll('.message');
if (messages.length > 100) {
messages[0].remove();
}
}
function handleChatKeypress(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendChatMessage();
}
}
// ============================================================================
// 10. LIVE UPDATE INTERVALS
// ============================================================================
function startLiveUpdates() {
console.log('โฐ Starting live update intervals...');
// Start streaming predictions (SSE)
startStreamingPredictions();
// Energy: Every 20 seconds (fallback)
setInterval(() => {
if (AppState.isConnected) {
fetchAndUpdateEnergy();
}
}, AppState.updateIntervals.energy);
// Initial fetch
setTimeout(() => {
fetchAndUpdateEnergy();
}, 1000);
console.log('โ
Live updates started with streaming predictions');
}
function startStreamingPredictions() {
console.log('๐ฎ Starting streaming predictions...');
// Close existing connection if any
if (predictionEventSource) {
predictionEventSource.close();
}
predictionEventSource = new EventSource(API_ENDPOINTS.predictStream);
predictionEventSource.onopen = () => {
console.log('โ
Prediction stream connected');
showNotification('๐ฎ Real-time predictions active', 'success');
};
predictionEventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
// Update state
AppState.currentTemp = data.current_temp;
AppState.predictedTemp = data.predicted_temp;
AppState.currentEnergy = data.energy;
AppState.anomalyRisk = data.anomaly_risk;
AppState.isAnomaly = data.is_anomaly;
// Update UI with streaming data
updatePredictionDisplay(data.predicted_temp, data.confidence);
updateQuantumRiskMeter(data.anomaly_risk);
updateAnomalyIndicator(data.is_anomaly, data.anomaly_risk);
// Update anomaly status
updateAnomalyStatus(data.is_anomaly, data.anomaly_risk, data.anomaly_risk);
// Alerts for high risk
if (data.is_anomaly || data.anomaly_risk > 0.7) {
showQuantumAlert(data.current_temp, data.anomaly_risk);
}
console.log(`๐ Stream: Temp=${data.current_temp}ยฐC, Pred=${data.predicted_temp}ยฐC, Risk=${(data.anomaly_risk*100).toFixed(1)}%`);
} catch (e) {
console.error('โ Parse error:', e);
}
};
predictionEventSource.onerror = (error) => {
console.error('โ Prediction stream error:', error);
// Reconnect after 5 seconds
setTimeout(() => {
if (AppState.isConnected) {
console.log('๐ Reconnecting prediction stream...');
startStreamingPredictions();
}
}, 5000);
};
}
function stopStreamingPredictions() {
if (predictionEventSource) {
predictionEventSource.close();
predictionEventSource = null;
console.log('โน๏ธ Prediction stream stopped');
}
}
// ============================================================================
// 11. UI HELPER FUNCTIONS
// ============================================================================
function updateConnectionStatus(isConnected) {
const indicator = document.querySelector('.status-dot');
if (indicator) {
indicator.style.backgroundColor = isConnected ? '#39FF14' : '#DC143C';
}
const text = document.getElementById('status-text');
if (text) {
text.textContent = isConnected ? '๐ข ONLINE' : '๐ด OFFLINE';
}
}
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 120px;
right: 20px;
z-index: 9999;
min-width: 300px;
padding: 1rem 1.5rem;
background: rgba(26, 26, 46, 0.95);
border: 2px solid;
border-radius: 12px;
backdrop-filter: blur(10px);
animation: slideIn 0.3s ease;
font-family: 'Rajdhani', sans-serif;
`;
if (type === 'success') {
notification.style.borderColor = '#39FF14';
notification.style.color = '#39FF14';
} else if (type === 'danger') {
notification.style.borderColor = '#DC143C';
notification.style.color = '#DC143C';
} else if (type === 'warning') {
notification.style.borderColor = '#FFD700';
notification.style.color = '#FFD700';
} else {
notification.style.borderColor = '#00BFFF';
notification.style.color = '#00BFFF';
}
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 5000);
}
function showQuantumAlert(temp, risk) {
if (risk > 0.7) {
showNotification(`๐จ QUANTUM ALERT: ${temp}ยฐC (Risk: ${(risk*100).toFixed(1)}%)`, 'danger');
} else if (risk > 0.4) {
showNotification(`โ ๏ธ QUANTUM WARNING: Elevated risk detected`, 'warning');
}
}
// ============================================================================
// 12. EVENT LISTENERS
// ============================================================================
function setupEventListeners() {
console.log('๐ Setting up event listeners...');
// Chat
const chatInput = document.getElementById('chat-input');
if (chatInput) {
chatInput.addEventListener('keypress', handleChatKeypress);
}
const sendBtn = document.querySelector('.btn-send');
if (sendBtn) {
sendBtn.addEventListener('click', sendChatMessage);
}
// Window resize
window.addEventListener('resize', () => {
AppState.isMobile = window.innerWidth <= 768;
if (AppState.charts.tempChart) AppState.charts.tempChart.resize();
if (AppState.charts.energyChart) AppState.charts.energyChart.resize();
});
console.log('โ
Event listeners setup complete');
}
// ============================================================================
// 13. ACTION BUTTONS
// ============================================================================
function startMonitoring() {
console.log('โก Starting monitoring...');
showNotification('๐ฅ Real-time monitoring activated!', 'success');
addChatMessage('bot', 'Monitoring initiated. Temperature sensors calibrated. Ready for foundry operations.');
}
function activateAI() {
console.log('๐ค Activating AI...');
document.getElementById('chat-input').focus();
showNotification('AI Agent activated', 'success');
}
function checkPourReadiness() {
console.log('โณ Checking pour readiness...');
document.getElementById('chat-input').value = 'Should I pour now?';
sendChatMessage();
}
function checkAnomalies() {
console.log('๐ฎ Checking anomalies...');
fetchAndUpdateAnomalies();
document.getElementById('chat-input').value = 'Any anomalies detected?';
sendChatMessage();
}
function getEnergyStatus() {
console.log('โก Getting energy status...');
fetchAndUpdateEnergy();
document.getElementById('chat-input').value = 'What is our energy efficiency?';
sendChatMessage();
}
function exportReport() {
console.log('๐ Exporting report...');
showNotification('Report export feature coming soon', 'info');
}
// ============================================================================
// 14. EXPORT FOR GLOBAL ACCESS
// ============================================================================
window.AppState = AppState;
window.sendChatMessage = sendChatMessage;
window.startMonitoring = startMonitoring;
window.activateAI = activateAI;
window.checkPourReadiness = checkPourReadiness;
window.checkAnomalies = checkAnomalies;
window.getEnergyStatus = getEnergyStatus;
window.exportReport = exportReport;
window.handleChatKeypress = handleChatKeypress;
console.log('โ
Forge Intelligence v3.0 - Main.JS Loaded Successfully');
console.log('๐งฌ Quantum ML Engine: Ready');
console.log('๐ Real-time monitoring: Active');
console.log('๐ค AI Chat Assistant: Online');
|