I’m looking to get a sensor that tells me how long a switch is currently running for. I want it to reset when the switch is off. So if the switch is on, i know how long it’s been on for. I want to use this time in another program.
'- platform: history_stats
name: Air exchange on time
entity_id: switch.shelly1_e8db84d73b52
state: "on"
type: time
start: "{{ 0 }}"
end: "{{ now() }}"'
There used to be a way to do it using the History Stats integration, but it stopped working around June last year and, AFAIK, is still broken/bugged. Currrently, one way to do it is to use two template sensors.
template:
- trigger:
- platform: state
entity_id: switch.shelly1_e8db84d73b52
to: 'on'
from: 'off'
sensor:
- name: Air Exchange Last On
state: "{{ now() }}"
- sensor:
- name: Air Exchange On Time
state: >
{% if is_state('switch.shelly1_e8db84d73b52', 'off') %}
0
{% else %}
{{ (now() - states('sensor.air_exchange_last_on') | as_datetime).total_seconds/3600 }}
{% endif %}
I’m using history_stats without issue. However, it doesn’t do what you’re after in the way you’ve defined it. Going from {{ 0 }} to {{ now() }} will give you the total on-time in your history (up to the purge days), not the amount of time it has currently been on.
One way to do this would be use a counter helper that resets to 0 when the switch turns off, and adds 1 every minute the switch is on. Alternatively, store the current time when it comes on in a datetime helper, and then have a template sensor calculate the difference between now and that time if the switch is currently on.