Template sensor "unknown" state

Hello,

I’m trying to create a sensor that contains the last time a different sensor was in a certain state. The below template sensor contains the correct value when the binary_sensor is on, otherwise it contains ‘Unknown’. Why is this? When the bvinary sensor is not on, it should set itself to the previous state of the sensor therefor always containing a timestamp.

  - sensor:
      - name: "Front door last opened time"
        unique_id: sensor_frontdoor_last_opened_time
        state: >
          {% set current = states("sensor.sensor_frontdoor_last_opened_time") %}
          {% if states('binary_sensor.frontdoor_sensor_window_door_is_open') == 'on' %}
            {{ int(as_timestamp(now()), 0) }}
          {% else %}
            {{ current }}
          {% endif %}
- sensor:
      - name: "Front door last opened time"
        unique_id: sensor_frontdoor_last_opened_time
        state: >
          {% if states('binary_sensor.frontdoor_sensor_window_door_is_open') == 'on' %}
            {{ int(as_timestamp(now()), 0) }}
          {% else %}
            {{ this.state }}
          {% endif %}

Thanks @123! Are you able to elaborate on why the previous didn’t work? I’d expect the variable to be set before any processing. I’ve stuck with your solution as it works nicely though - Much appreciated.

1 Like

The sensor’s entity_id will be a slugified version of the value you enter for name:. Slugified means all lower case and replace all spaces and symbols with underscores. It will also add an underscore and the next available number to the end if that id already exists (e.g. _2).

In your case you don’t have the word sensor at the beginning of the name but you do have it at the beginning of the entity_id you are referencing in the state. Taras’ code uses this which is the proper way to self-reference a template sensor and avoids issues like not knowing what the actual entity_id is.

As a side note, the unique_id just needs to be something that isn’t used in any other entity config. Most people use a UUID in this field. Google “UUID generator” and you’ll find a site that will create one for you.

You meant to set current to the sensor’s own state value but you referenced the wrong sensor’s entity_id.

I would have used the sql integration instead and just retrieved this from the database. Not solving the users question but I think that would be simpler.