Skip to content

Commit 9bfcc5f

Browse files
authored
Merge pull request #333 from viiru-/fix-issue-with-late-published-prices
Fix issue with late published prices
2 parents 5df170e + 944b434 commit 9bfcc5f

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed

custom_components/nordpool/__init__.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import logging
22
from collections import defaultdict
3-
from datetime import datetime, timedelta
4-
from functools import partial
3+
from datetime import timedelta
54
from random import randint
65

6+
import backoff
77
import voluptuous as vol
88
from homeassistant.config_entries import ConfigEntry
99
from homeassistant.core import Config, HomeAssistant
@@ -13,7 +13,7 @@
1313
from homeassistant.util import dt as dt_utils
1414
from pytz import timezone
1515

16-
from .aio_price import AioPrices
16+
from .aio_price import AioPrices, InvalidValueException
1717
from .events import async_track_time_change_in_tz
1818

1919
DOMAIN = "nordpool"
@@ -74,12 +74,12 @@ async def _update(self, type_="today", dt=None):
7474
if data:
7575
self._data[currency][type_] = data["areas"]
7676

77-
async def update_today(self, _: datetime):
77+
async def update_today(self):
7878
"""Update today's prices"""
7979
_LOGGER.debug("Updating today's prices.")
8080
await self._update("today")
8181

82-
async def update_tomorrow(self, _: datetime):
82+
async def update_tomorrow(self):
8383
"""Update tomorrows prices."""
8484
_LOGGER.debug("Updating tomorrows prices.")
8585
await self._update(type_="tomorrow", dt=dt_utils.now() + timedelta(hours=24))
@@ -96,8 +96,11 @@ async def _someday(self, area: str, currency: str, day: str):
9696
# set in the sensor.
9797
if currency not in self.currency:
9898
self.currency.append(currency)
99-
await self.update_today(None)
100-
await self.update_tomorrow(None)
99+
await self.update_today()
100+
try:
101+
await self.update_tomorrow()
102+
except InvalidValueException:
103+
_LOGGER.debug("No data available for tomorrow, retrying later")
101104

102105
# Send a new data request after new data is updated for this first run
103106
# This way if the user has multiple sensors they will all update
@@ -128,7 +131,7 @@ async def new_day_cb(_):
128131

129132
for curr in api.currency:
130133
if not api._data.get(curr, {}).get("tomorrow"):
131-
api._data[curr]["today"] = await api.update_today(None)
134+
api._data[curr]["today"] = await api.update_today()
132135
else:
133136
api._data[curr]["today"] = api._data[curr]["tomorrow"]
134137
api._data[curr]["tomorrow"] = {}
@@ -140,12 +143,16 @@ async def new_hr(_):
140143
_LOGGER.debug("Called new_hr callback")
141144
async_dispatcher_send(hass, EVENT_NEW_HOUR)
142145

143-
async def new_data_cb(tdo):
146+
@backoff.on_exception(
147+
backoff.constant,
148+
(InvalidValueException),
149+
logger=_LOGGER, interval=600, max_time=7200, jitter=None)
150+
async def new_data_cb(_):
144151
"""Callback to fetch new data for tomorrows prices at 1300ish CET
145152
and notify any sensors, about the new data
146153
"""
147154
# _LOGGER.debug("Called new_data_cb")
148-
await api.update_tomorrow(tdo)
155+
await api.update_tomorrow()
149156
async_dispatcher_send(hass, EVENT_NEW_PRICE)
150157

151158
# Handles futures updates

custom_components/nordpool/aio_price.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,12 @@
9090
"PL ": "PL",
9191
}
9292

93+
INVALID_VALUES = frozenset((None, float("inf")))
94+
95+
96+
class InvalidValueException(ValueError):
97+
pass
98+
9399

94100
def join_result_for_correct_time(results, dt):
95101
"""Parse a list of responses from the api
@@ -135,6 +141,8 @@ def join_result_for_correct_time(results, dt):
135141
local = val["start"].astimezone(zone)
136142
local_end = val["end"].astimezone(zone)
137143
if start_of_day <= local and local <= end_of_day:
144+
if val['value'] in INVALID_VALUES:
145+
raise InvalidValueException()
138146
if local == local_end:
139147
_LOGGER.info(
140148
"Hour has the same start and end, most likly due to dst change %s exluded this hour",
@@ -179,7 +187,10 @@ async def _fetch_json(self, data_type, end_date=None):
179187

180188
# Add more exceptions as we find them. KeyError is raised when the api return
181189
# junk due to currency not being available in the data.
182-
@backoff.on_exception(backoff.expo, (aiohttp.ClientError, KeyError), logger=_LOGGER)
190+
@backoff.on_exception(
191+
backoff.expo,
192+
(aiohttp.ClientError, KeyError),
193+
logger=_LOGGER, max_value=20, max_time=60)
183194
async def fetch(self, data_type, end_date=None, areas=None):
184195
"""
185196
Fetch data from API.

0 commit comments

Comments
 (0)