// Use relative URL - works everywhere (localhost and production) const API_BASE = '/api'; let charts = {}; // Theme Management function initThemeSwitcher() { const savedTheme = localStorage.getItem('weather-theme') || 'static'; applyTheme(savedTheme); document.querySelectorAll('.theme-btn').forEach(btn => { btn.addEventListener('click', () => { const theme = btn.dataset.theme; applyTheme(theme); localStorage.setItem('weather-theme', theme); }); }); } function applyTheme(theme) { document.body.dataset.theme = theme; document.querySelectorAll('.theme-btn').forEach(btn => { btn.classList.toggle('active', btn.dataset.theme === theme); }); } function formatValue(value, precision = 1) { if (value === null || value === undefined) return '--'; return typeof value === 'number' ? value.toFixed(precision) : value; } function formatUptime(seconds) { if (!seconds) return '--'; const days = Math.floor(seconds / 86400); const hours = Math.floor((seconds % 86400) / 3600); const minutes = Math.floor((seconds % 3600) / 60); if (days > 0) { return `${days}d ${hours}h`; } else if (hours > 0) { return `${hours}h ${minutes}m`; } else { return `${minutes}m`; } } function formatTimestamp(isoString) { if (!isoString) return '--'; const date = new Date(isoString); const now = new Date(); const diffSeconds = Math.floor((now - date) / 1000); // Handle clock skew (server time ahead of client) if (diffSeconds < 0) return 'just now'; if (diffSeconds < 60) return `${diffSeconds}s ago`; if (diffSeconds < 3600) return `${Math.floor(diffSeconds / 60)}m ago`; if (diffSeconds < 86400) return `${Math.floor(diffSeconds / 3600)}h ago`; // For very old timestamps, show days const days = Math.floor(diffSeconds / 86400); if (days === 1) return 'yesterday'; if (days < 7) return `${days} days ago`; return date.toLocaleString(); } async function fetchHardwareStats() { try { const response = await fetch(`${API_BASE}/hardware/stats`); const result = await response.json(); const data = result.data || result; // Handle both new and old format // Hub stats if (data.hub) { document.getElementById('hub_uptime').textContent = formatUptime(data.hub.uptime); document.getElementById('hub_rssi').textContent = formatValue(data.hub.rssi, 0); document.getElementById('hub_firmware').textContent = data.hub.firmware || '--'; document.getElementById('hub_radio').textContent = data.hub.radio_version || '--'; } // Station stats if (data.station) { document.getElementById('station_uptime').textContent = formatUptime(data.station.uptime); document.getElementById('station_voltage').textContent = formatValue(data.station.voltage, 2); document.getElementById('station_rssi').textContent = formatValue(data.station.rssi, 0); document.getElementById('station_firmware').textContent = data.station.firmware || '--'; } // Update last updated timestamp const lastUpdatedEl = document.getElementById('last-updated'); if (lastUpdatedEl && result.updated_at) { lastUpdatedEl.textContent = formatTimestamp(result.updated_at); } } catch (error) { console.error('Error fetching hardware stats:', error); } } async function fetchHardwareHistory(device, field, hours = 6) { try { const response = await fetch(`${API_BASE}/hardware/history/${device}/${field}?hours=${hours}`); return await response.json(); } catch (error) { console.error(`Error fetching ${device} ${field} history:`, error); return []; } } function createChart(canvasId, label, data, color, unit = '') { const ctx = document.getElementById(canvasId).getContext('2d'); if (charts[canvasId]) { charts[canvasId].destroy(); } // Check if static theme is active const isStatic = document.body.dataset.theme === 'static'; charts[canvasId] = new Chart(ctx, { type: 'line', data: { labels: data.map(d => new Date(d.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })), datasets: [{ label: label, data: data.map(d => d.value), borderColor: isStatic ? '#fff' : color, backgroundColor: isStatic ? 'rgba(255, 255, 255, 0.1)' : color + '40', tension: 0.4, fill: true, pointRadius: 0, pointHoverRadius: isStatic ? 0 : 6, pointBackgroundColor: isStatic ? '#fff' : color, pointHoverBackgroundColor: isStatic ? '#fff' : color, pointBorderColor: isStatic ? '#fff' : '#fff', pointHoverBorderColor: isStatic ? '#fff' : '#fff', pointBorderWidth: 2, pointHoverBorderWidth: 2, borderWidth: 2 }] }, options: { responsive: true, maintainAspectRatio: true, aspectRatio: 2.5, animation: isStatic ? false : undefined, hover: { mode: isStatic ? null : 'nearest', intersect: true, animationDuration: 0 }, plugins: { legend: { display: false }, tooltip: { enabled: !isStatic, callbacks: { label: (context) => `${context.parsed.y.toFixed(2)} ${unit}` } } }, scales: { x: { display: true, grid: { display: false }, ticks: { maxTicksLimit: 8, color: isStatic ? '#fff' : undefined } }, y: { display: true, grid: { color: isStatic ? '#333' : '#f0f0f0' }, ticks: { color: isStatic ? '#fff' : undefined } } } } }); } async function updateCharts() { const [voltageData, rssiData] = await Promise.all([ fetchHardwareHistory('station', 'voltage', 6), fetchHardwareHistory('station', 'rssi_hub', 6) ]); createChart('voltageChart', 'Battery Voltage', voltageData, '#4facfe', 'V'); createChart('rssiChart', 'Signal Strength', rssiData, '#43e97b', 'dBm'); } async function init() { // Initialize theme switcher initThemeSwitcher(); await fetchHardwareStats(); await updateCharts(); // Update stats every 1 minute setInterval(fetchHardwareStats, 60000); // Update charts every 5 minutes setInterval(updateCharts, 300000); } init();