SwapStation_WebApp/frontend/js/logs.js

139 lines
5.6 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
// --- CONFIGURATION ---
const SOCKET_URL = "http://10.10.1.183:5000";
const API_BASE = "http://10.10.1.183:5000/api";
// --- DOM ELEMENT REFERENCES ---
const stationNameEl = document.getElementById('station-name');
const stationLocationEl = document.getElementById('station-location');
const deviceIdEl = document.getElementById('device-id');
const productIdEl = document.getElementById('product-id');
const requestLogArea = document.getElementById('request-log-area');
const eventLogArea = document.getElementById('event-log-area');
const connChip = document.getElementById('connection-status-chip');
const clearReqBtn = document.getElementById('clear-req');
const clearEvtBtn = document.getElementById('clear-evt');
const clearAllBtn = document.getElementById('clear-all');
const refreshBtn = document.getElementById('refreshBtn');
const logoutBtn = document.getElementById('logout-btn');
// --- STATE ---
let selectedStation = null;
let socket;
let statusPollingInterval;
// --- HELPER FUNCTIONS --
const appendLog = (textarea, data, topic, timestampStr) => {
if (!textarea) return;
const timestamp = new Date(timestampStr).toLocaleTimeString();
const formattedJson = JSON.stringify(data, null, 2);
// Clean up the topic for better display
const topicParts = topic.split('/');
const shortTopic = topicParts.slice(-2).join('/'); // Gets the last two parts, e.g., "RPC/REQUEST" or ".../EVENTS"
const newLog = `[${timestamp}] - Topic: ${shortTopic}\n${formattedJson}\n\n---------------------------------\n\n`;
textarea.value += newLog;
textarea.scrollTop = textarea.scrollHeight;
};
const fetchRecentLogs = async () => {
try {
const response = await fetch(`${API_BASE}/logs/recent/${selectedStation.id}`);
if (!response.ok) throw new Error('Failed to fetch recent logs');
const logs = await response.json();
requestLogArea.value = '';
eventLogArea.value = '';
logs.forEach(log => {
if (log.topic.endsWith('EVENTS')) {
appendLog(eventLogArea, log.payload, log.topic, log.timestamp);
} else if (log.topic.endsWith('REQUEST')) {
appendLog(requestLogArea, log.payload, log.topic, log.timestamp);
}
});
console.log(`Successfully fetched and rendered ${logs.length} recent logs.`);
} catch (error) {
console.error(error);
}
};
// --- INITIALIZATION AND EVENT HANDLERS ---
function init() {
console.log("1. Starting initialization...");
// Step 1: Load the station from localStorage.
try {
const stationData = localStorage.getItem('selected_station');
console.log("2. Fetched from localStorage:", stationData);
if (!stationData) {
throw new Error('No station data found in localStorage.');
}
selectedStation = JSON.parse(stationData);
console.log("3. Parsed station data:", selectedStation);
if (!selectedStation || !selectedStation.id) {
throw new Error('Parsed station data is invalid or missing an ID.');
}
} catch (e) {
console.error("ERROR during station loading:", e);
// window.location.href = './station_selection.html'; // Temporarily disable redirect for debugging
return;
}
// Step 2: Populate the header.
console.log("4. Populating header...");
stationNameEl.textContent = selectedStation.name;
stationLocationEl.textContent = selectedStation.location;
deviceIdEl.textContent = selectedStation.id;
productIdEl.textContent = selectedStation.product_id;
console.log("5. Header populated.");
// Step 3: Set up button event listeners.
if(clearReqBtn) clearReqBtn.addEventListener('click', () => requestLogArea.value = '');
if(clearEvtBtn) clearEvtBtn.addEventListener('click', () => eventLogArea.value = '');
if(clearAllBtn) clearAllBtn.addEventListener('click', () => {
requestLogArea.value = '';
eventLogArea.value = '';
});
if(logoutBtn) logoutBtn.addEventListener('click', () => {
localStorage.clear();
window.location.href = 'index.html';
});
if(refreshBtn) refreshBtn.addEventListener('click', () => location.reload());
console.log("6. Event listeners attached.");
// Step 4: Fetch initial data now that everything is set up.
console.log("7. Calling fetchRecentLogs()...");
fetchRecentLogs();
// Step 5: Start WebSocket connection for live updates.
socket = io(SOCKET_URL);
socket.on('connect', () => {
console.log("Logs Page: Connected to WebSocket.");
socket.emit('join_station_room', { station_id: selectedStation.id });
});
socket.on('dashboard_update', (message) => {
const { stationId, topic, data } = message;
if (stationId !== selectedStation.id) return;
const now = new Date().toISOString();
if (topic.endsWith('EVENTS')) {
appendLog(eventLogArea, data, topic, now);
} else if (topic.endsWith('REQUEST')) {
appendLog(requestLogArea, data, topic, now);
}
});
}
// --- START THE APPLICATION ---
init();
});