Filter values in value template

Hey everyone,
I am trying to fine tune my thermometers, because they will sometimes report the wrong value.

So my idea was to simply compare each new value to the former one and if it falls within a certain window (say, 1 degree Celsius), update the state with the new value. If the difference is greater than the window, I assume that the reported value is an erroneous outlier and ignore it.
I had this setup running with the filter sensor, however sometimes the temperature would indeed change more than 1 degree between readings and now my sensor would stop updating. Not good.

Okay, so there needs to be a second piece of logic: If the last update is older than 5 minutes, update irregardless of whether it falls within the window or not.

I tried to translate this logic into a template, but so far I can’t get it to work. The sensor will aways be of the state “unknown”.

This is my configuration so far:

  - platform: mqtt
    name:  "balcony_temperature_new"
    state_topic: "homeassistant/sensor/rtl433/Acurite_tower_sensor/2682"
    unit_of_measurement: "°C"
    value_template: >
      {% set new_value = (((value_json.temperature_C | float) -0.50) | round(2)) %}
      {% set last_changed = as_timestamp(states.sensor.balcony_temperature.last_changed) %}
      {# if difference is < 1, update value #}
      {% if (abs(states.sensor.balcony_temperature.state - new_value) < 1) -%}
        {{ new_value }}
      {# if current value is older than 5 min, update value #}
      {% elif ((as_timestamp(now()) - last_changed) > 300) -%}
        {{ new_value }}
      {% endif %}

Any ideas what I might be doing wrong?

Have you already found the error or how did you solve it now?