From 888cf087cbf17cb731dc1300f485ef56a3d03e28 Mon Sep 17 00:00:00 2001 From: Malene Trab Date: Tue, 15 Oct 2024 15:31:01 +0000 Subject: [PATCH] Removing Nordpool connector --- .../connectors/nordpool/__init__.py | 188 ------------------ .../connectors/nordpool/mapping.py | 23 --- .../connectors/nordpool/regions.py | 25 --- custom_components/energidataservice/const.py | 16 -- 4 files changed, 252 deletions(-) delete mode 100644 custom_components/energidataservice/connectors/nordpool/__init__.py delete mode 100644 custom_components/energidataservice/connectors/nordpool/mapping.py delete mode 100644 custom_components/energidataservice/connectors/nordpool/regions.py diff --git a/custom_components/energidataservice/connectors/nordpool/__init__.py b/custom_components/energidataservice/connectors/nordpool/__init__.py deleted file mode 100644 index 24824bf..0000000 --- a/custom_components/energidataservice/connectors/nordpool/__init__.py +++ /dev/null @@ -1,188 +0,0 @@ -"""Nordpool connector.""" - -from __future__ import annotations - -import asyncio -import logging -from datetime import datetime, timedelta - -import homeassistant.util.dt as dt_util -import pytz - -from ...const import INTERVAL -from .mapping import map_region -from .regions import REGIONS - -_LOGGER = logging.getLogger(__name__) - -BASE_URL = ( - "https://www.nordpoolgroup.com/api/marketdata/page/10?currency=EUR&endDate=%s" -) - -SOURCE_NAME = "Nord Pool" - -DEFAULT_CURRENCY = "EUR" - -TIMEZONE = pytz.timezone("Europe/Stockholm") - -__all__ = ["REGIONS", "Connector", "DEFAULT_CURRENCY"] - - -def prepare_data(indata, date, tz) -> list: # pylint: disable=invalid-name - """Get today prices.""" - local_tz = dt_util.get_default_time_zone() - reslist = [] - for dataset in indata: - tmpdate = datetime.fromisoformat(dataset["HourUTC"]).astimezone(local_tz) - tmp = INTERVAL(dataset["SpotPriceEUR"], tmpdate) - if date in tmp.hour.strftime("%Y-%m-%d"): - reslist.append(tmp) - - return reslist - - -class Connector: - """Define Nordpool Connector Class.""" - - def __init__( - self, regionhandler, client, tz, config # pylint: disable=invalid-name - ) -> None: - """Init API connection to Nordpool Group.""" - self.config = config - self.regionhandler = map_region(regionhandler) - self.client = client - self._result = {} - self._tz = tz - self.status = 200 - - async def async_get_spotprices(self) -> None: - """Fetch latest spotprices, excl. VAT and tariff.""" - # yesterday = datetime.now() - timedelta(days=1) - yesterday = datetime.now() - timedelta(days=1) - today = datetime.now() - tomorrow = datetime.now() + timedelta(days=1) - jobs = [ - self._fetch(yesterday), - self._fetch(today), - self._fetch(tomorrow), - ] - - res = await asyncio.gather(*jobs) - raw = [] - - for i in res: - raw = raw + self._parse_json(i) - - self._result = raw - - _LOGGER.debug("Response for %s:", self.regionhandler.region) - _LOGGER.debug(self._result) - - async def _fetch(self, enddate: datetime) -> str: - """Fetch data from API.""" - url = BASE_URL % enddate.strftime("%d-%m-%Y") - _LOGGER.debug( - "Request URL for %s via Nordpool: %s", - (self.regionhandler.api_region or self.regionhandler.region), - url, - ) - resp = await self.client.get(url) - - if resp.status == 400: - _LOGGER.error("API returned error 400, Bad Request!") - return {} - elif resp.status == 411: - _LOGGER.error("API returned error 411, Invalid Request!") - return {} - elif resp.status == 200: - res = await resp.json() - _LOGGER.debug("Response for %s:", self.regionhandler.region) - _LOGGER.debug(self._result) - return res - elif resp.status == 500: - _LOGGER.warning("Server blocked request") - else: - _LOGGER.error("API returned error %s", str(resp.status)) - return {} - - def _parse_json(self, data) -> list: - """Parse json response.""" - # Timezone for data from Nord Pool Group are "Europe/Stockholm" - - if "data" not in data: - return [] - - # All relevant data is in data['data'] - data = data["data"] - - region_data = [] - - if self.regionhandler.api_region: - region = self.regionhandler.api_region - else: - region = self.regionhandler.region - - # Loop through response rows - for row in data["Rows"]: - start_hour = datetime.isoformat( - TIMEZONE.localize(datetime.fromisoformat(row["StartTime"])).astimezone( - dt_util.UTC - ) - ) - - # Loop through columns - for col in row["Columns"]: - name = col["Name"] - # If areas is defined and name isn't in areas, skip column - if region and name not in region: - continue - - # Check if we already have this hour in dict - known = False - for _i, val in enumerate( - region_data - ): # pylint: disable=unused-variable - if start_hour == val["HourUTC"]: - known = True - break - - if known: - # We already have this hour in dict, skip to next - continue - - value = self._conv_to_float(col["Value"]) - if isinstance(value, type(None)): - continue - - region_data.append( - { - "HourUTC": start_hour, - "SpotPriceEUR": value, - } - ) - - return region_data - - @staticmethod - def _conv_to_float(value) -> float | None: - """Convert numbers to float. Return infinity, if conversion fails.""" - try: - return float(value.replace(",", ".").replace(" ", "")) - except ValueError: - return None - - @property - def today(self) -> list: - """Return raw dataset for today.""" - date = datetime.now().strftime("%Y-%m-%d") - return prepare_data(self._result, date, self._tz) - - @property - def tomorrow(self) -> list: - """Return raw dataset for today.""" - date = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d") - data = prepare_data(self._result, date, self._tz) - if len(data) > 20: - return data - else: - return None diff --git a/custom_components/energidataservice/connectors/nordpool/mapping.py b/custom_components/energidataservice/connectors/nordpool/mapping.py deleted file mode 100644 index 34a598b..0000000 --- a/custom_components/energidataservice/connectors/nordpool/mapping.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Do some mappings for region naming.""" - -from __future__ import annotations - -from ...utils.regionhandler import RegionHandler - -_REGION_MAP = { - "DE": "DE-LU", - "NO1": "Oslo", - "NO2": "Kr.Sand", - "NO3": "Molde", - "NO4": "Tromsø", - "NO5": "Bergen", - "LU": "DE-LU", -} - - -def map_region(region: RegionHandler) -> RegionHandler(): - """Map integration region to API region.""" - if region.region in _REGION_MAP: - region.set_api_region(_REGION_MAP[region.region]) - - return region diff --git a/custom_components/energidataservice/connectors/nordpool/regions.py b/custom_components/energidataservice/connectors/nordpool/regions.py deleted file mode 100644 index d32ff4e..0000000 --- a/custom_components/energidataservice/connectors/nordpool/regions.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Define valid zones for Nord Pool.""" - -REGIONS = { - "DK1", - "DK2", - "SE1", - "SE2", - "SE3", - "SE4", - "NO1", - "NO2", - "NO3", - "NO4", - "NO5", - "FI", - "EE", - "LV", - "LT", - "FR", - "NL", - "BE", - "AT", - "DE", - "LU", -} diff --git a/custom_components/energidataservice/const.py b/custom_components/energidataservice/const.py index 956db61..67d48a6 100644 --- a/custom_components/energidataservice/const.py +++ b/custom_components/energidataservice/const.py @@ -86,25 +86,9 @@ REGIONS = { "DK1": [CURRENCY_LIST["DKK"], "Denmark", "West of the great belt", 0.25], "DK2": [CURRENCY_LIST["DKK"], "Denmark", "East of the great belt", 0.25], - "FI": [CURRENCY_LIST["EUR"], "Finland", "Finland", 0.24], - "EE": [CURRENCY_LIST["EUR"], "Estonia", "Estonia", 0.20], - "LT": [CURRENCY_LIST["EUR"], "Lithuania", "Lithuania", 0.21], - "LV": [CURRENCY_LIST["EUR"], "Latvia", "Latvia", 0.21], - "NO1": [CURRENCY_LIST["NOK"], "Norway", "Oslo", 0.25], "NO2": [CURRENCY_LIST["NOK"], "Norway", "Kristiansand", 0.25], - "NO3": [CURRENCY_LIST["NOK"], "Norway", "Molde, Trondheim", 0.25], - "NO4": [CURRENCY_LIST["NOK"], "Norway", "Tromsø", 0.25], - "NO5": [CURRENCY_LIST["NOK"], "Norway", "Bergen", 0.25], - "SE1": [CURRENCY_LIST["SEK"], "Sweden", "Luleå", 0.25], - "SE2": [CURRENCY_LIST["SEK"], "Sweden", "Sundsvall", 0.25], "SE3": [CURRENCY_LIST["SEK"], "Sweden", "Stockholm", 0.25], "SE4": [CURRENCY_LIST["SEK"], "Sweden", "Malmö", 0.25], - "FR": [CURRENCY_LIST["EUR"], "France", "France", 0.055], - "NL": [CURRENCY_LIST["EUR"], "Netherlands", "Netherlands", 0.21], - "BE": [CURRENCY_LIST["EUR"], "Belgium", "Belgium", 0.21], - "AT": [CURRENCY_LIST["EUR"], "Austria", "Austria", 0.20], - "DE": [CURRENCY_LIST["EUR"], "Germany", "Germany", 0.19], - "LU": [CURRENCY_LIST["EUR"], "Luxemburg", "Luxemburg", 0.08], "FIXED": [CURRENCY_LIST["NONE"], "Fixed Price", "Fixed Price", 0.0], }