Utility meter from mqtt energy sensor


I have a small issue with the utility meter I created to track and group my power consumption.
I have several energy mqtt sensor (one per light) and I sum them all with a template sensor.
I created a utility meter on the template sensor, to track the daily consumption.

The problem is, in some cases the mqtt sensor has a GAP, the cap generates a 0 point in my template and this creates a huge step up in my meter…

Any suggestion on how to solve this?

Code example
   - platform: mqtt
      name: 'light1'
      unique_id: 'MAC_e1'
      qos: 1
      state_topic: 'dingz/MAC/dz1f-pir/energy/light/1'
      device_class: energy
      state_class: total_increasing
      unit_of_measurement: 'Wh'
      value_template: >
            {% if value == 0 %}
            {{ states('sensor.light1') }}
            {% else %}
            {{ value | float / 3600 }}
            {% endif %}
      icon: mdi:lightning-bolt

   - sensor:
      - name: "Lights Energy"
         state: > 
               states('sensor.light1')| float(0) +
               states('sensor.light2')| float(0)
         state_class: total
         device_class: energy
         unit_of_measurement: "Wh"
         unique_id: template.sensor_energy_lights

      name: Light Daily
      source: sensor.lights_energy
      cycle: daily


I don’t think that these steps are caused by the gaps of your MQTT sensors. I think, that sensors are normally scanned and updated in intervalls of 30 seconds and your mqtt sensor will send their data in regular time steps aswell. So there won’t be any values for the time in between these updates.
For MQTT there is the option force_update but you might have to change the update intervall of your MQTT sensors aswell. https://community.home-assistant.io/t/change-scan-interval-for-mqtt-sensor/22851/6?u=ellarso


I had also the problem of random zero values. I used a template sensor that only updates if the value is above 0 and not ‘unknown’.

As additional info:
the gaps are caused by me restarting the MQTT server
(I was tinkering to enable a mqtt bridge)

Thanks for the hint, i’ll check that, but still:

  • I can create a ‘gap’ (by restarting mosquitto)
  • if I create a ‘gap’ I gave a fall to 0 in the template and a step.

I guess he real the problem is the 0 point in the template :slight_smile:

I’ll try to update my template this evening and report back :smiley:

I already did a try like this but it was not enough:

      {% set value = (
        states('sensor.light1')| float(0) +
        states('sensor.light2')| float(0)
      {{ value | is_defined }}