Template not showing state but template shows up in jinja Editor

Hi all, not a first timer but still feeling new all the while!

Hoping I can get some help for this as it bugs me that I can’t seem to get a template entity working the way it should be but the template not throwing up any errors in the Jinja Editor in HA.

So this is my template that I am trying to get my head around;

  - platform: template
    sensors:
      last_opened:
        friendly_name: 'Last opened'
        entity_id:
          - binary_sensor.front_door
          # DO NOT REMOVE for now....
          # - binary_sensor.garage_closed_bike
          # - binary_sensor.garage_closed_car
          # - binary_sensor.patio_door_left
          # - binary_sensor.utility_door_exterior
          # - binary_sensor.guest_bedroom_window_left
          # - binary_sensor.guest_bedroom_window_right
          # - binary_sensor.spare_bedroom_window_left
          # - binary_sensor.spare_bedroom_window_right
          # - binary_sensor.second_bedroom_window_left
          # - binary_sensor.second_bedroom_window_right
          # - binary_sensor.second_bedroom_window_ensuite
          # - binary_sensor.bathroom_window
        value_template: >-
          {%- set sensors = [states.binary_sensor.front_door] %}
          {% for sensor in sensors %}
            {% if as_timestamp(sensor.last_changed) == as_timestamp(sensors | map(attribute='last_changed') | max) %}
              {{ sensor.name }}
            {% endif %}
          {% endfor %}

The error it throws up on HA is:

Could not render template Last opened, the state is unknown.
5:41 PM components/template/sensor.py (WARNING)

This also shows a ‘unknown’ state on the dev state page and yet if I put the template code into the editor it shows correctly the last opened entity.

I have added the front door sensor (and will add more as I get more sensors) into a few groups: exit_doors, entrance_doors and alarm_sensors. This has still not changed nor updated the state of the entity.

I will freely admit that I got this part of my presence detection code from @Tinkerer on here, I have asked the question however his jinja templating skills are about as abundant as mine!

Really love the power of templating, and wish I knew more and it seems that I am learning as I go along however this time I’m pretty stumped as my template results show I’m getting no where fast!

Thanks for any help in advance - I will owe you a coffee/beer/smoke/can of water(no plastic!)

Dave

Weird, if it works in the dev-templates menu, it should work in the sensor.

Throwing an error on startup is normal, but if you open the front door (or manually change the state of the entity) does it update?

I am, however, moving towards using an input_text and an automation instead of a sensor. This is because every change to the sensor requires a restart of HA, and that’s a pain (partly because I’m on a Pi, partly because every so often, OZW corrupts it’s own cache file, and crashes HA on startup).

Well, I have mine in a Ubuntu Docker and restarting HA takes seconds as it runs on a SSD so this wouldn’t be a problem but I really don’t want it restarting everytime.

Can I ask @Tinkerer , what should be the output of this template (just to make sure what I get back from the editor is the correct result required for the automation to work)

The template editor shows ‘Front Door’

It should be the friendly name of the open entity, so what you see would be right.

I hope you don’t mind me asking but where can I get any info on what the square bracket notation does in the template?

I don’t see that referenced in any of the HA docs on templating.

I hope you don’t mind me asking but where can I get any info on what the square bracket notation does in the template?

I don’t see that referenced in any of the HA docs on templating.

http://jinja.pocoo.org/docs/dev/templates/#variables

You can use a dot ( .) to access attributes of a variable in addition to the standard Python getitem “subscript” syntax ( ).

1 Like

So it should not show a timestamp as per the template coding?

{% if as_timestamp(sensor.last_changed) == as_timestamp(sensors | map(attribute='last_changed') | max) %}

No, because that bit you quoted is doing a comparison

            {% if as_timestamp(sensor.last_changed) == as_timestamp(sensors | map(attribute='last_changed') | max) %}
              {{ sensor.name }}
            {% endif %}

That’s checking to see if this sensor (you can replace sensor and sensors with kipper and whales in that template FYI, they’re just variables) is the one with the most recent update. If it is, then it displays the name (see here) of the entity.

I’m not sure I understand the supplied answer to your question (“dot to access attributes of a variable, etc”). The square brackets define a list.

For example, this will iterate through the list and print out values greater than 10.

{% set my_list = [12, 3, 18, 8, 19, 2, 9] %}
{% for nmbr in my_list %}
  {%- if nmbr > 10 %}
    {{ nmbr }}
  {% endif -%}
{% endfor %}

In the ‘Last Opened’ example, it contains a list with one item. That one item is states.binary_sensor.front_door which, if you did this:

{{ states.binary_sensor.front_door }}

it would produce something like this:

<template state binary_sensor.front_door=off; friendly_name=Front, device_class=door, templates=hidden=return (state === 'off'); @ 2019-07-14T16:37:36.887124-04:00>

I see, as I saw the timestamp in there I kind of assumed it was being used to display entity attributes.

Door was opened {{ (as_timestamp(now()) - as_timestamp(states.sensor.last_opened.last_updated)) | int }} seconds ago

This is what confused me as this gives a reading of time since last time the sensor was tripped.

Still, I’m utterly confused as to why the entity shows no data?!?

