Calculations on MQTT sensor value with value_template

I have a water level sensor, which provides the distance from top of the cistern to the water surface. It would be nice to display water level, which is:

300 cm - (water level provided by sensor)

I’m using the following code:

  state_topic: "/garden-01/01/Distance" # ESPeasy 
  name: "Water_level" # ESPeasy 
  unit_of_measurement: cm

The value is showing up in HA frontend.
I put this sensor value in the following template:
"{{ states.sensor.water_level.state | int*-1+300 }}"
and it works perfect in the template “sandbox”.

But, if I try the following code:

  state_topic: "/garden-01/01/Distance" # ESPeasy 
  name: "Water_level" # ESPeasy 
  unit_of_measurement: cm
  value_template: "{{ states.sensor.water_level.state | int*-1+300 }}"

This gives me alternating 0 cm and 300 cm values, while the sensor value is 189 cm :frowning:

Can anybody help me to get the right (300 cm - (water level provided by sensor)) value as a sensor value, or any other entity, witch can be displayed and used in automations?

thank you very much.

Try it with some brackets…

“{{ ((states.sensor.water_level.state | int)*-1)+300 }}”
or
“{{ 300 - (state.sensor.water_level.state | int) }}”

You can do math functions inside of espeasy.

I’ve tried both suggestions, but no luck.
The same alternating 0 and 300.
I guess it’s not the template, but something else.

Yes, I know, but I would like to learn how to do such things in HA as well :slight_smile:

Did you look in states to see if it changing to 0?

yes, in states it’s changing in the same way as in the frontend

If this code gives me the right value (189 cm): (It really works)

- platform: mqtt
  state_topic: "/garden-01/01/Distance" # ESPeasy
  name: "Water_level" # ESPeasy
  unit_of_measurement: cm

Should this code provide the same value (189 cm)?

- platform: mqtt
  state_topic: "/garden-01/01/Distance" # ESPeasy
  name: "Water_level" # ESPeasy
  value_template: "{{ states.sensor.water_level.state }}"
  unit_of_measurement: cm

I’m asking, because I think, the second code is equivalent with the first one.
But the second gives an “unknown” value…

I think the problem is that you are trying to use the state of the sensor, but the value_template is the code that actually sets the state of the sensor. You need to use value in the template, which gets the value from the incoming message.

Try something like

value_template: "{{ 300 - (value | int) }}"
5 Likes

Thank you all for the support, especially @gpbenton: this is the method I was looking for.
Now the working code is as follows:

- platform: mqtt
  state_topic: "/garden-01/01/Distance" # ESPeasy
  name: "Water_level" # ESPeasy
  value_template: "{{ 300 - (value | int) }}"
  unit_of_measurement: cm
3 Likes

Thanks you made my day. Had the calculation in the esp. This is better.

1 Like