import os import threading import time import logging from datetime import datetime, timezone from dotenv import load_dotenv from flask import Flask, jsonify, send_from_directory from flask_cors import CORS from influxdb_client import InfluxDBClient load_dotenv() # Configure logging log_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 configuration cache = { 'weather_stats': {'data': None, 'updated_at': None}, 'hardware_stats': {'data': None, 'updated_at': None} } CACHE_TTL = 30 # seconds # InfluxDB 2.x client influx_host = os.getenv('INFLUX_HOST', 'localhost') influx_port = os.getenv('INFLUX_PORT', '8086') # Build URL - check if host already includes protocol if 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 patterns WEATHER_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('/') 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/') 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/') 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//') 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 threads weather_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 startup logger.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)