diff --git a/custom_components/met_next_6_hours_forecast/const.py b/custom_components/met_next_6_hours_forecast/const.py index ddf6e2c..049e03b 100644 --- a/custom_components/met_next_6_hours_forecast/const.py +++ b/custom_components/met_next_6_hours_forecast/const.py @@ -20,6 +20,7 @@ "Weather forecast from met.no, delivered by the Norwegian " "Meteorological Institute." ) +ATTR_FORECAST_JSON = "forecast_json" CONDITIONS_MAP = { ATTR_CONDITION_CLEAR_NIGHT: {"clearsky_night"}, ATTR_CONDITION_CLOUDY: {"cloudy_night", "cloudy_day", "cloudy"}, diff --git a/custom_components/met_next_6_hours_forecast/weather.py b/custom_components/met_next_6_hours_forecast/weather.py index e0a6d22..0ae44ea 100755 --- a/custom_components/met_next_6_hours_forecast/weather.py +++ b/custom_components/met_next_6_hours_forecast/weather.py @@ -1,8 +1,12 @@ """Support for Met.no next 6 hours forecast service.""" - import logging +import json +from datetime import datetime, timedelta +from random import randrange import pytz + + from homeassistant.const import ( CONF_LATITUDE, CONF_LONGITUDE, @@ -17,14 +21,12 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.util import dt as dt_util -from random import randrange -from datetime import datetime, timedelta from homeassistant.components.weather import ( Forecast, WeatherEntity, ) from .met_api import MetApi -from .const import ATTRIBUTION, DOMAIN, NAME, CONDITIONS_MAP +from .const import ATTR_FORECAST_JSON, ATTRIBUTION, DOMAIN, NAME, CONDITIONS_MAP _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(minutes=randrange(40, 50)) @@ -74,6 +76,7 @@ def __init__( self._raw_data = None self._forecast: list[Forecast] = None self._first_timeserie = None + self._forecast_json = {} @property def force_update(self) -> str: @@ -132,6 +135,13 @@ def attribution(self) -> str: """Return the attribution.""" return ATTRIBUTION + @property + def extra_state_attributes(self): + """Return the state attributes.""" + return { + ATTR_FORECAST_JSON: self._forecast_json + } + @property def forecast(self) -> list[Forecast]: """Return the forecast array.""" @@ -150,6 +160,12 @@ def device_info(self): ) return device_info + def serialize_datetime(self, obj): + """serialize datetime to json""" + if isinstance(obj, datetime): + return obj.isoformat() + raise TypeError("Type not serializable") + async def async_update(self): """Retrieve latest state.""" self._raw_data = await self._hass.async_add_executor_job( @@ -194,6 +210,8 @@ async def async_update(self): ) ) last_added_time = time - + self._forecast_json = json.dumps( + self._forecast, default=self.serialize_datetime + ) self._first_timeserie = self._raw_data["properties"]["timeseries"][0] _LOGGER.info("%s updated", self.location_name)