Skip to content

Commit

Permalink
Merge pull request #383 from rrooggiieerr/master
Browse files Browse the repository at this point in the history
Fix blocking calls inside the event loop
  • Loading branch information
Hellowlol authored Jun 16, 2024
2 parents 83b6869 + 24afe61 commit 45b4087
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
3 changes: 1 addition & 2 deletions custom_components/nordpool/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_track_time_change
from homeassistant.util import dt as dt_utils
from pytz import timezone

from .aio_price import AioPrices, InvalidValueException
from .events import async_track_time_change_in_tz
Expand Down Expand Up @@ -174,7 +173,7 @@ async def new_data_cb(_):
hour=13,
minute=RANDOM_MINUTE,
second=RANDOM_SECOND,
tz=timezone("Europe/Stockholm"),
tz=await dt_utils.async_get_time_zone("Europe/Stockholm"),
)

cb_new_day = async_track_time_change(
Expand Down
17 changes: 12 additions & 5 deletions custom_components/nordpool/aio_price.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from collections import defaultdict
from datetime import date, datetime, timedelta

from dateutil import tz
from homeassistant.util import dt as dt_utils
from dateutil.parser import parse as parse_dt
import backoff
import aiohttp
Expand Down Expand Up @@ -97,7 +97,7 @@ class InvalidValueException(ValueError):
pass


def join_result_for_correct_time(results, dt):
async def join_result_for_correct_time(results, dt):
"""Parse a list of responses from the api
to extract the correct hours in there timezone.
"""
Expand All @@ -113,7 +113,7 @@ def join_result_for_correct_time(results, dt):
_LOGGER.debug("Skipping %s", key)
continue
else:
zone = tz.gettz(zone)
zone = await dt_utils.async_get_time_zone(zone)

# We add junk here as the peak etc
# from the api is based on cet, not the
Expand Down Expand Up @@ -227,10 +227,17 @@ async def fetch(self, data_type, end_date=None, areas=None):

res = await asyncio.gather(*jobs)

raw = [self._parse_json(i, areas) for i in res]
raw = [await self._async_parse_json(i, areas) for i in res]
# Just to test should be removed
# exceptions_raiser()
return join_result_for_correct_time(raw, end_date)
return await join_result_for_correct_time(raw, end_date)

async def _async_parse_json(self, data, areas):
"""
Async version of _parse_json to prevent blocking calls inside the event loop.
"""
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, self._parse_json, data, areas)

async def hourly(self, end_date=None, areas=None):
"""Helper to fetch hourly data, see Prices.fetch()"""
Expand Down

0 comments on commit 45b4087

Please sign in to comment.