Water Consumption with an ultrasonic sensor (SR04)

Hi,

I have a working configuration to display current water level on a water tank built in my basement. It uses a combination of an ultrasonic sensor, SR04, and good old Wemos D1 mini.

The Wemos publishes the current water height to an MQTT server (mosquitto) that is read by the following configuration:

  - name: "water tank"
    state_topic: "watertank/distance"
    unique_id: "watertank.depth"
    value_template: '{{ (326-value | float) | multiply(0.01) | round(2) }}'
    expire_after: 3600

326 being the total height of the tank.

Screenshot_2022-11-17_13-42-32

Now I would like to use the same sensor in order to measure my water consumption.
I came up with the following configuration but while the result given by the state is correct. the result on the energy dashboard is erratic:

  - name: "water tank cubic meters"
    unit_of_measurement: "m³"
    state_topic: "watertank/distance"
    unique_id: "watertank.cubemeters"
    device_class: water
    value_template: '{{ (239-value|int) * 0.2453 | float }}'
    state_class: total_increasing
    force_update: true

Where:

  • 239 is the actual maximum height I can fill the tank with
  • 0.2453 is the result of 80m³ (max tank capacity) / 326 (tank’s height)

I did read this related topic Water sensor template (water tank) for Energy dashboard but I don’t think I’m on the same situation.