How to have Home Assistant alert you when a sensor is out of range

published Dec 02, 2022

While Home Assistant does not currently support range objects, you can definitely do this using built-in functionality.

How to have Home Assistant alert you when a sensor is out of range

This article is based on the following forum post.

Let's say your Home Assistant setup has a thermometer in your living room, indicating the temperature of the room.  You'd like to be alerted when this temperature falls out of a certain range — let's say, it goes below 19 degrees Celsius or above 26 degrees Celsius.

How do you do that?  There is no entity in Home Assistant that allows you to represent this range of temperatures.  It would also be very tedious to have to hardcode values in your automations — that may be fine for one sensor, but not if you want to supervise 5.  You could do with threshold sensors, but then you'd have to maintain three entities per actual sensor... and your automations would still be very cumbersome to maintain.

No worries!  There's a trick that Home Assistant supports, and it's called manual customization.  In short, you can give any entity any attribute with any value you want.  And we will do exactly that to your living room sensor, complete with automation code that uses this data.

Open up your Home Assistant's configuration.yaml file.  Now ensure that the file has the following under the homeassistant: section (add it if it's not present):

upper: 26
lower: 19

Ensure you adjust this snippet to your sensor name.  Now save the file and restart Home Assistant.

You are ready to create the automation that will alert you.  Create a new automation, going to YAML editing mode, and paste the following (obviously adjusting to your sensor name):

alias: Temp out of range
mode: queued
t_max: "{{ state_attr(trigger.entity_id, 'upper') }}"
t_min: "{{ state_attr(trigger.entity_id, 'lower') }}"
  val: "{{ trigger.to_state.state | float(0) }}"
  - platform: state
    - sensor.living_room_temp
  - condition: template
    value_template: "{{ not t_min < val < t_max }}"
  - service: notify.persistent_notification
    title: "{{ trigger.entity_id }} is out of range."
      message: "Value: {{ val }}, Range: {{ t_min }}, {{t_max }}"

Save the automation and you're done.  Now you will get alerted every time the temperature in your living room goes below 16 or above 26.