I’m trying to find a way to take a sensor value (I’ll call this daily_sensor) I have in Home Assistant and create a new sensor (I’ll call sum_sensor) that will be the sum of the value of daily_sensor taken at the end of each day.
The problem might be better described in pseudocode.
I’m trying to keep this generic so it’s more useful for people in the future searching for the same thing but as an example say I have a sensor which holds the total kWh used in one day, so resets to 0 at the start of each day (and this resetting to 0 is outside of your control). I want a sensor which holds the total kWh ever consumed and for it to be preserved after a Home Assistant restart.
After some searching I came up with one method of doing it which involves saving the sensor value to a text file in an automation each day (shown here: Export sensor data to text file) and then use Node-RED to try and sum these values and update the sum_sensor.
I also found the Utility Meter integration and while this looks good there is no option for the reset cycle to be set to never and also it would poll the sensor_daily to often which ruin the data because the sensor itself is already a daily sum.
I just wondered before I started trying to implement the Node-RED method (which just seems a bit unintuitive for me for what seems like a straightforward problem) if someone had a better idea or even a solution that’s built into Home Assistant that I’ve missed.
there have been some discussions in the forums recently about that subject and I believe the consensus is that template sensor don’t survive restarts so this one won’t either.
it’s likely best to use an automation to update the input number or some other variable that will survive restarts.
Thank you all for your help. I’ve just played around with stuff and this seems to work with the value being preserved after restart. I don’t know if it’ll survive a hard shutdown and restart but I’m not willing to test that…
input_number:
sum_sensor:
name: Sum Sensor
min: 0
max: 1000000
step: 0.01
mode: box
automation:
- alias: "Increment Sensor Sum"
description: 'Add the value of sensor daily to sum_sensor at the end of each day'
trigger:
- platform: time
at: "23:59:00"
condition: []
action:
- service: input_number.set_value
data:
value: "{{ states('input_number.sum_sensor')|float + states('sensor.daily_sensor')|float }}"
target:
entity_id: input_number.sum_sensor
mode: single
A few things to note is that max is required when creating your input_number and automation wasn’t happy if I didn’t include the step: 0.01. This might be because Home Assistant will treat it like an int so then adding a float to it isn’t allowed but I’m not sure.
The input_number integration page has a few more examples of use within automations: