I have an RF weather sensor that gives me cumulative rainfall via MQTT since it was powered on.
I want to see the rainfall since midnight, so I use the following to store the rain to midnight yesterday as a reference value in mqtt (to ensure it survives any HASS restarts etc):
sensor:
# Rain is cumulative forever - collect it and subtract yesterday for todays rain
- platform: mqtt
state_topic: 'RF/DKW2012-ID=004c'
name: 'rain_cum'
icon: mdi:weather-rainy
unit_of_measurement: 'mm'
value_template: '{{ value_json.RAIN }}'
- platform: mqtt
state_topic: 'ha/cum_rain_prior'
name: 'rain_cum_prior'
unit_of_measurement: 'mm'
value_template: '{{ value_json.day_1 }}'
- platform: template
sensors:
rain:
value_template: '{%- if not (is_state("sensor.rain_cum","unknown") or is_state("sensor.rain_cum_prior","unknown") )-%} {{ ((states.sensor.rain_cum.state | float) - (states.sensor.rain_cum_prior.state | float)) | max (0) | round(1) }} {%- endif -%}' ## ensure calc is no lower than zero!
friendly_name: 'Rain Today'
unit_of_measurement: 'mm'
Plus an automation to roll over the daily value after midnight:
automation:
- alias: 'record cumulative rain to midnight'
trigger:
- platform: time
at: "00:00:01"
action:
service: mqtt.publish
data_template:
topic: 'ha/cum_rain_prior'
retain: true
payload: '{"day_1":"{{states.sensor.rain_cum.state}}"}'
Gives me cumulative rain for the day ending midnight like so:
The templating took a bit of trial and error to ensure missing values were excluded from the maths … otherwise you can get negative rain at some points in the day if mqtt glitches!
Hope someone else finds this useful.
Phil