Rest sensor - retry or skip if there are connection issues

  - resource: "url"
    scan_interval: 59
    timeout: 300
    binary_sensor:
      - name: "Regen"
        value_template: >-
          {% if value_json %}
            {{ value_json.Regen }}
          {% else %}
            None
          {% endif %}

I am using this rest template to get data. Sometimes the urls are not available for a short time or the json itself delivers None. In both cases the sensor goes to None and triggers my fail safe scripts.

However, I want the sensor to try again x times before setting the sensor to None. So for example it would retry two times - which means after three minutes the state would go to None if the issue persists. If it has to set a value, it could be the last value as well.

Is this possible in the template?

I found the solution:

         - name: "test"
        value_template: >-
          {% if value_json %}
            {{ value_json.data }}
          {% else %}
            {% if now() - states.sensor.timestamp.last_updated < timedelta(minutes=5) %}
              {{states('sensor.test')}}
            {% else %}
              None
            {% endif %}
          {% endif %}
        unit_of_measurement: "%"

      - name: "Timestamp"
        value_template: >-
          {% if value_json %}
            {{ now() }}
          {% else %}
            {{ states('sensor.timestamp') }}
          {% endif %}

If the json value is valid it will be stored in the sensor.
If json is not valid the existing value of the sensor is used for 5 minutes as a backup. After that it goes to None.

Timestamp is needed to get an update on last_update.

2 Likes