Something went wrong. Try again.
Pretty website for a WeatherFlow Tempest using InfluxDB via UDP Broadcasts
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645import osimport threadingimport timeimport loggingfrom datetime import datetime, timezonefrom dotenv import load_dotenvfrom flask import Flask, jsonify, send_from_directoryfrom flask_cors import CORSfrom influxdb_client import InfluxDBClient
load_dotenv()
# Configure logginglog_level = os.getenv('LOG_LEVEL', 'INFO').upper()logging.basicConfig( level=getattr(logging, log_level, logging.INFO), format='[%(asctime)s] %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')logger = logging.getLogger(__name__)
app = Flask(__name__, static_folder='public')CORS(app)
# Cache configurationcache = { 'weather_stats': {'data': None, 'updated_at': None}, 'hardware_stats': {'data': None, 'updated_at': None}}CACHE_TTL = 30 # seconds
# InfluxDB 2.x clientinflux_host = os.getenv('INFLUX_HOST', 'localhost')influx_port = os.getenv('INFLUX_PORT', '8086')
# Build URL - check if host already includes protocolif influx_host.startswith('http://') or influx_host.startswith('https://'): influx_url = f"{influx_host}:{influx_port}"else: influx_url = f"http://{influx_host}:{influx_port}"
influx_client = InfluxDBClient( url=influx_url, token=os.getenv('INFLUX_TOKEN'), org=os.getenv('INFLUX_ORG'))query_api = influx_client.query_api()
BUCKET = os.getenv('INFLUX_BUCKET', 'homeassistant')
# WeatherFlow measurement patternsWEATHER_MEASUREMENT = 'ST-00196107_observation'STATUS_MEASUREMENT_HUB = 'HB-00196305_status'STATUS_MEASUREMENT_STATION = 'ST-00196107_status'RADIO_MEASUREMENT = 'HB-00196305_radio'
@app.route('/')def index(): response = send_from_directory('public', 'index.html') # Short cache for HTML - can update quickly when you deploy changes response.headers['Cache-Control'] = 'public, max-age=300' # 5 minutes return response
@app.route('/<path:path>')def static_files(path): response = send_from_directory('public', path) # Long cache for static assets (CSS, JS, images) # Use versioned filenames (style.v123.css) or query params (?v=123) to bust cache if path.endswith(('.css', '.js', '.png', '.jpg', '.jpeg', '.svg', '.ico', '.woff', '.woff2')): response.headers['Cache-Control'] = 'public, max-age=31536000, immutable' # 1 year else: response.headers['Cache-Control'] = 'public, max-age=300' # 5 minutes for other files return response
@app.route('/api/current')def get_current(): try: # Field mappings: API name -> InfluxDB field name field_mappings = { 'temperature': 'temperature_air', 'humidity': 'r-humidity', 'pressure': 'pressure_station', 'wind_speed': 'wind_speed', 'wind_direction': 'wind_direction', 'precipitation': 'rain_accumulation', 'uv_index': 'uv', 'solar_radiation': 'irradiance_sun', 'lightning_strike_count': 'strike_count' }
results = {}
query = f''' from(bucket: "{BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> last() '''
tables = query_api.query(query)
# Collect all fields from the query for table in tables: for record in table.records: field_name = record.get_field() # Map back to API field names for api_name, influx_field in field_mappings.items(): if field_name == influx_field: results[api_name] = record.get_value() break
return jsonify(results) except Exception as e: logger.error(f'Error fetching current data: {e}', exc_info=True) return jsonify({'error': 'Failed to fetch current weather data'}), 500
@app.route('/api/history/<measurement>')def get_history(measurement): try: from flask import request hours = int(request.args.get('hours', 24))
# Field mappings: API name -> InfluxDB field name field_mappings = { 'temperature': 'temperature_air', 'humidity': 'r-humidity', 'pressure': 'pressure_station', 'wind_speed': 'wind_speed', 'wind_direction': 'wind_direction', 'precipitation': 'rain_accumulation', 'uv_index': 'uv', 'solar_radiation': 'irradiance_sun', 'lightning_strike_count': 'strike_count' }
influx_field = field_mappings.get(measurement, measurement)
# Adaptive grouping: 10m for <24h, 1h for longer window = '1h' if hours > 24 else '10m'
query = f''' from(bucket: "{BUCKET}") |> range(start: -{hours}h) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "{influx_field}") |> aggregateWindow(every: {window}, fn: mean, createEmpty: false) '''
tables = query_api.query(query)
formatted = [] for table in tables: for record in table.records: formatted.append({ 'time': record.get_time().isoformat(), 'value': record.get_value() })
return jsonify(formatted) except Exception as e: logger.error(f'Error fetching historical data: {e}') return jsonify({'error': 'Failed to fetch historical data'}), 500
def fetch_weather_stats(): """Fetch current weather statistics from InfluxDB (internal function for caching)""" try: stats = {}
# Temperature (convert C to F) query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "temperature_air") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['temperature'] = round(record.get_value() * 9.0 / 5.0 + 32.0, 1) break
# Humidity query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "r-humidity") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['humidity'] = round(record.get_value(), 0) break
# Pressure (convert Pa to mb) query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "pressure_station") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['pressure'] = round(record.get_value() / 100.0, 1) break
# Wind Speed (convert m/s to mph) query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "wind_speed") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['wind_speed'] = round(record.get_value() * 2.237, 1) break
# Wind Direction (degrees) query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "wind_direction") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['wind_direction'] = round(record.get_value(), 0) break
# Wind Gust (24h max, convert m/s to mph) query = f''' from(bucket: "{BUCKET}") |> range(start: -24h) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "wind_gust") |> max() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['wind_gust_24h'] = round(record.get_value() * 2.237, 1) break
# Wind Gust (all time max, convert m/s to mph) query = f''' from(bucket: "{BUCKET}") |> range(start: -365d) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "wind_gust") |> max() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['wind_gust_max'] = round(record.get_value() * 2.237, 1) break
# Solar Radiation query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "irradiance_sun") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['solar_radiation'] = round(record.get_value(), 0) break
# UV Index query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "uv") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['uv'] = round(record.get_value(), 1) break
# Precipitation (24h accumulation, convert mm to inches) query = f''' from(bucket: "{BUCKET}") |> range(start: -24h) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "rain_accumulation") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['precipitation_24h'] = round(record.get_value() / 25.4, 2) break
return stats except Exception as e: logger.error(f'Error fetching weather stats: {e}') return {}
def fetch_hardware_stats(): """Fetch current hardware statistics from InfluxDB (internal function for caching)""" try: stats = { 'hub': {}, 'station': {} }
# Hub Uptime query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{STATUS_MEASUREMENT_HUB}") |> filter(fn: (r) => r._field == "uptime") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['hub']['uptime'] = int(record.get_value()) break
# Hub RSSI query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{STATUS_MEASUREMENT_HUB}") |> filter(fn: (r) => r._field == "rssi_self") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['hub']['rssi'] = int(record.get_value()) break
# Hub Firmware query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{STATUS_MEASUREMENT_HUB}") |> filter(fn: (r) => r._field == "firmware_revision") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['hub']['firmware'] = int(record.get_value()) break
# Hub Radio Version query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{RADIO_MEASUREMENT}") |> filter(fn: (r) => r._field == "version") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['hub']['radio_version'] = int(record.get_value()) break
# Station Uptime query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{STATUS_MEASUREMENT_STATION}") |> filter(fn: (r) => r._field == "uptime") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['station']['uptime'] = int(record.get_value()) break
# Station Battery query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{STATUS_MEASUREMENT_STATION}") |> filter(fn: (r) => r._field == "voltage") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['station']['voltage'] = round(record.get_value(), 2) break
# Station RSSI (to hub) query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{STATUS_MEASUREMENT_STATION}") |> filter(fn: (r) => r._field == "rssi_hub") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['station']['rssi'] = int(record.get_value()) break
# Station Firmware query = f''' from(bucket: "{BUCKET}") |> range(start: -5m) |> filter(fn: (r) => r._measurement == "{STATUS_MEASUREMENT_STATION}") |> filter(fn: (r) => r._field == "firmware_revision") |> last() ''' tables = query_api.query(query) for table in tables: for record in table.records: stats['station']['firmware'] = int(record.get_value()) break
return stats except Exception as e: logger.error(f'Error fetching hardware stats: {e}') return {'hub': {}, 'station': {}}
def refresh_weather_cache(): """Background thread to refresh weather stats cache""" while True: try: cache['weather_stats']['data'] = fetch_weather_stats() cache['weather_stats']['updated_at'] = datetime.now(timezone.utc) logger.debug("Weather cache refreshed") except Exception as e: logger.error(f"Weather cache refresh error: {e}") time.sleep(CACHE_TTL)
def refresh_hardware_cache(): """Background thread to refresh hardware stats cache""" while True: try: cache['hardware_stats']['data'] = fetch_hardware_stats() cache['hardware_stats']['updated_at'] = datetime.now(timezone.utc) logger.debug("Hardware cache refreshed") except Exception as e: logger.error(f"Hardware cache refresh error: {e}") time.sleep(CACHE_TTL)
@app.route('/api/weather/stats')def get_weather_stats(): """Get current weather statistics from cache""" data = cache['weather_stats']['data'] if data is None: return jsonify({'error': 'Cache not ready'}), 503
response = jsonify({ 'data': data, 'updated_at': cache['weather_stats']['updated_at'].isoformat() if cache['weather_stats']['updated_at'] else None }) # Cache for 30s (matches your backend cache TTL) response.headers['Cache-Control'] = 'public, max-age=30, s-maxage=30' return response
@app.route('/api/hardware/stats')def get_hardware_stats(): """Get current hardware statistics from cache""" data = cache['hardware_stats']['data'] if data is None: return jsonify({'error': 'Cache not ready'}), 503
response = jsonify({ 'data': data, 'updated_at': cache['hardware_stats']['updated_at'].isoformat() if cache['hardware_stats']['updated_at'] else None }) # Cache for 30s (matches your backend cache TTL) response.headers['Cache-Control'] = 'public, max-age=30, s-maxage=30' return response
@app.route('/api/weather/history/<field>')def get_weather_history(field): """Get historical weather data for charts""" try: from flask import request hours = int(request.args.get('hours', 24))
# Field mappings field_map = { 'temperature': 'temperature_air', 'humidity': 'r-humidity', 'pressure': 'pressure_station', 'wind': 'wind_speed' }
influx_field = field_map.get(field, field) window = '1h' if hours > 24 else '10m'
query = f''' from(bucket: "{BUCKET}") |> range(start: -{hours}h) |> filter(fn: (r) => r._measurement == "{WEATHER_MEASUREMENT}") |> filter(fn: (r) => r._field == "{influx_field}") |> aggregateWindow(every: {window}, fn: mean, createEmpty: false) '''
tables = query_api.query(query)
formatted = [] for table in tables: for record in table.records: value = record.get_value()
# Apply conversions if field == 'temperature': value = value * 9.0 / 5.0 + 32.0 # C to F elif field == 'wind': value = value * 2.237 # m/s to mph # pressure is already in mb, no conversion needed
formatted.append({ 'time': record.get_time().isoformat(), 'value': round(value, 2) })
response = jsonify(formatted) # Cache historical data for 5 minutes (it doesn't change much) response.headers['Cache-Control'] = 'public, max-age=300, s-maxage=300' return response except Exception as e: logger.error(f'Error fetching weather history: {e}') return jsonify({'error': 'Failed to fetch weather history'}), 500
@app.route('/api/hardware/history/<device>/<field>')def get_hardware_history(device, field): """Get historical hardware data for charts""" try: from flask import request hours = int(request.args.get('hours', 6))
# Device measurement patterns measurement_pattern = '^HB-.*_status$' if device == 'hub' else '^ST-.*_status$' window = '10m' if hours <= 6 else '1h'
query = f''' from(bucket: "{BUCKET}") |> range(start: -{hours}h) |> filter(fn: (r) => r._measurement =~ /{measurement_pattern}/) |> filter(fn: (r) => r._field == "{field}") |> aggregateWindow(every: {window}, fn: mean, createEmpty: false) '''
tables = query_api.query(query)
formatted = [] for table in tables: for record in table.records: formatted.append({ 'time': record.get_time().isoformat(), 'value': round(record.get_value(), 2) })
response = jsonify(formatted) # Cache historical data for 5 minutes response.headers['Cache-Control'] = 'public, max-age=300, s-maxage=300' return response except Exception as e: logger.error(f'Error fetching hardware history: {e}') return jsonify({'error': 'Failed to fetch hardware history'}), 500
@app.route('/api/health')def health_check(): try: # Ping InfluxDB health = influx_client.health() if health.status == 'pass': return jsonify({'status': 'ok', 'database': 'connected'}) else: return jsonify({'status': 'error', 'database': 'disconnected'}), 500 except Exception as e: return jsonify({'status': 'error', 'database': 'disconnected'}), 500
@app.route('/api/debug/measurements')def debug_measurements(): """Debug endpoint to see what measurements are available""" try: query = f''' from(bucket: "{BUCKET}") |> range(start: -24h) |> group(columns: ["_measurement", "entity_id"]) |> distinct(column: "_measurement") |> limit(n: 50) '''
tables = query_api.query(query) measurements = []
for table in tables: for record in table.records: measurements.append({ 'measurement': record.get_value(), 'entity_id': record.values.get('entity_id', 'N/A'), 'tags': {k: v for k, v in record.values.items() if not k.startswith('_')} })
return jsonify({ 'bucket': BUCKET, 'measurements_found': len(measurements), 'measurements': measurements }) except Exception as e: import traceback return jsonify({ 'error': str(e), 'traceback': traceback.format_exc() }), 500
# Start background cache refresh threadsweather_thread = threading.Thread(target=refresh_weather_cache, daemon=True)hardware_thread = threading.Thread(target=refresh_hardware_cache, daemon=True)weather_thread.start()hardware_thread.start()
# Populate cache immediately on startuplogger.info("Initializing cache...")cache['weather_stats']['data'] = fetch_weather_stats()cache['weather_stats']['updated_at'] = datetime.now(timezone.utc)cache['hardware_stats']['data'] = fetch_hardware_stats()cache['hardware_stats']['updated_at'] = datetime.now(timezone.utc)logger.info("Cache initialized")
if __name__ == '__main__': port = int(os.getenv('PORT', 3000)) app.run(host='0.0.0.0', port=port, debug=True)