Skip to content
Snippets Groups Projects
data_openmeteo.py 2.17 KiB
Newer Older
from typing import Any
from source.data_source import *


class DataOpenMeteo(DataSource):

    def parse_response_open_meteo(self, api_response: dict[str, Any]) -> None:
        """Parse the OpenMeteo API response to store the result in the source variables

        :param api_response: the api response
        """
        logging.info("-- Parsing OpenMeteo datas ")
        hourly = api_response["hourly"]
        # wind speed needs to be converted from km/h to m/s

        self.variables[int(VariableAtmospheric.AIR_TEMPERATURE)].values = np.array(hourly["temperature_2m"])
        self.variables[int(VariableAtmospheric.WIND_SPEED)].values = np.array(
            [round(speed / 3.6, 2) for speed in hourly["windspeed_10m"]])
        self.variables[int(VariableAtmospheric.WIND_DIRECTION)].values = np.array(hourly["winddirection_10m"])
        self.variables[int(VariableAtmospheric.ATMOSPHERIC_PRESSURE)].values = np.array(hourly["pressure_msl"])

        times = np.array(hourly["time"], dtype="datetime64[s]")
        for variable in VARIABLES_ATMOSPHERIC:
            self.variables[int(variable)].times = times

        return

    def download(self, start_date: datetime, end_date: datetime) -> bool:
        """Download forecast data from open meteo api
        Data are requested from a gironde center point: 45.38°N, -0.88°E

        :param OpenMeteoSource self: open meteo source
        :param datetime start_date: start date
        :param datetime end_date: end date
        :returns: bool
        """
        logging.info("Downloading OpenMeteo datas")
        real_start_date, real_end_date, mode = self.compute_real_dates(start_date, end_date)
        # open meteo api does not handle hour and minutes.
        # end_date has been set to the next day at midnight by compute_real_dates. Therefore,
        # it will retrieve one day too many.
        real_end_date = real_end_date - timedelta(days=1)
        req_url = (
            f"{self.url[mode]}?{self.api_params[mode][0]}"
            f"&start_date={real_start_date:%Y-%m-%d}&end_date={real_end_date:%Y-%m-%d}"
        )
        response = ast.literal_eval(get_curl(req_url))
        self.parse_response_open_meteo(response)
        return True