Setting up value of sensor conditionally according to scheduler helper state

First, I have to say that I am a real newbie with HA, python, yaml, templates and stuff like that.

I need to dynamically change value of price for electricity consumption according to some schedule. Thus I created schedule in Helpers called “low_tariff” and would like to set sensor price_kwh (to use it in energy dashboard then) to some value when schedule.low_tariff is ON and to different value when schedule.low_tariff is OFF.

Thus I added following section to configuration.yaml

template:
  - sensor:
     - name: "Electricity price LT/HT"
        unit_of_measurement: "EUR/kWh"
        state: >
          {% if states(schedule.low_tariff) == "on" %}
             {% set price_eur_kwh = (0.15 * 1.17) %}
          {% else %}
             {% set price_eur_kwh = (0.19 * 1.17) %}
          {% endif %}

but I am getting following error in homeassistant log (and of course value of price_eur_kwh is unavalaible):

2023-02-08 11:58:25.065 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'schedule' is undefined when rendering '{% if states(schedule.low_tariff) == "on" %}

Thanks, Z.

  1. your entity_id is not in quotes.
  2. You aren’t outputting anything. {{ }} outputs the result of what’s wrapped in the brackets, {% %} is a non-outputting line of code.

I forgot to copy last line of config where is output {{ }}
Missing quotes was the issue. Thanks a lot!

Tryed using this code with some changes to make my own but something is missing

