hass-core/homeassistant/components/metoffice/helpers.py
avee87 2d1744c573
Add forecasts to MetOffice integration (#50876)
* MetOfficeData now retrieves both 3-hourly and daily data (full forecast data, as well as "now" snapshot) on each update

* Bump datapoint API up to latest version

* Create 2 sets of sensors - one of each set for 3-hourly and for daily data (same ones initially enabled, for now)

* Create two entities (one each for 3-hourly and daily data) and also add in the forecast data for each dataset

* Testing changes to accommodate now having two sets of everything for 3-hourly and daily update data

* Removed unused import (reported by flake8)

* As per conversation with @MatthewFlamm leave the 3-hourly entity's unique_id unchanged (although the display name is changed)

* Make some improvements based on reviews

Make some improvements and fix up the formatting/linting failures.

* Make some improvements based on reviews

Make some improvements and fix up the formatting/linting failures.

* Added more test coverage

* import asyncio

* Try to fix test

* Rewrote everything using CoordinatorEntity

* Fixed config flow

* Fixed lint errors

Co-authored-by: MrHarcombe <ian.harcombe@gmail.com>
Co-authored-by: Henco Appel <hencoappel+github@gmail.com>
2021-06-27 15:04:42 -04:00

44 lines
1.3 KiB
Python

"""Helpers used for Met Office integration."""
import logging
import datapoint
from homeassistant.helpers.update_coordinator import UpdateFailed
from homeassistant.util import utcnow
from .data import MetOfficeData
_LOGGER = logging.getLogger(__name__)
def fetch_site(connection: datapoint.Manager, latitude, longitude):
"""Fetch site information from Datapoint API."""
try:
return connection.get_nearest_forecast_site(
latitude=latitude, longitude=longitude
)
except datapoint.exceptions.APIException as err:
_LOGGER.error("Received error from Met Office Datapoint: %s", err)
return None
def fetch_data(connection: datapoint.Manager, site, mode) -> MetOfficeData:
"""Fetch weather and forecast from Datapoint API."""
try:
forecast = connection.get_forecast_for_site(site.id, mode)
except (ValueError, datapoint.exceptions.APIException) as err:
_LOGGER.error("Check Met Office connection: %s", err.args)
raise UpdateFailed from err
else:
time_now = utcnow()
return MetOfficeData(
forecast.now(),
[
timestep
for day in forecast.days
for timestep in day.timesteps
if timestep.date > time_now
],
site,
)