State object of passed in entity

How can I access the state object of a passed in entity?

So if I pass in a motion sensor to a blueprint:

    motion_sensor:
      name: Motion Sensor
      description: "A motion sensor or group of motion sensors. Where state will be 'off' to trigger."
      selector:
        entity:
motion_sensor: binary_sensor.nursery_pir

I want to know when it was last changed. I tried this:

  - condition: template
    value_template: >
      {{ is_state(motion_sensor, 'off')
      and (as_timestamp(now()) - as_timestamp(motion_sensor.last_changed)) | float(0) > states('input_number.occupancy_timeout') | float(20) }}

But I get an error:

[homeassistant.helpers.condition] Error during template condition: UndefinedError: 'str object' has no attribute 'last_changed'

I am assuming that “motion_sensor” is a string and not an object?

Use the state_attr(…) notation, like this:

as_timestamp(state_attr(motion_sensor, 'last_changed'))

No that does not work I’m afraid as last_changed is not within attributes. So cannot be retrieved using the state_attr function.

My understanding is that I have to access the state object directly, rather than a function, to access last_changed. But not sure if I can do this dynamically.

1 Like

Change this:

as_timestamp(motion_sensor.last_changed)

to this:

states[motion_sensor].last_changed.timestamp()
4 Likes

The solution above is the right one for this use case IMO. But just as an FYI for future, if you pass an entity ID into the expand filter it gives you back the full state object to work with. The examples in the doc talk about the expand filter’s usage in groups but actually it works for anything. Here’s an example of how that works:

Figured you might find it useful in future blueprints.

2 Likes

Amazing thank you!
That was exactly what I was missing.

Thank you this is super handy to know :slight_smile: