Wait_template not working

Hi, I’m using the following variables and a wait_template in an automation:

  action:
    - variables:
        occupancy: 'binary_sensor.{{ trigger.id }}_occupancy'
        light: '{{ trigger.entity_id }}'

    - wait_template: '{{ is_state(occupancy, "off") and (as_timestamp(now()) - as_timestamp(states.occupancy.last_changed) | default(0) | int > 5*60) or is_state(light, "off") }}'

I’ve isolated the problem to: as_timestamp(states.occupancy.last_changed), the variable occupancy, doesn’t appear to work here.

If I use the name of the entity in it’s place e.g. binary_sensor.bathroom_occupancy the template functions. How can I use a variable here?

Here’s the error I’m getting when I test this in Developer tools:

ValueError: Template error: as_timestamp got invalid input 'None' when rendering template
{% set occupancy = "binary_sensor.bathroom_occupancy" %}
{% set light = "light.bathroom_pendant" %}
{{ is_state(occupancy, "off")
    and (as_timestamp(now()) - as_timestamp(states.occupancy.last_changed) | default(0) | int > 5*60) or is_state(light, "off") }}
but no default was specified

See if this works (untested):

    - wait_template: '{{ is_state(occupancy, "off") and (as_timestamp(now()) - as_timestamp(states. ~ occupancy ~ .last_changed) | default(0) | int < 5*60) or is_state(light, "off") }}'

Thank you, I tried what you suggested that now results in this error:

TemplateSyntaxError: expected name or number

Can you show the whole automation config?

action:
    - variables:
        occupancy: 'binary_sensor.{{ trigger.id }}_occupancy'
        light: '{{ trigger.entity_id }}'

    - wait_template: '{{ is_state(occupancy, "off") and now() - states[occupancy].last_changed < timedelta(minutes=5) or is_state(light, "off") }}'

That sorted it @123! Thanks both for your help :+1:

1 Like