I populate a sensor via a REST call and I have an automation setup to update it periodically. However sometimes the REST call fails and returns an error. In those cases I fall back to other less reliable sources.
- platform: rest
name: openuv_custom
resource: "https://api.openuv.io/api/v1/uv?lat=50.661972&lng=-120.271317"
method: GET
headers:
x-access-token: !secret openuv_api_token
unit_of_measurement: "UV index"
scan_interval: 86400 # 86400 = 1 day. Automation handles periodic updates under certain conditions to stay under API limits
json_attributes_path: "$.result"
json_attributes:
- uv
- uv_max
value_template: "{{ value_json.result.uv }}"
...
openuv_current_uv_index:
unit_of_measurement: UV index
value_template: "{{ state_attr('sensor.openuv_custom', 'uv') }}"
...
current_uv_index_rounded:
unit_of_measurement: UV index
friendly_name: Current UV Index Rounded
icon_template: "mdi:weather-sunny"
value_template: >
{% if states('sensor.openuv_current_uv_index') != 'unavailable' and states('sensor.openuv_current_uv_index') != 'unknown' and states('sensor.openuv_current_uv_index') != 'None' %}
{{ states('sensor.openuv_current_uv_index') | round(1) }}
{% else %}
{{ states('sensor.uv_current_mean') | round(1) }}
{% endif %}
However I would prefer to just keep the value from the last successful call of the more reliable primary source. Is there a way I can effectively “cache” the value from the last successful REST call? For example is there a way to update another sensor value when the main REST call happens and is successful and in the template fall back to that instead?
FYI: I am aware of the OpenUV integration but decided to do a custom approach to work around some of it’s limitations