Need help with a trigger on a sensor attribute within a set time

The following Trigger-based Template Sensor maintains a record of the last 5 weight and BMI measurements in an attribute named history. Each measurement is time-stamped.

template:
  - trigger:
      - platform: state
        entity_id: sensor.test_weight
        attribute: timestamp
    sensor:
      - name: Weight History
        state: "{{ now().timestamp() | timestamp_custom() }}"
        attributes:
          history: >
            {% set current = this.attributes.get('history', []) %}
            {% set new = [{
                "weight": trigger.to_state.attributes.weight,
                "bmi": trigger.to_state.attributes.bmi,
                "time": now().timestamp() | timestamp_custom() }] %}
            {{ (new + current)[:5] }}

If you don’t want to record BMI, just remove this line:

                "bmi": trigger.to_state.attributes.bmi,

If you want to record another parameter like basal_metabolism, just add this line after the one that records weight:

                "basal_metabolism": trigger.to_state.attributes.basal_metabolism,

If you want to record more than the last 5 measurements, perhaps to 7 or more, just change [:5] to [:7] on the last line of the template.

1 Like