For a Home Assistant installation I wanted to display the total time a relay switch has been turned on, since the beginning.
Home Assistant provides the integration history_stats. On the documentation page it is mentioned, that it is possible to show all available history, and an example is showed:
sensor:
- platform: history_stats
name: Lamp ON today
entity_id: light.my_lamp
state: "on"
type: time
start: "{{ 0 }}"
end: "{{ now() }}"
However, I noticed that my sensor was lowering even though time was going up and that it shouldn’t get lower. The reason for this is, that data of entities is only kept for 10 days by default based on the purge_keep_days
value of the recorder integration. Therefore with above example it isn’t possible to add a sensor with all time history for an entity.
I therefore chose to apply following approach. I will create below history_stats
sensors and input field. I use an automation to fill the input field at 0:00:00 midnight with the value of the current template sensor hours_switch_on + the value of yesterday
(which is then just turned yesterday).
sensor:
- platform: template
sensors:
hours_switch_on:
friendly_name: "Hours turned on since beginning."
unit_of_measurement: "h"
value_template: "{{(states.sensor.hours_turned_on_today.state | float) + (states.input_number.value_untill_today.state | float ) | round(1)}}"
- platform: history_stats
name: hours_turned_on_today
entity_id: switch.relay
state: 'on'
type: time
start: "{{ now().replace(hour=0, minute=0, second=0) }}"
end: '{{ now()}}'
- platform: history_stats
name: hours_turned_on_yesterday
entity_id: switch.relay
state: 'on'
type: time
end: "{{ now().replace(hour=0, minute=0, second=0) }}"
duration:
hours: 24
Input number field:
input_number:
value_untill_today:
name: Value untill today
initial: 0
min: 0
step: 0.001
mode: box
Automation:
- id: '1615465816435'
alias: Refresh history input field
description: ''
trigger:
- platform: time
at: '0:00:00'
condition: []
action:
- service: input_number.set_value
data:
value: '{{(states.sensor.hours_switch_on.state) | float + (states.sensor.hours_turned_on_yesterday.state | float)}}'
entity_id: input_number.value_untill_today
mode: single
I want to propose this change to the documentation. Would this be a preferred method or does any else have another way that’s better/more convenient?