Skip to content

Commit

Permalink
Merge pull request #266 from custom-components/kek
Browse files Browse the repository at this point in the history
Kek
  • Loading branch information
Hellowlol authored Jan 6, 2023
2 parents 25d8224 + affb623 commit f72815f
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 30 deletions.
5 changes: 1 addition & 4 deletions custom_components/nordpool/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@


NAME = DOMAIN
VERSION = "0.0.10b2"
VERSION = "0.0.10b3"
ISSUEURL = "https://github.com/custom-components/nordpool/issues"

STARTUP = f"""
Expand All @@ -49,7 +49,6 @@ def __init__(self, hass: HomeAssistant):
self._hass = hass
self._last_tick = None
self._data = defaultdict(dict)
self._tomorrow_valid = False
self.currency = []
self.listeners = []

Expand Down Expand Up @@ -83,7 +82,6 @@ async def update_tomorrow(self, _: datetime):
"""Update tomorrows prices."""
_LOGGER.debug("Updating tomorrows prices.")
await self._update(type_="tomorrow", dt=dt_utils.now() + timedelta(hours=24))
self._tomorrow_valid = True

async def _someday(self, area: str, currency: str, day: str):
"""Returns todays or tomorrows prices in a area in the currency"""
Expand Down Expand Up @@ -127,7 +125,6 @@ async def _dry_setup(hass: HomeAssistant, _: Config) -> bool:
async def new_day_cb(_):
"""Cb to handle some house keeping when it a new day."""
_LOGGER.debug("Called new_day_cb callback")
api._tomorrow_valid = False

for curr in api.currency:
if not len(api._data[curr]["tomorrow"]):
Expand Down
54 changes: 35 additions & 19 deletions custom_components/nordpool/aio_price.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,12 @@ def join_result_for_correct_time(results, dt):


class AioPrices(Prices):
def __init__(self, currency, client, tz=None):
"""Interface"""

def __init__(self, currency, client, timeezone=None):
super().__init__(currency)
self.client = client
self.tz = tz
self.timeezone = timeezone
self.API_URL_CURRENCY = "https://www.nordpoolgroup.com/api/marketdata/page/%s"

async def _io(self, url, **kwargs):
Expand All @@ -154,7 +156,7 @@ async def _io(self, url, **kwargs):
return await resp.json()

async def _fetch_json(self, data_type, end_date=None, areas=None):
""" Fetch JSON from API """
"""Fetch JSON from API"""
# If end_date isn't set, default to tomorrow
if end_date is None:
end_date = date.today() + timedelta(days=1)
Expand All @@ -168,7 +170,7 @@ async def _fetch_json(self, data_type, end_date=None, areas=None):
endDate=end_date.strftime("%d-%m-%Y"),
)

async def fetch(self, data_type, end_date=None, areas=[]):
async def fetch(self, data_type, end_date=None, areas=None):
"""
Fetch data from API.
Inputs:
Expand All @@ -189,13 +191,17 @@ async def fetch(self, data_type, end_date=None, areas=[]):
- list of values (dictionary with start and endtime and value)
- possible other values, such as min, max, average for hourly
"""
if areas is None:
areas = []

# Check how to handle all time zone in this,
# dunno how to do this yet.
# now = datetime.utcnow()
# timezone_for_data = now.astimezone(tz.gettz(ts))
# stock = datetime.utcnow().astimezone(tz.gettz("Europe/Stockholm"))
# stock_offset = stock.utcoffset().total_seconds()
# if stock.utcoffset(now) == timezone_for_data.utcoffset(now):
# pass

# compare utc offset
if self.tz == tz.gettz("Europe/Stockholm"):
if self.timeezone == tz.gettz("Europe/Stockholm"):
data = await self._fetch_json(data_type, end_date, areas)
return self._parse_json(data, areas)
else:
Expand Down Expand Up @@ -250,28 +256,38 @@ async def fetch(self, data_type, end_date=None, areas=[]):
raw = [self._parse_json(i, areas) for i in res]
return join_result_for_correct_time(raw, end_date)

async def hourly(self, end_date=None, areas=[]):
""" Helper to fetch hourly data, see Prices.fetch() """
async def hourly(self, end_date=None, areas=None):
"""Helper to fetch hourly data, see Prices.fetch()"""
if areas is None:
areas = []
return await self.fetch(self.HOURLY, end_date, areas)

async def daily(self, end_date=None, areas=[]):
""" Helper to fetch daily data, see Prices.fetch() """
async def daily(self, end_date=None, areas=None):
"""Helper to fetch daily data, see Prices.fetch()"""
if areas is None:
areas = []
return await self.fetch(self.DAILY, end_date, areas)

async def weekly(self, end_date=None, areas=[]):
""" Helper to fetch weekly data, see Prices.fetch() """
async def weekly(self, end_date=None, areas=None):
"""Helper to fetch weekly data, see Prices.fetch()"""
if areas is None:
areas = []
return await self.fetch(self.WEEKLY, end_date, areas)

async def monthly(self, end_date=None, areas=[]):
""" Helper to fetch monthly data, see Prices.fetch() """
async def monthly(self, end_date=None, areas=None):
"""Helper to fetch monthly data, see Prices.fetch()"""
if areas is None:
areas = []
return await self.fetch(self.MONTHLY, end_date, areas)

async def yearly(self, end_date=None, areas=[]):
""" Helper to fetch yearly data, see Prices.fetch() """
async def yearly(self, end_date=None, areas=None):
"""Helper to fetch yearly data, see Prices.fetch()"""
if areas is None:
areas = []
return await self.fetch(self.YEARLY, end_date, areas)

def _conv_to_float(self, s):
""" Convert numbers to float. Return infinity, if conversion fails. """
"""Convert numbers to float. Return infinity, if conversion fails."""
try:
return float(s.replace(",", ".").replace(" ", ""))
except ValueError:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/nordpool/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
"requirements": [
"nordpool>=0.2"
],
"version": "0.0.10b2"
"version": "0.0.10b3"
}
14 changes: 8 additions & 6 deletions custom_components/nordpool/sensor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
import math
from datetime import datetime
from operator import itemgetter
from statistics import mean, median

Expand Down Expand Up @@ -494,18 +493,21 @@ async def check_stuff(self) -> None:
# No need to update if we got the info we need
if self._data_tomorrow is not None:
self._data_today = self._data_tomorrow
# Just to stop the hourly update if its a new day
if dt_utils.now().hour != 0:
self._update()
else:
today = await self._api.today(self._area, self._currency)
if today:
self._data_today = today
if dt_utils.now().hour != 0:
self._update()

self._data_tomorrow = None
_LOGGER.debug("Cleared self._data_tomorrow = %s", self._data_tomorrow)
should_be_none = await self._api.tomorrow(self._area, self._currency)
if should_be_none is None:
_LOGGER.debug(
"Tomorrow should have been none, but was %s", should_be_none
)

# Update attrs for the day.
self._update()

tomorrow = await self._api.tomorrow(self._area, self._currency)
if tomorrow:
Expand Down

0 comments on commit f72815f

Please sign in to comment.