#!/usr/bin/env python3 """ WeatherProvider - Hämtar väderdata från SMHI """ import requests import json import time from datetime import datetime from pathlib import Path CACHE_DIR = Path("/home/bernt/.openclaw/workspace/life-weather/cache") CACHE_DIR.mkdir(exist_ok=True) class WeatherProvider: def __init__(self, station_id="97530"): self.station_id = station_id self.base_url = "https://opendata-download-metobs.smhi.se/api/version/latest" def _fetch_with_retry(self, url, max_retries=3): """Hämta data med retry-logik""" for attempt in range(max_retries): try: response = requests.get(url, timeout=10) if response.status_code == 200: return response.json() time.sleep(2 ** attempt) # Exponentiell backoff except Exception as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) return None def fetch_temperature(self): """Hämta temperatur""" url = f"{self.base_url}/parameter/1/station/{self.station_id}/period/latest-hour/data.json" return self._fetch_with_retry(url) def fetch_precipitation(self): """Hämta nederbörd""" url = f"{self.base_url}/parameter/7/station/{self.station_id}/period/latest-day/data.json" return self._fetch_with_retry(url) def fetch_wind(self): """Hämta vind""" url = f"{self.base_url}/parameter/4/station/{self.station_id}/period/latest-hour/data.json" return self._fetch_with_retry(url) def get_current_weather(self): """Hämta komplett väderbild""" weather = { "timestamp": datetime.now().isoformat(), "station_id": self.station_id, "temperature": None, "precipitation": None, "wind": None } temp_data = self.fetch_temperature() if temp_data and "value" in temp_data: values = temp_data["value"] if values: weather["temperature"] = { "value": float(values[-1]["value"]), "unit": "celsius", "timestamp": values[-1]["date"] } precip_data = self.fetch_precipitation() if precip_data and "value" in precip_data: values = precip_data["value"] if values: total = sum(float(v["value"]) for v in values if float(v["value"]) >= 0) weather["precipitation"] = { "value": total, "unit": "mm", "period": "latest-day" } wind_data = self.fetch_wind() if wind_data and "value" in wind_data: values = wind_data["value"] if values: weather["wind"] = { "value": float(values[-1]["value"]), "unit": "m/s", "timestamp": values[-1]["date"] } return weather if __name__ == "__main__": provider = WeatherProvider() weather = provider.get_current_weather() print(json.dumps(weather, indent=2))