MQTT Trigger updates with previous sent value

Hi

I have a slightly odd issue that I’m struggling to understand.

I have a sensor connected via MQTT which sends the amount of rain that falls in a given period, usually 5 minutes. I want to add this to a running total to get the daily rainfall.

Initially I thought I could use a state trigger but this doesn’t appear to work if the value remains the same, ie continuous rain at 1mm per 5 minutes for an hour.

My solution was to create an automation that triggered on receiving an MQTT message then using a template to add it to the total.

I have an input_text helper to store the rain_total and the MQTT payload goes into rain_live and for debugging I display these on a dashboard and can see the MQTT value being displayed correctly.

The oddity is that it appears to update the rain_total with the previous value sent over MQTT, so if I send 0,1,2,3,0 I get totals of 0,0,1,3,6 rather than 0,1,3,6,6

This is the automation:

alias: rain_total
description: ""
trigger:
  - platform: mqtt
    topic: rain_live
condition: []
action:
  - action: input_text.set_value
    metadata: {}
    data:
      value: >-
        {{ states ('input_text.rain_total')|float(0) +
        states('sensor.rain_live')|float(0)}}
    target:
      entity_id: input_text.rain_total
mode: single

Can somebody point me in the right direction.

Cheers

Richard

Just an update:

The issue appears to be timing related. The trigger seems to run before the sensor value is assigned to the sensor via MQTT so the last previous of rain_live is used.

Adding a small delay in the process fixes the issue:

alias: rain_total_test
description: ""
trigger:
  - platform: mqtt
    topic: rain_live
condition: []
action:
  - delay:
      milliseconds: 200
  - action: input_text.set_value
    metadata: {}
    target:
      entity_id: input_text.rain_total
    data:
      value: "{{ states('input_text.rain_total')|float(0) + states('sensor.rain_live')|float(0) }}"
mode: single