Store state change to "on" of binary_sensor to its attributes

Hi,
I’m struggeling by defining the time of a state_change to the attributes of a template binary sensor. Can someone help me out?

This is what I have so far, but it doesn’t work like expectetd. The attribute “ein” is not updated or never gets true, somehow.

Does someone have an idea how to strore the time of

  • the last state change to on in its attribute “ein” and
  • the last state change to off in its attribute “aus”?
  # Spuelmaschinen Sensor
  - binary_sensor:
    - unique_id: spuelmaschine_status
      name: "Spülmaschine Status"
      icon: "mdi:dishwasher"
      state: "{{states('sensor.spuelmaschine_power') | float > 0 }}"
      device_class: running
      delay_off:
        minutes: 5
      delay_on:
        seconds: 10
      attributes:
        ein: >
          {% if is_state('binary_sensor.spuelmaschine_status','on') %}
          {{ states.binary_sensor.spuelmaschine_status.last_changed }}
          {% endif %}
        aus: >
          {% if is_state('binary_sensor.spuelmaschine_status','off') %}
          {{ states.binary_sensor.spuelmaschine_status.last_changed }}
          {% endif %}

Thank you!

A few things that needs attention:

You don’t have an else clause for either attribute. I’m not sure whether that will results in issues.

Also, the state you’re checking will be the current state, not the new state.

Maybe convert this to a trigger-based template and use the trigger.to_state state object.

That all said, how are you planning on using this?

Thank you for that hint. I’ll give it a try with an additional else clause.
Trigger-based template is also a very good hint. I’ll give this a try also.

I already have a working solution by using a input_date helper and a automation. But I was trying to get rid of this due to the input helper. I dont want to change somethin manually.

My Plan is to show the current running time of the washingmaschine or dishwasher

image

For this I have a Binary Sensor which is monitoring the energy of a power plug

  1. Zigbee Plug: “sensor.waschmaschine_power”

  2. Template Binary Sensor to monitor washing state: “binary_sensor.waschmaschine_status”

  3. Automation which detects the change to “on” state of washing maschine and fires two services
    input_datetime.set_datetime: “input_datetime.waschmaschine_eingeschaltet”
    counter.increment: counter.waschgaenge

  4. To calculate the time I have a history stats sensor which calculates the time from start: “input_datetime.waschmaschine_eingeschaltet” to end: now() and store it as “sensor.spuelmaschine_laufzeit”

If you’re interessted in code I can manage to share all code snippets.

I’ll keep you up to date on my finding regarding my initial question.

UPDATE: Sorry I would have shared some more pictures of my settings, but my account is by now not allowed to uploade more pictures.

Sorry, new users can only put one embedded media item in a post.