Record sensor value only if conditions met

Hi,

Here’s my scenario. I have an MQTT publishing temperature from a pool, but the readings are only accurate if the pool pump is actually running. So, I’d like to display the latest real time value while the pump is running and display the last value recorded before the pump turned off when the pump is not running.

I’m experimenting with different ways to achieve this goal, so far none are working and seem to very quickly get too complicated.

My latest thought is something like this:

- platform: mqtt
  state_topic: "emon/XXXXXX/temp1"
  name: "Pool Temperature"
  unit_of_measurement: "C" 
  value_template: >-
          {% if is_state('switch.pool_hd_switch', 'on') %}
            {  value | round(1) }
          {% else %}
            not running
          {% endif %}

but just get unknown C.

Any suggestions on where I’m going astray would be greatly appreciated.

one thing that i see is that you need to have double {{ :

{{ value | round(1) }}

Thank you, can believe I missed that. Now halfway there: As expected the temperature now shows correctly when the pump is running and shows the message ‘not running’ when it’s not. Now just need to store the last valid reading somehow and display this when the pump is not running.

Think I’ll try using the sensor code to publish two temperature values in JSON, then just use the template to pick the right one depending on the condition. Will try that tomorrow anyway.

Maybe you can trigger an automation when this sensor changes.
the “numeric_state” trigger has a “from_state” with the old value, which you could compare and use to overwrite if the new value is “not running”?

Thanks, All working now. I used your trigger suggestion to post to a retained MQTT topic when the pump switches off.