Need some insight on binary sensor

Trying to show the total time the heating was on in the last 30 days based on whether any of my 3 thermostats’ hvac actions was set to heating.

Below is what I have in my configuration.yaml

However, this seems to only return the total time as in image below.

Where am I going wrong here?

recorder:
  include:
    entities:
      - binary_sensor.all_thermostats_heating

binary_sensor:
  - platform: template
    sensors:
      all_thermostats_heating:
        friendly_name: "All Thermostats Heating"
        value_template: >
          {{ 
            is_state_attr('climate.living_room', 'hvac_action', 'heating') or
            is_state_attr('climate.main_bedroom', 'hvac_action', 'heating') or
            is_state_attr('climate.livs_room', 'hvac_action', 'heating') 
          }}

sensor:
  - platform: history_stats
    name: Total Heating Hours
    entity_id: binary_sensor.all_thermostats_heating
    state: "on"
    type: time
    start: "{{ as_timestamp(now()) - 24 * 60 * 60 }}"
    end: "{{ as_timestamp(now()) }}"

image

What does the history graph for this show binary_sensor.all_thermostats_heating?

Also what happens if you use datetimes instead of timestamps?

    start: "{{ now() - timedelta(days = 1) }}"
    end: "{{ now() }}"

Hi Tom

Thanks for responding, much appreciated!

History graph shows:
image

Changing the Sensor start and end as so:

sensor:
  - platform: history_stats
    name: Total Heating Hours
    entity_id: binary_sensor.all_thermostats_heating
    state: "on"
    type: time
    start: "{{ now()) - timedelta(days = 1) }}"
    end: "{{ now() }}"

Gives me an error on the configuration check:
Configuration warnings

Invalid config for ‘history_stats’ from integration ‘sensor’ at configuration.yaml, line 35: invalid template (TemplateSyntaxError: unexpected ‘)’) for dictionary value ‘start’, got ‘{{ now()) - timedelta(days = 1) }}’

Should be now()

As the error says:

TemplateSyntaxError: unexpected ‘)’

right, my bad

This gives:
image

It seems to be counting down somehow?

If you are using a “shifting” timeframe - then yes, it can be decreasing.

I had a lengthy discussion with the code owner a while back about history stats. One of the takeaways from that was that if there is absolutely no history before the start of the timeframe, the results are wrong. In that case the assumption is made that the first state it sees in the timeframe also applies since the start of the timeframe (before the sensor even existed), explaining the 23 hours on. So tomorrow the sensor should behave better.

And as Tom said, because you’re using a timeframe of the last 24 hours instead of today, the value can decrease. So during today it will decrease until it is correct.

1 Like

Okay, that would explain things.
No more need to keep banging my head against this issue then.

I’ll wait and see what the sensor does tomorrow