History_stats from last_triggered

hi,

i have set up a sensor to determine how long a switch has been on since an automation has been triggered

here is my code

sensor
  - platform: history_stats
    name: filtration UpTime since last auto start
    state: 'on'
    entity_id: switch.tz3000_pompe_piscine
    start: "{{state_attr('automation.pool_filtration_cycle_start', 'last_triggered') }}"
    end: "{{ now() }}"

i don’t understand why sometimes the sensor is not updating and stay at 0

image

image

any clue ?

Could it be because there was no state change inside the period from the last trigger to now? I had a lengthy discussion in another thread on the behaviour of the history stats sensor with regard to value before the first logged entry in that period. But what actually happens if the period has no state change in it I’m not sure. From that I would have guessed this would work, but if it does not then this does seem like a bug.

What happens if you set the history sensor to start a little bit earlier by substracting a minute or so as a workaround? What happens if you turn it off, wait a few seconds and turn it on again?

And are you sure the template evaluates to the same start time you see in the gui?

yes i have triple checked
the automation gui in screenshot is automation.pool_filtration_cycle_start

when i try it on dev/template i have the correct start date

i changed it by

sensor
  - platform: history_stats
    name: filtration UpTime since last auto start
    state: 'on'
    entity_id: switch.tz3000_pompe_piscine
    start: "{{(state_attr('automation.pool_filtration_cycle_start', 'last_triggered') - timedelta(minutes=1)) }}"
    end: "{{ now() }}"

it seems to work now !
the 1 minute workaround did the trick, thanks

1 Like

I think you should report this as a bug, as this is quite a normal use case and it is pretty evident the result is not right. The workaround will not work for every one.

1 Like

FWIW, here’s the result of a simple experiment I performed with a History Stats sensor.

  • I chose an entity whose state hasn’t change in months. It’s an automation that’s been on since it was created last March.
  • The History Stats sensor is configured to report how long the entity has been on for the current day (i.e. from midnight until the current time).
sensor:
  - platform: history_stats
    name: Example Today
    entity_id: automation.days_example
    state: 'on'
    type: time
    start: "{{ today_at() }}"
    end: '{{ now() }}'
  • After restarting Home Assistant, the History Stats sensor was loaded and immediately reported automation.days_example was on for 0.0 hours. Ten minutes later, it still reported zero hours. In other words, it reported the entity had been on for zero hours since midnight despite the fact it has been on since March.

  • I turned off automation.days_example then turned it back on. About a minute later, the History Stats sensor reported 0.02 hours.

The result implies if there’s no state-change to the desired state, during the specified time period, the History Stats sensor will not start counting time. It requires a state-change to begin counting.

When you changed start to be one minute earlier, you expanded the time period to just before the moment the pump switch was turned on. In other words, the expanded time period now incorporated the pump’s state-change to on (and provided the History Stats sensor with the state-change it needs to see in order to begin counting).

1 Like

Yes, that was the intent of my suggestion to work around the problem. Nice to see your experiments confirming my suspicions.

I do think this means the sensor does not live up to its promises. The documentation states it can be used to see e.g. how long a sensor has been in its state since the start of the day. But if the sensor was in that state at the start of the day, it may not get counted. And the chance of that is biggest for a binary sensor. The above example shows it can be wrong for hours in total. If it does not count being already in that state, the docs should mention it. And personally I think it makes the sensor useless the way it is now.

I agree with you that the documentation, in its current form, is misleading; there’s no mention of state-changes so one gets the impression it doesn’t use that to determine when to start counting.

In the experiment I performed, the documentation leads one to believe the resulting History Stats sensor will immediately report the entity has been on for several hours since midnight (because it’s been on since March). However, it reported zero because it hasn’t detected a state-change since midnight and that specific behavior isn’t suggested anywhere in the documentation.

Just a thought but maybe the documentation describes the original behavior of History Stats but one of the many changes made to its code over past few months has altered it to what we experience now and either it was overlooked to update the docs or, worst case, the new behavior is unintentional. :thinking:

I really appreciate the many changes to optimize the database, but I feared consequences like these. It is kind of to be expected that side effects of the changes occur, and I guess this is one of them. This is really hard to get right. Luckily, the fixes also come at high pace most of the time, if people take the time to report them.

If it was on since March then I expect it to go wrong even more, since the change will likely have been purged already. But the case of the poster is a more likely scenario I’d want to go right for this sensor to be of use. Binary sensors are it’s most likely use case, and they only store changes. They have 50% chance of being in the wanted state at the start of the period, and are not likely to change quickly after.

i reported the issue

2 Likes

This still seems to be broken in 2022.7

it’s still working with 2022.7 on my side

Are you able to explain what I might be doing wrong? For me when a switch is turned on the counter does not start unless I reload the history stat service. When I turn the switch off the counter restarts at 0 and starts counting up again.

Here is my code:

- platform: history_stats
  name: stats camera
  entity_id: switch.camera
  state: "on"
  type: time
  start: "{{ as_timestamp(states.switch.camera.last_changed) }}"
  end: "{{ as_timestamp(now()) }}"
  scan_interval: 60

here is my code

  - platform: template
    sensors:
      last_autostart_triggered_since:
        friendly_name: 'duration since last autofiltration was triggered'
        value_template: >
         {{ (( now().timestamp() - as_timestamp(state_attr('automation.pool_filtration_cycle_start','last_triggered')) ) / 3600 )
           | round(2) }}
        icon_template: mdi:chart-areaspline-variant
        unit_of_measurement: 'hours'

That’s code for a Template Sensor (in legacy format). This topic concerns the behavior of the History Stats Sensor.

oh yes ! you are right
i just noticed that i have switched to template sensore because i had trouble to make the history stat work

This is still broken for me on 2022.9. Is anyone else still having problems with it?

Did you have some progress with this? I have the same issue in HA 2023.10.2:

With this code:

  - platform: history_stats
    name: Laddbox Laddtid4
    unique_id: laddbox_laddtid4
    entity_id: binary_sensor.laddbox_laddar
    state: "on"
    type: time
    start: "{{ state_attr('automation.laddbox_tid_start', 'last_triggered')  - timedelta(minutes=1) }}" 
    end: "{{ now() }}"

The history_state will not update until I restart HA or call the service history_stats: reload

But with this code, where the start time is from a input_datetime from the same automation as above, it works as intended.

  - platform: history_stats
    name: Laddbox Laddtid5
    unique_id: laddbox_laddtid5
    entity_id: binary_sensor.laddbox_laddar
    state: "on"
    type: time
    start: "{{ states('input_datetime.laddbox_tid_laddstart') | as_datetime | as_local }}"
    end: "{{ now() }}"

Maybe its just that you can’t have a state_attr object as start condtion, because it listens to a state change?