Getting Strange Behavior from template sensor

Hey, can anyone tell me what I’m doing wrong here? I built a sensor for my thermostat that determines whether the it should be on heat, cool, or off.

Here it is

  template:
    - sensor:
        - name: "Down Heat or Cool"
          state: >-
                {%- if state_attr('weather.home','temperature') < 60 -%}
                  heat
                {%- elif state_attr('weather.home','temperature') > 85 -%}
                  cool
                {%- else -%}
                  {%- if states('input_boolean.vacation_mode') == 'off' -%}
                    {%- if state_attr('climate.downstairs_thermostat','current_temperature') | int > (states('sensor.optimum_downstairs_temperature') | int + 4) -%}
                      cool
                    {%- elif state_attr('climate.downstairs_thermostat','current_temperature') | int < (states('sensor.optimum_downstairs_temperature') | int - 4) -%}
                      heat
                    {%- elif states('climate.downstairs_thermostat') == "cool" -%}
                      cool
                    {%- elif states('climate.downstairs_thermostat') == "heat" -%}
                      heat
                    {%- endif -%}
                  {%- else -%}
                    off
                  {%- endif -%}
                {%- endif -%}

The problem is it keeps changing state for no reason.
And when I look at the logs they say this: Down Heat or Cool changed to heat triggered by state of Downstairs Thermostat changed to Cool.

First of all the Thermostat had been on cool for over 2 hours already, second even if it had just changed to cool the sensor should not have changed to heat because of it.

Can anyone tell me what I did wrong?

Thx

Nothing. That template will update when any of the states or attributes listed in the template change.

Most likely the thermostat current temperature attribute is changing the most. The logs may be misleading because they don’t list the attribute changes for an entity, only the state.

If you only want it to update when a particular entity state or attribute changes use a triggered template sensor.

Also that if statement nested inside the main if needs an else case for when the current and optimal temperatures are equal and the thermostat is off. Currently you are not covering this case.