Blueprint template unavailable

Hi, this template worked, but when I turned it in to blueprint the result is off when all switches are off or unavailable when they are on.
Please help.

blueprint:
   name: heating_error
   domain: template
   input:
      timeout:
         selector:
            entity:
               domain: input_number
      switches:
         selector:
            entity:
               domain: switch
               multiple: true

variables:
   timeout: !input timeout
   switches: !input switches

binary_sensor:
   device_class: problem
   state: >
      {% for switch in switches %}
         {% if (is_state (switch, 'on') and (int (as_timestamp (now ()) - as_timestamp (states.switch.last_changed)) > int (states (timeout)) * 36)) %}
            {{ true }}
         {% endif %}
      {% endfor %}

That’s going to return a sequence of zero or more trues, which will evaluate to false for zero, true for one and unavailable for more than one. I can have a guess what you’re probably trying to achieve, but please describe what you want.

As a first guess, sorting out the issues of loop scope and switch referencing, and assuming your timing code is correct:

   state: >
      {% set ns = namespace(out=false) %}
      {% for switch in switches %}
         {% if (is_state(switch, 'on') and (int(as_timestamp(now()) - as_timestamp(states[switch].last_changed)) > int(states(timeout)) * 36)) %}
            {% set ns.out = true %}
         {% endif %}
      {% endfor %}
      {{ ns.out }}

Your modification is more precise and clear. But now it’s in false always.
EDIT: Wait, maybee…

YES, it works! Only it’s rounded to minute, but in final it will be in hours.
What’s the purpose of

set ns = namespace(out=false)

just simple

set out = false

wouldn’t be enough?

Scope. If you update a variable inside a loop the change doesn’t persist outside the loop. So:

{% set x = 0 %}
{% for i in [1,2,3] %}
  {% set x = i %}
{% endfor %}
{{ x }}

will return 0 not 3. Using a namespace “protects” it:

{% set ns = namespace(x=0) %}
{% for i in [1,2,3] %}
  {% set ns.x = i %}
{% endfor %}
{{ ns.x }}

will return 3. Try both in Developer Tools / Templates.

thanks Troon

1 Like