template:
  - sensor:
     - name: "Preço Electricidade"
        unit_of_measurement: "EUR/kWh"
        state: >
          {% if states("schedule.cheias_verao") == "on" and if states("cinput_boolean.eda_horario_verao") == "on"  %}
             {% set price_eur_kwh = (0.1711 * 1.16) %}
          {% else %}
          {% if states("schedule.cheias_inverno") == "on" and if states("cinput_boolean.eda_horario_verao") == "off"  %}
             {% set price_eur_kwh = (0.1711 * 1.16) %}
            {% else %}
          {% if states("schedule.eda_vazio_verao") == "on" and if states("cinput_boolean.eda_horario_verao") == "on"  %} 
             {% set price_eur_kwh = (0,1056 * 1.16) %} 
          {% else %}
          {% if states("schedule.eda_vazio_inverno") == "on" and if states("cinput_boolean.eda_horario_verao") == "off"  %} 
             {% set price_eur_kwh = (0,1056 * 1.16) %}
            {% else %}
          {% if states("schedule.ponta_verao") == "on" and if states("cinput_boolean.eda_horario_verao") == "on"  %} 
             {% set price_eur_kwh = (0,2380 * 1.16) %} 
          {% else %}
          {% if states("schedule.ponta_inverno") == "on" and if states("cinput_boolean.eda_horario_verao") == "off"  %} 
             {% set price_eur_kwh = (0,2380 * 1.16) %}  
          {% endif %}
  • Your last four {% set price statements use an invalid “decimal comma”. Must be e.g. 0.1056 not 0,1056.
  • Remove the ifs after each and.
  • You have a lot of nested ifs that don’t have matching {% endif %} statements.
  • Finally, you need to actually output something. Instead of:
             {% set price_eur_kwh = (0.1711 * 1.16) %}

use:

             {{ 0.1711 * 1.16 }}
1 Like

Thanks :smiley: , but still getting a error:

Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 97, column 8
expected <block end>, but found '<block mapping start>'
in "/config/configuration.yaml", line 98, column 9
template:
  - sensor:
     - name: "Preço Electricidade"                        #### LINE 97
        unit_of_measurement: "EUR/kWh"             #### LINE 98
        state: >
          {% if states("schedule.cheias_verao") == "on" and states("cinput_boolean.eda_horario_verao") == "on"  %}
             {% set price_eur_kwh = (0.1711 * 1.16) %}
          {% else %}
          {% if states("schedule.cheias_inverno") == "on" and states("cinput_boolean.eda_horario_verao") == "off"  %}
             {% set price_eur_kwh = (0.1711 * 1.16) %}
            {% else %}
          {% if states("schedule.eda_vazio_verao") == "on" and states("cinput_boolean.eda_horario_verao") == "on"  %} 
             {% set price_eur_kwh = (0.1056 * 1.16) %}
          {% else %}
          {% if states("schedule.eda_vazio_inverno") == "on" and states("cinput_boolean.eda_horario_verao") == "off"  %} 
             {% set price_eur_kwh = (0.1056 * 1.16) %}
            {% else %}
          {% if states("schedule.ponta_verao") == "on" and states("cinput_boolean.eda_horario_verao") == "on"  %} 
             {% set price_eur_kwh = (0.2380 * 1.16) %}
          {% else %}
          {% if states("schedule.ponta_inverno") == "on" and states("cinput_boolean.eda_horario_verao") == "off"  %} 
             {% set price_eur_kwh = (0.2380 * 1.16) %}
          {% endif %}

See my edited post. Explain the pricing structure and what the schedule and cinput entities are, and I’ll suggest a better template.

1 Like

Great :smiley:

But still getting error on line 97 and 98 -.- dont know why

Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 97, column 8
expected <block end>, but found '<block mapping start>'
in "/config/configuration.yaml", line 98, column 9
template:
  - sensor:
     - name: "Preço Electricidade"  ###Line 97
        unit_of_measurement: "EUR/kWh"  ###Line 98
        state: >
          {% if states(schedule.cheias_verao) == "on" and if states(cinput_boolean.eda_horario_verao) == "on"  %} 
             {{ 0.1711 * 1.16 }}
          {% else %}
          {% if states(schedule.cheias_inverno) == "on" and if states(cinput_boolean.eda_horario_verao) == "off"  %} 
             {{ 0.1711 * 1.16 }}
            {% else %}
          {% if states(schedule.eda_vazio_verao) == "on" and if states(cinput_boolean.eda_horario_verao) == "on"  %} 
             {{ 0.1056 * 1.16 }}
          {% else %}
          {% if states(schedule.eda_vazio_inverno) == "on" and if states(cinput_boolean.eda_horario_verao) == "off"  %} 
             {{ 0.1056 * 1.16 }}
            {% else %}
          {% if states(schedule.ponta_verao) == "on" and if states(cinput_boolean.eda_horario_verao) == "on"  %} 
             {{ 0.2380 * 1.16 }}
          {% else %}
          {% if states(schedule.ponta_inverno) == "on" and if states(cinput_boolean.eda_horario_verao) == "off"  %} 
             {{ 0.2380 * 1.16 }}
          {% endif %}

Your indentation is out. name should align with unit... and state.

You also haven’t quoted your entity IDs, and I think you mean input_boolean not cinput_boolean.

You seem to have started with the OP’s code which was broken and made it worse without implementing the posted solution :smiley:.

Try this, which should be functionally identical to what you intended:

template:
  - sensor:
      - name: "Preço Electricidade"                       
        unit_of_measurement: "EUR/kWh"             
        state: >
          {% set cv, ci, ev, ei, pv, pi, hv = bool(states("schedule.cheias_verao")),
                                              bool(states("schedule.cheias_inverno")),
                                              bool(states("schedule.eda_vazio_verao")),
                                              bool(states("schedule.eda_vazio_inverno")),
                                              bool(states("schedule.ponta_verao")),
                                              bool(states("schedule.ponta_inverno")),
                                              bool(states("input_boolean.eda_horario_verao")) %}
          {% if (cv and hv) or (ci and not hv) %}
            {{ 0.1711 * 1.16 }}
          {% elif (ev and hv) or (ei and not hv) %}
            {{ 0.1056 * 1.16 }}
          {% elif (pv and hv) or (pi and not hv) %}
            {{ 0.2380 * 1.16 }}
          {% endif %}

There are a few combinations of those various entities that will fall through the template without giving a value — for example, any of the verao schedules being off whilst the input_boolean is on.

1 Like

Awesome.

The price struture is like this

So i made a shedule for each Tariff (green/yellow/red) for both Winter and Summer
And have a input_boolean that i can set when its summer (turns ON) and when its winter (turns Off) so that it uses the apropriate schedule.

1 Like

Your code works without errors :smiley:

Have to try and see if it does what i want :smiley:

In that case, instead of this in my template:

bool(states("input_boolean.eda_horario_verao"))

you could use this:

(5 < now().month < 11)

and then you wouldn’t need the input_boolean.

1 Like

Like this then

Awesome :smiley: thanks man, you’re a life saver

###################################
WORKING :smiley:
###################################

template:
  - sensor:
      - name: "Preço Electricidade"                       
        unit_of_measurement: "EUR/kWh"             
        state: >
          {% set cv, ci, ev, ei, pv, pi, hv = bool(states("schedule.cheias_verao")),
                                              bool(states("schedule.cheias_inverno")),
                                              bool(states("schedule.eda_vazio_verao")),
                                              bool(states("schedule.eda_vazio_inverno")),
                                              bool(states("schedule.ponta_verao")),
                                              bool(states("schedule.ponta_inverno")),
                                              (5 < now().month < 11) %}
          {% if (cv and hv) or (ci and not hv) %}
            {{ 0.1711 * 1.16 }}
          {% elif (ev and hv) or (ei and not hv) %}
            {{ 0.1056 * 1.16 }}
          {% elif (pv and hv) or (pi and not hv) %}
            {{ 0.2380 * 1.16 }}
          {% endif %}
1 Like

Sorry for bothering you again, but for some reason it says that the sensor is unavailable.

Gives this error in the log

2023-05-25 12:42:22.108 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template<template=({% set cv, ci, ev, ei, pv, pi, hv = bool(states("schedule.cheias_verao")),
bool(states("schedule.cheias_inverno")),
bool(states("schedule.eda_vazio_verao")),
bool(states("schedule.eda_vazio_inverno")),
bool(states("schedule.ponta_verao")),
bool(states("schedule.ponta_inverno")),
(5 < now().month < 11) %}
{% if (cv and hv) or (ci and not hv) %}
{{ 0.1711 * 1.16 }}
{% elif (ev and hv) or (ei and not hv) %}
{{ 0.1056 * 1.16 }}
{% elif (pv and hv) or (pi and not hv) %}
{{ 0.2380 * 1.16 }}
{% endif %}) renders=2>
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1136, in forgiving_boolean
return cv.boolean(value)
File "/usr/src/homeassistant/homeassistant/helpers/config_validation.py", line 187, in boolean
raise vol.Invalid(f"invalid boolean value {value}")
voluptuous.error.Invalid: invalid boolean value unknown
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 544, in async_render
render_result = _render_with_context(self.template, compiled, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2164, in _render_with_context
return template.render(**kwargs)
File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
self.environment.handle_exception()
File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "<template>", line 1, in top-level template code
File "/usr/local/lib/python3.10/site-packages/jinja2/sandbox.py", line 393, in call
return __context.call(__obj, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1139, in forgiving_boolean
raise_no_default("bool", value)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1594, in raise_no_default
raise ValueError(
ValueError: Template error: bool got invalid input 'unknown' when rendering template '{% set cv, ci, ev, ei, pv, pi, hv = bool(states("schedule.cheias_verao")),
bool(states("schedule.cheias_inverno")),
bool(states("schedule.eda_vazio_verao")),
bool(states("schedule.eda_vazio_inverno")),
bool(states("schedule.ponta_verao")),
bool(states("schedule.ponta_inverno")),
(5 < now().month < 11) %}
{% if (cv and hv) or (ci and not hv) %}
{{ 0.1711 * 1.16 }}
{% elif (ev and hv) or (ei and not hv) %}
{{ 0.1056 * 1.16 }}
{% elif (pv and hv) or (pi and not hv) %}
{{ 0.2380 * 1.16 }}
{% endif %}' but no default was specified
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 665, in async_render_to_info
render_info._result = self.async_render(variables, strict=strict, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 546, in async_render
raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: ValueError: Template error: bool got invalid input 'unknown' when rendering template '{% set cv, ci, ev, ei, pv, pi, hv = bool(states("schedule.cheias_verao")),
bool(states("schedule.cheias_inverno")),
bool(states("schedule.eda_vazio_verao")),
bool(states("schedule.eda_vazio_inverno")),
bool(states("schedule.ponta_verao")),
bool(states("schedule.ponta_inverno")),
(5 < now().month < 11) %}
{% if (cv and hv) or (ci and not hv) %}
{{ 0.1711 * 1.16 }}
{% elif (ev and hv) or (ei and not hv) %}
{{ 0.1056 * 1.16 }}
{% elif (pv and hv) or (pi and not hv) %}
{{ 0.2380 * 1.16 }}
{% endif %}' but no default was specified
2023-05-25 12:42:22.111 ERROR (MainThread) [homeassistant.helpers.template_entity] TemplateError('ValueError: Template error: bool got invalid input 'unknown' when rendering template '{% set cv, ci, ev, ei, pv, pi, hv = bool(states("schedule.cheias_verao")),
bool(states("schedule.cheias_inverno")),
bool(states("schedule.eda_vazio_verao")),
bool(states("schedule.eda_vazio_inverno")),
bool(states("schedule.ponta_verao")),
bool(states("schedule.ponta_inverno")),
(5 < now().month < 11) %}
{% if (cv and hv) or (ci and not hv) %}
{{ 0.1711 * 1.16 }}
{% elif (ev and hv) or (ei and not hv) %}
{{ 0.1056 * 1.16 }}
{% elif (pv and hv) or (pi and not hv) %}
{{ 0.2380 * 1.16 }}
{% endif %}' but no default was specified') while processing template 'Template<template=({% set cv, ci, ev, ei, pv, pi, hv = bool(states("schedule.cheias_verao")),
bool(states("schedule.cheias_inverno")),
bool(states("schedule.eda_vazio_verao")),
bool(states("schedule.eda_vazio_inverno")),
bool(states("schedule.ponta_verao")),
bool(states("schedule.ponta_inverno")),
(5 < now().month < 11) %}
{% if (cv and hv) or (ci and not hv) %}
{{ 0.1711 * 1.16 }}
{% elif (ev and hv) or (ei and not hv) %}
{{ 0.1056 * 1.16 }}
{% elif (pv and hv) or (pi and not hv) %}
{{ 0.2380 * 1.16 }}
{% endif %}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.preco_electricidade'

That suggests that one of your schedule entities is unknown. Pop this into Developer Tools / Template Editor:

cv: {{ states("schedule.cheias_verao") }}
ci: {{ states("schedule.cheias_inverno") }}
ev: {{ states("schedule.eda_vazio_verao") }}
ei: {{ states("schedule.eda_vazio_inverno") }}
pv: {{ states("schedule.ponta_verao") }}
pi: {{ states("schedule.ponta_inverno") }}
cv: on
ci: unknown
ev: off
ei: off
pv: on
pi: off

Looking into why its giving unkown, just a minute

Ok got it, had a sensor ID wrong -.- sorry, fixed it now its working :smiley:

Again THANKS ALOT :smiley:

1 Like

Why are schedule.cheias_verao (green) and schedule.ponta_verao (red) both on? You have about a week to work that out until summer starts :smiley: .

1 Like

Ya thats because i had the IDs wrong… i did the schedules in my phone and had to backtrack on two of them and didnt notice the ID, but when “coding” i used the correct names, but the helpers were not correct, big mistake my part :slight_smile:

cv: off
ci: on
ev: off
ei: off
pv: on
pi: off

Now its fine

1 Like