Something went wrong. Try again.
Pretty website for a WeatherFlow Tempest using InfluxDB via UDP Broadcasts
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154require('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 implementationconst 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 configurationconst 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 periodicallyasync 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 cacheapp.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 chartsapp.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 checkapp.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`); });})();