So, to simplyfy what you said - all I need to do is to change my code from this;

          {%- set sensors = [states.binary_sensor.front_door] %}
          {% for sensor in sensors %}
            {% if as_timestamp(sensor.last_changed) == as_timestamp(sensors | map(attribute='last_changed') | max) %}
              {{ sensor.name }}
            {% endif %}
          {% endfor %}

To this:

          {{ states.binary_sensor.front_door }}
          {% for sensor in sensors %}
            {% if as_timestamp(sensor.last_changed) == as_timestamp(sensors | map(attribute='last_changed') | max) %}
              {{ sensor.name }}
            {% endif %}
          {% endfor %}

Would it be so easy? :slight_smile:

last_changed contains a datetime object. You can compare datetime objects without having to first convert them into timestamps. Therefore the template can be simplified to this:

        value_template: >
          {% set sensors = [states.binary_sensor.front_door] %}
          {% set last = sensors | map(attribute='last_changed') | max %}
          {% for sensor in sensors %}
            {% if sensor.last_changed == last %}
              {{ sensor.name }}
            {% endif %}
          {% endfor %}

I assume you will be putting more entities into the sensor list and you stripped it down to just one item for demo purposes?

1 Like

No, and yes?

So I currently have just the one sensor so currently I only want to use it for the one but for sure soon enough (like I’m ordering two more sensors now) I will be leaving it as is - so as a list of sensors.

Ok, so now I see the reason for the error kicking up - so how would I template this for the one sensor to work temporary for now? Having this for future use demo purposes would be useful to document too.

Thanks again for your help

The way I’ve shown it above.

When you get more binary_sensors, add them to the sensors list:

{% set sensors = [states.binary_sensor.front_door, states.binary_sensor.rear_door] %}

Ok, so I updated the template sensor and it now, all together, looks like this;

  - platform: template
    sensors:
      last_opened:
        friendly_name: 'Last opened'
        entity_id:
          - binary_sensor.front_door
          # - binary_sensor.garage_closed_bike
          # - binary_sensor.garage_closed_car
          # - binary_sensor.patio_door_left
          # - binary_sensor.utility_door_exterior
          # - binary_sensor.guest_bedroom_window_left
          # - binary_sensor.guest_bedroom_window_right
          # - binary_sensor.spare_bedroom_window_left
          # - binary_sensor.spare_bedroom_window_right
          # - binary_sensor.second_bedroom_window_left
          # - binary_sensor.second_bedroom_window_right
          # - binary_sensor.second_bedroom_window_ensuite
          # - binary_sensor.bathroom_window
        value_template: >
          {% set sensors = [states.binary_sensor.front_door] %}
          {% set last = sensors | map(attribute='last_changed') | max %}
          {% for sensor in sensors %}
            {% if sensor.last_changed == last %}
              {{ sensor.name }}
            {% endif %}
          {% endfor %}

I have left the original and unused entities in there just commented them out, I don’t think this can cause issue. Give HA a reboot, opened and closed the door a few times and still no change in the error on HA and entity state?

I must’ve overlooked something on this?

Here’s my theory: This sounds like a case of unfortunate timing. After rebooting, Home Assistant creates the Template Sensor before binary_sensor.front_door contains a valid state.

Whatever device you are using to monitor the front door appears to take time to be detected by Home Assistant. While it is in the process of being initialized, the binary_sensor has no known state.

In contrast, the Template Sensor is created instantly, apparently well before binary_sensor.front_door. That presents a problem because the Template Sensor’s template depends on the availability of binary_sensor.front_door.

Right, so then can I delay the start of the last_opened sensor to give the binary_sensor time to update its entity state?

No.

If I was faced with this situation, I would use the approach suggested by Tinkerer. Use an automation to monitor the security (door/window) sensors. Whichever sensor triggers the automation gets its friendly_name recorded in an input_text.

input_text:
  last_security_sensor:
    name: 'Last Security Sensor Changed'
    initial: 'None'

Here’s the automation:

- alias: 'monitor security sensors'
  trigger:
    platform: state
    entity_id:
      - binary_sensor.front_door
      - binary_sensor.rear_door
      - binary_sensor.garage_door
      - binary_sensor.bedroom_window
    to: 'on'
  action:
    service: input_text.set_value
    entity_id: input_text.last_security_sensor
    value: '{{ trigger.to_state.attributes.friendly_name }}'
1 Like

If you don’t like using an input_text for this purpose, the alternative is to use a sensor. However, there is no sensor.set_value service in Home Assistant. That makes it challenging for the automation to assign a value to a sensor.

I know of two workarounds:

  1. If you’re already using MQTT, the automation can use mqtt.publish to set the sensor’s state.
  2. @rodpayne has created a python_script, called set_state.py, that can set a sensor’s state. The automation can use python_script.set_state to set the sensor’s state.

I’ve used the first workaround so I can speak from experience about it. The sensor would look something like this:

  - platform: mqtt
    name: "last security sensor"
    state_topic: "home/last_sensor"

The automation I posted above would have the following action:

  action:
    service: mqtt.publish
    data_template:
      topic: 'home/last_sensor'
      payload: '{{ trigger.to_state.attributes.friendly_name }}'
      retain: true
1 Like