Automation: Alternative condition if sensor is not available

Hi,

Is there a way that you can test if a sensor is available in automation and if not you supply an alternative to make sure the automation will never fail :slight_smile:
Sometimes a sensor is not available and then my automation will fail.

Thanks

Marcel

1 Like

You can do this with a template condition.

condition: template
value_template: >
  {% if states('sensor.sensor_1') == 'unavailable' %}
    {{ states('sensor.sensor_2')|float > 42 }}
  {% else %}
    {{ states('sensor.sensor_1')|float > 42 }}
  {% endif %}

You can also do it without template conditions but it is not as compact:

condition: or
conditions:
- condition: and
  conditions:
  - condition: not
    conditions:
    - condition: state
      entity_id: sensor.sensor_1
      state: 'unavailable'
  - condition: numeric_state
    entity_id: sensor.sensor_1
    above: 42
- condition: and
  conditions:
  - condition: state
    entity_id: sensor.sensor_1
    state: 'unavailable'
  - condition: numeric_state
    entity_id: sensor.sensor_2
    above: 42
4 Likes

Great! Thanks!

Still another question (sorry) can you then also use for: minutes: 1 (against flip flopping?) :slight_smile:

You can also use a logical OR like this but only if 0 is not one of the values normally reported by either sensor:

condition: template
value_template: "{{ states('sensor.sensor_1') | float > 42 or states('sensor.sensor_2') | float > 42 }}"

If either sensor’s state value is unavailable or unknown, the float filter reports 0.

3 Likes

That’s clever.

There’s also an interesting difference in how Home Assistant assigns listeners to the two examples.

In this one, both entities get listeners:

In this one, only the first entity is assigned a listener:

The algorithm it employs prefers to listen to the entities that make “the most difference” (that’s my description and not anything official) in the template’s outcome.

In your template, it doesn’t matter if sensor_2 changes state because, in terms of determining the template’s result, it’s subordinate to sensor_1 owing to its importance in the first line’s if statement.

In my template, the two sensor’s have parity because changes in either one impact the template’s outcome. (However, my template cannot be used for this application if either sensor can normally report 0)

This algorithm’s choices can come as a surprise and is subject of a recent Issue:

2 Likes

Also nice !