When defining a template sensor for use in the energy dashboard it is important to also use the availability template option. Without this you may see incorrect values in your energy dashboard.
For example, consider this template sensor that sums two energy sensors to obtain a total:
template:
- sensor:
- name: "Energy Total"
unique_id: 094412db-6903-dead-beef-b40e0e41ea28
device_class: energy
state_class: total_increasing
unit_of_measurement: kWh
state: "{{ states('sensor.one') | float(0) + states('sensor.two') | float(0) }}"
If one of the source sensors becomes unavailable
or unknown
for some reason the total will drop in value. When the sensor becomes available again the total will increase. This increase will be incorrectly logged to the energy dashboard as actual energy used.
To prevent this we add an availability template:
template:
- sensor:
- name: "Energy Total"
unique_id: 094412db-6903-dead-beef-b40e0e41ea28
device_class: energy
state_class: total_increasing
unit_of_measurement: kWh
state: "{{ states('sensor.one') | float(0) + states('sensor.two') | float(0) }}"
availability: "{{ has_value('sensor.one') and has_value('sensor.two') }}"
Now if one (or both) of the source sensors become unavailable
the total sensor value will also be set to unavailable
.
Changing from unavailable
to a value is not logged by the energy dashboard.
If using attributes you can use is_number
instead of has_value
, e.g.
availability: "{{ state_attr('sensor.one','energy')|is_number and has_value('sensor.two') }}"
There are other ways to construct the availability template, the important thing is that it must only evaluate to true
when all your source sensors are reporting valid numeric state values.
NOTE: I used the simplest possible example here. If you only want to add two sensors you can do this in the UI using the Min / Max Helper from the Settings menu (set the State Characteristic option to āSumā) and it will take care of the availability for you.