315 lines
13 KiB
JavaScript
315 lines
13 KiB
JavaScript
// document.addEventListener('DOMContentLoaded', () => {
|
|
// // --- CONFIGURATION ---
|
|
// const SOCKET_URL = "http://192.168.1.12:5000";
|
|
// const API_BASE = "http://192.168.1.12:5000/api";
|
|
|
|
// // --- DOM ELEMENT REFERENCES ---
|
|
// const stationNameEl = document.getElementById('station-name');
|
|
// const stationLocationEl = document.getElementById('station-location');
|
|
// const deviceIdEl = document.getElementById('device-id');
|
|
// const lastUpdateEl = document.getElementById('last-update-status');
|
|
// const connChip = document.getElementById('connection-status-chip');
|
|
// const requestLogArea = document.getElementById('request-log-area');
|
|
// const eventLogArea = document.getElementById('event-log-area');
|
|
// const clearReqBtn = document.getElementById('clear-req');
|
|
// const clearEvtBtn = document.getElementById('clear-evt');
|
|
// const clearAllBtn = document.getElementById('clear-all');
|
|
// const refreshBtn = document.getElementById('refreshBtn');
|
|
// const downloadBtn = document.getElementById('downloadBtn');
|
|
// const logoutBtn = document.getElementById('logout-btn');
|
|
// const resetBtn = document.getElementById('station-reset-btn');
|
|
|
|
// // --- STATE ---
|
|
// let selectedStation = null;
|
|
// let socket;
|
|
// let statusPollingInterval;
|
|
|
|
// // --- HELPER FUNCTIONS ---
|
|
// // **MODIFIED** to accept the 'topic'
|
|
// const prependLog = (textarea, data, topic) => {
|
|
// if (!textarea) return;
|
|
// const timestamp = new Date().toLocaleTimeString();
|
|
// const formattedJson = JSON.stringify(data, null, 2);
|
|
// // **MODIFIED** to include the topic string
|
|
// const newLog = `[${timestamp}] - Topic: ${topic}\n${formattedJson}\n\n---------------------------------\n\n`;
|
|
// textarea.value = newLog + textarea.value;
|
|
// };
|
|
|
|
// // --- NEW: LOG PERSISTENCE HELPERS ---
|
|
// const saveLogs = () => {
|
|
// if (!selectedStation) return;
|
|
// sessionStorage.setItem(`request_logs_${selectedStation.id}`, requestLogArea.value);
|
|
// sessionStorage.setItem(`event_logs_${selectedStation.id}`, eventLogArea.value);
|
|
// };
|
|
|
|
// const loadLogs = () => {
|
|
// if (!selectedStation) return;
|
|
// requestLogArea.value = sessionStorage.getItem(`request_logs_${selectedStation.id}`) || '';
|
|
// eventLogArea.value = sessionStorage.getItem(`event_logs_${selectedStation.id}`) || '';
|
|
// };
|
|
|
|
// const sendCommand = (command, data = null) => {
|
|
// if (!selectedStation || !socket || !socket.connected) {
|
|
// console.error(`Cannot send command '${command}', not connected.`);
|
|
// return;
|
|
// }
|
|
// const payload = { station_id: selectedStation.id, command: command, data: data };
|
|
// socket.emit('rpc_request', payload);
|
|
// };
|
|
|
|
// const checkStationStatus = async () => {
|
|
// // ... (This function is unchanged)
|
|
// if (!selectedStation) return;
|
|
// try {
|
|
// const response = await fetch(`${API_BASE}/stations`);
|
|
// if (!response.ok) return;
|
|
// const stations = await response.json();
|
|
// const thisStation = stations.find(s => s.id === selectedStation.id);
|
|
// if (thisStation) {
|
|
// stationNameEl.textContent = thisStation.name;
|
|
// stationLocationEl.textContent = thisStation.location;
|
|
// if (thisStation.status === 'Online') {
|
|
// connChip.innerHTML = `<span class="h-2 w-2 rounded-full bg-emerald-400 animate-pulseDot"></span> Online`;
|
|
// connChip.className = 'cham_chip cham_chip-emerald';
|
|
// } else {
|
|
// connChip.innerHTML = `<span class="h-2 w-2 rounded-full bg-rose-500"></span> Offline`;
|
|
// connChip.className = 'cham_chip cham_chip-rose';
|
|
// }
|
|
// }
|
|
// } catch (error) { console.error("Failed to fetch station status:", error); }
|
|
// };
|
|
|
|
// // --- INITIALIZATION ---
|
|
// try {
|
|
// selectedStation = JSON.parse(localStorage.getItem('selected_station'));
|
|
// if (!selectedStation || !selectedStation.id) {
|
|
// throw new Error('No station selected. Please go back to the selection page.');
|
|
// }
|
|
// deviceIdEl.textContent = selectedStation.id;
|
|
// } catch (e) {
|
|
// document.body.innerHTML = `<div class="text-center p-8 text-rose-400">${e.message}<a href="./station_selection.html" class="underline ml-2">Go Back</a></div>`;
|
|
// return;
|
|
// }
|
|
|
|
// // --- SOCKET.IO CONNECTION ---
|
|
// socket = io(SOCKET_URL);
|
|
// socket.on('connect', () => {
|
|
// console.log("Connected to WebSocket for logs.");
|
|
// socket.emit('join_station_room', { station_id: selectedStation.id });
|
|
// });
|
|
|
|
// socket.on('dashboard_update', (message) => {
|
|
// const { stationId, topic, data } = message;
|
|
// if (stationId !== selectedStation.id) return;
|
|
|
|
// lastUpdateEl.textContent = 'Last Recv ' + new Date().toLocaleTimeString();
|
|
|
|
// // **MODIFIED** to pass the 'topic' to prependLog
|
|
// if (topic.endsWith('EVENTS')) {
|
|
// prependLog(eventLogArea, data, topic);
|
|
// } else if (topic.endsWith('REQUEST')) {
|
|
// prependLog(requestLogArea, data, topic);
|
|
// }
|
|
|
|
// // **NEW**: Save the logs after every update
|
|
// saveLogs();
|
|
// });
|
|
|
|
// // --- BUTTON EVENT LISTENERS ---
|
|
// // **MODIFIED** to clear sessionStorage
|
|
// if(clearReqBtn) clearReqBtn.addEventListener('click', () => {
|
|
// requestLogArea.value = '';
|
|
// sessionStorage.removeItem(`request_logs_${selectedStation.id}`);
|
|
// });
|
|
// if(clearEvtBtn) clearEvtBtn.addEventListener('click', () => {
|
|
// eventLogArea.value = '';
|
|
// sessionStorage.removeItem(`event_logs_${selectedStation.id}`);
|
|
// });
|
|
// if(clearAllBtn) clearAllBtn.addEventListener('click', () => {
|
|
// requestLogArea.value = '';
|
|
// eventLogArea.value = '';
|
|
// sessionStorage.removeItem(`request_logs_${selectedStation.id}`);
|
|
// sessionStorage.removeItem(`event_logs_${selectedStation.id}`);
|
|
// });
|
|
|
|
// // (The rest of your button listeners are unchanged)
|
|
// if(logoutBtn) logoutBtn.addEventListener('click', () => {
|
|
// localStorage.clear();
|
|
// window.location.href = 'index.html';
|
|
// });
|
|
// if(refreshBtn) refreshBtn.addEventListener('click', () => location.reload());
|
|
// if(resetBtn) resetBtn.addEventListener('click', () => {
|
|
// if (confirm('Are you sure you want to reset the station?')) {
|
|
// sendCommand('STATION_RESET');
|
|
// }
|
|
// });
|
|
|
|
// // --- STARTUP ---
|
|
// checkStationStatus();
|
|
// statusPollingInterval = setInterval(checkStationStatus, 10000);
|
|
// loadLogs(); // **NEW**: Load saved logs from this session on startup
|
|
// if (typeof lucide !== 'undefined') {
|
|
// lucide.createIcons();
|
|
// }
|
|
// });
|
|
|
|
|
|
|
|
|
|
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
// --- CONFIGURATION ---
|
|
const SOCKET_URL = "http://192.168.1.12:5000";
|
|
const API_BASE = "http://192.168.1.12: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 clearReqBtn = document.getElementById('clear-req');
|
|
const clearEvtBtn = document.getElementById('clear-evt');
|
|
const clearAllBtn = document.getElementById('clear-all');
|
|
const refreshBtn = document.getElementById('refreshBtn');
|
|
const resetBtn = document.getElementById('station-reset-btn');
|
|
const logoutBtn = document.getElementById('logout-btn');
|
|
|
|
// --- STATE ---
|
|
let selectedStation = null;
|
|
let socket;
|
|
|
|
// --- HELPER FUNCTIONS ---
|
|
|
|
const appendLog = (textarea, data, topic, timestampStr) => {
|
|
if (!textarea) return;
|
|
const timestamp = new Date(timestampStr).toLocaleTimeString();
|
|
const formattedJson = JSON.stringify(data, null, 2);
|
|
const newLog = `[${timestamp}] - Topic: ${topic}\n${formattedJson}\n\n---------------------------------\n\n`;
|
|
|
|
// Append the new log to the end of the existing text
|
|
textarea.value += newLog;
|
|
|
|
// Auto-scroll to the bottom to always show the newest log
|
|
textarea.scrollTop = textarea.scrollHeight;
|
|
};
|
|
|
|
const sendCommand = (command, data = null) => {
|
|
if (!selectedStation || !socket || !socket.connected) {
|
|
console.error(`Cannot send command '${command}', not connected.`);
|
|
return;
|
|
}
|
|
const payload = { station_id: selectedStation.id, command: command, data: data };
|
|
socket.emit('rpc_request', payload);
|
|
};
|
|
|
|
const checkStationStatus = async () => {
|
|
if (!selectedStation) return;
|
|
try {
|
|
const response = await fetch(`${API_BASE}/stations`);
|
|
if (!response.ok) return;
|
|
const stations = await response.json();
|
|
const thisStation = stations.find(s => s.id === selectedStation.id);
|
|
if (thisStation) {
|
|
stationNameEl.textContent = thisStation.name;
|
|
stationLocationEl.textContent = thisStation.location;
|
|
if (thisStation.status === 'Online') {
|
|
connChip.innerHTML = `<span class="h-2 w-2 rounded-full bg-emerald-400 animate-pulseDot"></span> Online`;
|
|
connChip.className = 'cham_chip cham_chip-emerald';
|
|
} else {
|
|
connChip.innerHTML = `<span class="h-2 w-2 rounded-full bg-rose-500"></span> Offline`;
|
|
connChip.className = 'cham_chip cham_chip-rose';
|
|
}
|
|
}
|
|
} catch (error) { console.error("Failed to fetch station status:", error); }
|
|
};
|
|
|
|
// --- NEW: Fetch recent logs from the database ---
|
|
const fetchAndRenderLogs = 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();
|
|
|
|
// Clear text areas before populating
|
|
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 ---
|
|
try {
|
|
selectedStation = JSON.parse(localStorage.getItem('selected_station'));
|
|
if (!selectedStation || !selectedStation.id) {
|
|
throw new Error('No station selected.');
|
|
}
|
|
deviceIdEl.textContent = selectedStation.id;
|
|
productIdEl.textContent = selectedStation.product_id;
|
|
} catch (e) {
|
|
document.body.innerHTML = `<div class="text-center p-8 text-rose-400">${e.message}<a href="./station_selection.html" class="underline ml-2">Go Back</a></div>`;
|
|
return;
|
|
}
|
|
|
|
// --- SOCKET.IO FOR LIVE UPDATES ---
|
|
socket = io(SOCKET_URL);
|
|
socket.on('connect', () => {
|
|
console.log("Connected to WebSocket for live logs.");
|
|
socket.emit('join_station_room', { station_id: selectedStation.id });
|
|
});
|
|
|
|
socket.on('dashboard_update', (message) => {
|
|
const { stationId, topic, data } = message;
|
|
if (stationId !== selectedStation.id) return;
|
|
|
|
// Just prepend live messages as they arrive
|
|
const now = new Date().toISOString();
|
|
if (topic.endsWith('EVENTS')) {
|
|
appendLog(eventLogArea, data, topic, now);
|
|
} else if (topic.endsWith('REQUEST')) {
|
|
appendLog(requestLogArea, data, topic, now);
|
|
}
|
|
});
|
|
|
|
// --- 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 = '';
|
|
});
|
|
|
|
// (The rest of your button listeners are unchanged)
|
|
if(logoutBtn) logoutBtn.addEventListener('click', () => {
|
|
localStorage.clear();
|
|
window.location.href = 'index.html';
|
|
});
|
|
if(refreshBtn) refreshBtn.addEventListener('click', () => location.reload());
|
|
if(resetBtn) resetBtn.addEventListener('click', () => {
|
|
if (confirm('Are you sure you want to reset the station?')) {
|
|
sendCommand('STATION_RESET');
|
|
}
|
|
});
|
|
|
|
// --- STARTUP ---
|
|
fetchAndRenderLogs(); // Fetch historical logs on page load
|
|
checkStationStatus();
|
|
|
|
if (typeof lucide !== 'undefined') {
|
|
lucide.createIcons();
|
|
}
|
|
}); |