How can avoid "unavailable" or "unknown" state in statistics template?

Hello,
I’ve got a ‘OpenWeatherMap Forecast Precipitation’ sensor. It works fine, however sometimes, when there is no precipitation at all, it shows the state “unavailable” or “unknown”. I count the sum for next 12 hours by the “statistics” template from this sensor. I use it to check if should I water the garden if it exceeds the threshold.

But how can I change “unavailable” or “unknown” state for simple 0.0 value? I tried value_template, but it does not work in statistics template.

sensor:
  - platform: statistics
    name: "Precipitation in next 12 hours"
    entity_id: sensor.openweathermap_forecast_precipitation
    state_characteristic: sum
    max_age:
      hours: 12

Yeah, that is not listed as an option in the documents: https://www.home-assistant.io/integrations/statistics/#configuration-variables

You can create a template sensor to filter your statistics sensor.

template:
  - sensor:
      - name: "Filtered Precipitation in last 12 hours"
        unit_of_measurement: "mm"
        device_class: precipitation
        state_class: measurement ### only include this line if you want long term statistics. 
        state: "{{ states('sensor.precipitation_in_next_12_hours') if states('sensor.precipitation_in_next_12_hours')|is_number else 0 }}"
3 Likes

Whoah! That’s a prompt message! Thanks! It looks that it does what I wanted.
But can you explain the syntax further? I understand the ending "|is_number else 0 (that’s quite obvious), but the beginning looks odd…?
Is the first part a declaration and then the condition “if…”?

state: "{{ states('sensor.precipitation_in_next_12_hours') if states('sensor.precipitation_in_next_12_hours')|is_number else 0 }}"

Basically: x if x is convertible to a number else 0.

Where x is the state value of your statistics sensor.

I could also have written it like this:

state: >
  {% if states('sensor.precipitation_in_next_12_hours')|is_number %}
    {{ states('sensor.precipitation_in_next_12_hours') }}
  {% else %}
    0
  {% endif %}
4 Likes

Ok, now it’s quite clear. Thank you.

1 Like