Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add current_price to template #165

Merged
merged 1 commit into from
Oct 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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