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 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 --- const prependLog = (textarea, data) => { if (!textarea) return; const timestamp = new Date().toLocaleTimeString(); const formattedJson = JSON.stringify(data, null, 2); const newLog = `[${timestamp}]\n${formattedJson}\n\n---------------------------------\n\n`; textarea.value = newLog + textarea.value; }; 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 = ` Online`; connChip.className = 'cham_chip cham_chip-emerald'; } else { connChip.innerHTML = ` 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; productIdEl.textContent = selectedStation.product_id; } catch (e) { document.body.innerHTML = `