Help with incorrect template (binary sensor using history)


I’ve made a few templates which work fine, but now I’m trying to make one which uses history to detect if either of two temperature sensors have been below 0C in the last 8h, and if so, set a boolean to true. However it does not work, just showing as “Unavailable” in HA. Can anyone tell directly what is wrong, and/or how I can best debug it? Thanks!

(I have ‘default config:’ in my configuration.yaml so I believe the history and recorder integrations are enabled … however they are not shown under settings/integrations?)

  - platform: template
        friendly_name: "Outdoors temperature below zero last 8h"
        unique_id: outdoors_temperature_below_zero
        value_template: >
          {% set th001_history = states(sensor.telldusfineoffset183_temperature.history('-8h')) %}
          {% set th002_history = states(sensor.ute_temperature.history('-8h')) %}
          {% set th001_below_zero = th001_history | selectattr('state', 'lt', 0) | list %}
          {% set th002_below_zero = th002_history | selectattr('state', 'lt', 0) | list %}
          {{ th001_below_zero | count > 0 or th002_below_zero | count > 0 }}
        icon_template: mdi:thermometer-alert
        device_class: "cold"

This is invalid.


Where did you get the idea to do that?

I am ashamed to admit that I trusted ChatGPT with this :smiley: (it had worked fine for templates w/o history)… but I know of it’s propensity to fabricate stuff, so…

So, anyways, what is the correct way to use history for a sensor…?

I suspected as much.

It would be nice if something like history('-8h') existed but it doesn’t; ChatGPT made it up.

To access an entity’s recent history requires querying the database using a SQL query. It’s far more complicated than what ChatGPT fabricated.

Perhaps another way to achieve your goal is to create a Trigger-based Template Sensor that monitors both temperature sensors and records the time when either of them reports a value less than 0.

  - trigger:
      - platform: template 
        value_template: |
          {{ states('sensor.telldusfineoffset183_temperature') | int(1) < 0 or
              states(sensor.ute_temperature') | int(1) < 0 }}
       - name: "Outdoors temperature below zero last 8h"
         unique_id: outdoors_temperature_below_zero
         value_template: "{{ now().isoformat () }}"
         device_class: "timestamp"

An Entities card will display this sensor’s value as a relative time. If the displayed time is over 8 hours then it means the temperature hasn’t been below 0 in the past 8 hours.

1 Like

Great, thanks a lot, that’ll do now that I understand that ChatGPT lied to me (it tricked me with some correct/working templates at first though) and that it’d be more complicated.

I’m thinking another solution could be to use History stats to show how much time had been spent below 0, and then a binary sensor based on that (but then I would need a “time below 0” as a state somehow).