Skip to content

Commit

Permalink
Merge pull request #312 from MTrab:Fetch-dated-tariffs
Browse files Browse the repository at this point in the history
Switch to dated tariffs
  • Loading branch information
MTrab committed Jun 20, 2023
2 parents 1cc5851 + bf7595c commit accc999
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 33 deletions.
2 changes: 2 additions & 0 deletions custom_components/energidataservice/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ def __init__(
self.predictions = None
self.api_predictions = None
self.tariff_data = None
self.tariff_connector = None
self.predictions_calculated = False
self.predictions_currency = None
self.connector_currency = "EUR"
Expand Down Expand Up @@ -225,6 +226,7 @@ async def async_get_tariffs(self) -> None:
self._config.options.get(CONF_TARIFF_CHARGE_OWNER),
)

self.tariff_connector = tariff
self.tariff_data = await tariff.async_get_tariffs()

@property
Expand Down
41 changes: 12 additions & 29 deletions custom_components/energidataservice/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,17 +639,19 @@ def inner(*_, **__):
and len(self._api.tariff_data["tariffs"]) > 0
):
try:
if "additional_tariffs" in self._api.tariff_data:
for tariff, additional_tariff in self._api.tariff_data[
"additional_tariffs"
].items():
tariff_value += float(additional_tariff)
if tariff == "elafgift":
elafgift = float(additional_tariff)

tariff_value += float(
self._api.tariff_data["tariffs"][str(fake_dt.hour)]
system_tariff: dict = (
self._api.tariff_connector.get_dated_system_tariff(fake_dt)
)
chargeowner_tariff: dict = self._api.tariff_connector.get_dated_tariff(
fake_dt
)

for tariff, additional_tariff in system_tariff.items():
tariff_value += float(additional_tariff)
if tariff == "elafgift":
elafgift = float(additional_tariff)

tariff_value += float(chargeowner_tariff[str(fake_dt.hour)])
except KeyError:
_LOGGER.warning(
"Error adding tariffs for %s, no valid tariffs was found!", fake_dt
Expand Down Expand Up @@ -704,13 +706,6 @@ def inner(*_, **__):
if self._cent:
price = price * CENT_MULTIPLIER

_LOGGER.debug(
"Hour %s: Tariff %s, Template %s",
fake_dt.hour,
tariff_value,
template_value,
)

return price

def _format_list(
Expand All @@ -727,12 +722,6 @@ def _format_list(
if predictions:
list_for = "FORECASTS"

_LOGGER.debug(
"Unformatted list for '%s':\n%s",
list_for,
json.dumps(data, indent=2, default=str),
)

_start = datetime.now().timestamp()
Interval = namedtuple("Interval", "price hour")
for i in data:
Expand All @@ -746,12 +735,6 @@ def _format_list(
_stop = datetime.now().timestamp()
_ttf = round(_stop - _start, 2)

_LOGGER.debug(
"Formatted list for '%s':\n%s",
list_for,
json.dumps(formatted_pricelist, indent=2, default=str),
)

if tomorrow:
_calc_for = "TOMORROW"
self._api.tomorrow_calculated = True
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ def __init__(
self.client = client
self._chargeowner = chargeowner
self._tariffs = {}
self._result = {}
self._additional_tariff = {}
self._all_tariffs = {}
self._all_additional_tariffs = {}

# dt_now = datetime.now()
# for elafgift in FM_EL_AFGIFT:
Expand Down Expand Up @@ -81,12 +82,12 @@ async def async_get_tariffs(self):
return
else:
# We got data from the DataHub - update the dataset
self._result = resp
self._all_tariffs = resp

check_date = (datetime.utcnow()).strftime("%Y-%m-%d")

tariff_data = {}
for entry in self._result:
for entry in self._all_tariffs:
if (entry["ValidFrom"].split("T"))[0] <= check_date and (
entry["ValidTo"] is None
or (entry["ValidTo"].split("T"))[0] >= check_date
Expand Down Expand Up @@ -117,6 +118,48 @@ async def async_get_tariffs(self):
self._chargeowner,
)

def get_dated_tariff(self, date: datetime) -> dict:
"""Get tariff for this specific date."""
check_date = date.strftime("%Y-%m-%d")

tariff_data = {}
for entry in self._all_tariffs:
if (entry["ValidFrom"].split("T"))[0] <= check_date and (
entry["ValidTo"] is None
or (entry["ValidTo"].split("T"))[0] >= check_date
):
baseprice = 0
for key, val in entry.items():
if key == "Price1":
baseprice = val
if "Price" in key:
hour = str(int("".join(filter(str.isdigit, key))) - 1)

tariff_data.update(
{hour: val if val is not None else baseprice}
)

if len(tariff_data) == 24:
return tariff_data

return {}

def get_dated_system_tariff(self, date: datetime) -> dict:
"""Get system tariffs for this specific date."""
check_date = date.strftime("%Y-%m-%d")
tariff_data = {}
for entry in self._all_additional_tariffs:
if (entry["ValidFrom"].split("T"))[0] <= check_date and (
entry["ValidTo"] is None
or (entry["ValidTo"].split("T"))[0] >= check_date
):
if not entry["Note"] in tariff_data:
tariff_data.update(
{util_slugify(entry["Note"]): float(entry["Price1"])}
)

return tariff_data

async def async_get_system_tariffs(self) -> dict:
"""Get additional system tariffs defined by the Danish government."""
search_filter = '{"Note":["Elafgift","Systemtarif","Transmissions nettarif"]}'
Expand All @@ -131,10 +174,12 @@ async def async_get_system_tariffs(self) -> dict:
"Could not fetch tariff data from Energi Data Service DataHub!"
)
return
else:
self._all_additional_tariffs = dataset

check_date = (datetime.utcnow()).strftime("%Y-%m-%d")
tariff_data = {}
for entry in dataset:
for entry in self._all_additional_tariffs:
if (entry["ValidFrom"].split("T"))[0] <= check_date and (
entry["ValidTo"] is None
or (entry["ValidTo"].split("T"))[0] >= check_date
Expand Down

0 comments on commit accc999

Please sign in to comment.