Skip to content

Commit

Permalink
Merge pull request #165 from custom-components/current_price_in_template
Browse files Browse the repository at this point in the history
Add current_price to template
  • Loading branch information
Hellowlol authored Oct 1, 2022
2 parents 9526f3d + ee83184 commit 259fc6c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
9 changes: 7 additions & 2 deletions custom_components/nordpool/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,13 @@ async def async_step_user(

async def _valid_template(self, user_template):
try:
_LOGGER.debug(user_template)
ut = Template(user_template, self.hass).async_render()
#
ut = Template(user_template, self.hass).async_render(
current_price=0
) # Add current price as 0 as we dont know it yet..
_LOGGER.debug("user_template %s value %s", user_template, ut)

return True
if isinstance(ut, float):
return True
else:
Expand Down
32 changes: 17 additions & 15 deletions custom_components/nordpool/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ def __init__(
self._off_peak_2 = None
self._peak = None

_LOGGER.debug("Template %s", str(ad_template))
# Check incase the sensor was setup using config flow.
# This blow up if the template isnt valid.
if not isinstance(self._ad_template, Template):
Expand Down Expand Up @@ -255,27 +256,28 @@ def _calc_price(self, value=None, fake_dt=None) -> float:
_LOGGER.debug("api returned junk infinty %s", value)
return None

# Used to inject the current hour.
# so template can be simplified using now
if fake_dt is not None:
def faker():
def inner(*args, **kwargs):
return fake_dt

def faker():
def inner(*args, **kwargs):
return fake_dt

return pass_context(inner)

template_value = self._ad_template.async_render(now=faker())
else:
template_value = self._ad_template.async_render()
return pass_context(inner)

# The api returns prices in MWh
if self._price_type in ("MWh", "mWh"):
price = template_value / 1000 + value * float(1 + self._vat)
price = value / 1000 * float(1 + self._vat)
template_value = self._ad_template.async_render(
now=faker(), current_price=price
)
#_LOGGER.debug("Template value are %s", template_value)

price += template_value
else:
price = template_value + value / _PRICE_IN[self._price_type] * (
float(1 + self._vat)
price = value / _PRICE_IN[self._price_type] * (float(1 + self._vat))
template_value = self._ad_template.async_render(
now=faker(), current_price=price
)
_LOGGER.debug("Template value are %s", template_value)
price += template_value

# Convert price to cents if specified by the user.
if self._use_cents:
Expand Down

0 comments on commit 259fc6c

Please sign in to comment.