Is there a way to retain the previous attribute with trigger sensor?

This trigger-based template sensor writes the current state of a sensor. I would like to capture the last_changed attributes of both the ‘on’ state and ‘off’ state. In this current example, the previous state ( either last_on or last_off) is overwritten. Is there a way to retain the previous state’s attribute each time the entity triggers?

template:

  - trigger:
      - platform: state
        entity_id: binary_sensor.living_room_zone_motion
        not_from:
          - unknown
          - unavailable
    binary_sensor:
      - name: Test Attribute Overwrite
        state: "{{ trigger.to_state.state }}"
        attributes:
          last_on: "{{ trigger.to_state.last_changed.isoformat() if trigger.to_state.state == 'on' }}"
          last_off: "{{ trigger.to_state.last_changed.isoformat() if trigger.to_state.state == 'off' }}"

You might have a look at Variables+History from HACS.

I finally found some inspiration from here. This seems to be working well.

template:

  - trigger:
      - platform: state
        entity_id: binary_sensor.living_room_zone_motion
        not_from:
          - unknown
          - unavailable
        variables:
          to_state: "{{trigger.to_state.state}}"
          last_changed: "{{ trigger.to_state.last_changed.isoformat() }}"
    binary_sensor:
      - name: Test Attribute Overwrite
        state: "{{ trigger.to_state.state }}"
        attributes:
          last_on: |-
            {% set current = this.attributes.get('last_on', {}) %}
            {{ last_changed if to_state == 'on' else current }}
          last_off: |-
            {% set current = this.attributes.get('last_off', {}) %}
            {{ last_changed if to_state == 'off' else current }}
3 Likes

I’m simply using trigger.from_state.last_changed for motion and trigger.to_state.last_changed for no motion.

This is a cool approach to use trigger variables! I’ve totally overlooked this possibility. Helped me tighten up my template sensor significantly.