I have a sensor have 3 states (ON, Off, ON-LPI)
I am trying to set up a history states sensor to calculate how much time the sensor is in (ON-LPI) state before changing to other states,
In other words, time reset and recalculate when back to (ON-LPI) state
thanks
Have you looked into the history_stats integration? I should think that would do what you are looking for.
I do, talk about timed start end at xx: xx time
I’m looking for something to calculate how much time the sensor stays in state and reset this time after the changing state
for example
sensor.x ======> ON 5pm to 6PM
sensor.x ======> Off 6pm to 7PM
sensor.x ======> ON-LPI 8pm to 9PM >>>>>> result 1h
sensor.x ======> Off10pm to 11PM
sensor.x ======> ON-LPI 11pm to 11:30PM >>>>>> result 30min
Etc
Check out this post there are a couple of solutions there that might work for you:
@Control I’m not sure if you solved this issue for yourself yet, but I was trying to do a very similar thing to you. This is how I got mine working. My goal was to get the average time a sensor was in the off and on state. To do this I used 3 sensors for each state.
- History Stats sensor to total the amount of time the sensor was in the desired state in the last 24 hours.
- History Stats sensor to count the number of times the sensor was in the desired state in the last 24 hours.
- Template sensor to divide the amount of time by the count to get the average. This sensor converts the hours that the history stats sensor outputs to seconds and does error checking to ensure we don’t encouter a divide by zero error.
I hope this helps you or anyone else who comes across this issue.
- platform: history_stats
name: Office EP-1 mmWave 24h Off Count
entity_id: binary_sensor.office_ep_1_mmwave
state: "off"
type: count
start: "{{ now() - timedelta(hours=24) }}"
end: "{{ now() }}"
- platform: history_stats
name: Office EP-1 mmWave 24h Off Time
entity_id: binary_sensor.office_ep_1_mmwave
state: "off"
type: time
start: "{{ now() - timedelta(hours=24) }}"
end: "{{ now() }}"
- platform: template
sensors:
office_ep1_mmwave_average_off_time:
unique_id: sensor.office_ep1_mmwave_average_off_time
friendly_name: Office EP-1 Average Off Time
unit_of_measurement: s
icon_template: mdi:timer
value_template: >
{% set off_count = states("sensor.office_ep_1_mmwave_24h_off_count") | int %}
{% if off_count > 0 %}{{ ((states("sensor.office_ep_1_mmwave_24h_off_time")|float * 3600) | int / off_count) | round(1) }}
{% else %}0{% endif %}
Thanks for sharing the sample configuration, this is really helpful.
One question though: How would you solve the following? I would like to see the duration of a sensor’s specifc state for the current week (starting on Monday) not the last 24 hours.
Thanks for the hints
I think ChatGPT just gave me the answer to my question:
start: "{{ now().replace(hour=0, minute=0, second=0) - timedelta(days=now().weekday()) }}"