require('dotenv').config(); const express = require('express'); const cors = require('cors'); const Influx = require('influx'); const app = express(); const PORT = process.env.PORT || 3000; // Simple log level implementation const LOG_LEVELS = { DEBUG: 0, INFO: 1, WARNING: 2, ERROR: 3 }; const currentLogLevel = LOG_LEVELS[process.env.LOG_LEVEL?.toUpperCase()] ?? LOG_LEVELS.INFO; const logger = { debug: (msg) => currentLogLevel <= LOG_LEVELS.DEBUG && console.log(`[${new Date().toISOString()}] DEBUG: ${msg}`), info: (msg) => currentLogLevel <= LOG_LEVELS.INFO && console.log(`[${new Date().toISOString()}] INFO: ${msg}`), warning: (msg) => currentLogLevel <= LOG_LEVELS.WARNING && console.warn(`[${new Date().toISOString()}] WARNING: ${msg}`), error: (msg, err) => { if (currentLogLevel <= LOG_LEVELS.ERROR) { console.error(`[${new Date().toISOString()}] ERROR: ${msg}`); if (err) console.error(err); } } }; app.use(cors()); app.use(express.static('public')); // Cache configuration const cache = { current: { data: null, updatedAt: null } }; const CACHE_TTL = 30000; // 30 seconds in milliseconds const influx = new Influx.InfluxDB({ host: process.env.INFLUX_HOST || 'localhost', port: process.env.INFLUX_PORT || 8086, database: process.env.INFLUX_DATABASE || 'homeassistant', username: process.env.INFLUX_USERNAME, password: process.env.INFLUX_PASSWORD, }); // Fetch current weather conditions from InfluxDB (internal function for caching) async function fetchCurrentData() { try { const measurements = [ 'temperature', 'humidity', 'pressure', 'wind_speed', 'wind_direction', 'precipitation', 'uv_index', 'solar_radiation', 'lightning_strike_count' ]; const results = {}; for (const measurement of measurements) { const query = ` SELECT last(value) as value FROM "${measurement}" WHERE entity_id =~ /tempest/ AND time > now() - 1h `; const data = await influx.query(query); if (data.length > 0) { results[measurement] = data[0].value; } } return results; } catch (error) { logger.error('Error fetching current data:', error); return {}; } } // Refresh cache periodically async function refreshCache() { try { cache.current.data = await fetchCurrentData(); cache.current.updatedAt = new Date(); logger.debug('Cache refreshed'); } catch (error) { logger.error('Cache refresh error:', error); } } // Get current weather conditions from cache app.get('/api/current', (req, res) => { if (cache.current.data === null) { return res.status(503).json({ error: 'Cache not ready' }); } res.json({ data: cache.current.data, updated_at: cache.current.updatedAt ? cache.current.updatedAt.toISOString() : null }); }); // Get historical data for charts app.get('/api/history/:measurement', async (req, res) => { try { const { measurement } = req.params; const hours = parseInt(req.query.hours) || 24; const query = ` SELECT mean(value) as value FROM "${measurement}" WHERE entity_id =~ /tempest/ AND time > now() - ${hours}h GROUP BY time(${hours > 24 ? '1h' : '10m'}) `; const data = await influx.query(query); const formatted = data.map(point => ({ time: point.time.toISOString(), value: point.value })); res.json(formatted); } catch (error) { logger.error('Error fetching historical data:', error); res.status(500).json({ error: 'Failed to fetch historical data' }); } }); // Health check app.get('/api/health', async (req, res) => { try { await influx.ping(5000); res.json({ status: 'ok', database: 'connected' }); } catch (error) { res.status(500).json({ status: 'error', database: 'disconnected' }); } }); // Initialize cache and start refresh interval (async () => { logger.info('Initializing cache...'); await refreshCache(); logger.info('Cache initialized'); // Start periodic refresh setInterval(refreshCache, CACHE_TTL); app.listen(PORT, () => { logger.info(`Weather dashboard server running on port ${PORT}`); logger.info(`Cache refresh interval: ${CACHE_TTL / 1000} seconds`); }); })();