brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: has_value() checks that a Home Assistant entity has a usable state

Yaml
~/tips/tip-home-assistant-template-has-value

Sensor is available

has_value() is true only when the entity exists and is not unavailable or unknown.

A sensor that goes unavailable at the wrong moment can wreck an automation that does math on its state. I like a guard that says so up front, and has_value is that guard in one word.

The docs describe it as a test that an entity exists and has a valid state, meaning not unavailable and not unknown. It comes in three forms:

{{ has_value("sensor.temperature") }}
{{ "sensor.temperature" | has_value }}
{% if "sensor.temperature" is has_value %}
  Sensor is available
{% endif %}

A typical use is a template condition at the top of an automation, or a guard inside a template:

{{ states("sensor.temperature") | float if has_value("sensor.temperature") else 0 }}

That way a sensor that dropped off the network gives a fallback instead of an error in the log.

The caveat is the size of the promise. has_value tells you the state is not one of the two broken ones. It does not tell you the state is a number. A text sensor passes happily, and so does a state like idle. If you do math on it, the template functions list also has an is_number test for that.

The docs list it as available since Home Assistant 2023.3.

Further reading: has_value in the Home Assistant template functions

More Yaml tips yamllint -f parsable config.yaml yamllint -d relaxed docker-compose.yml iif(condition, if_true, if_false, if_none) Today_at() makes time-of-day checks in Home Assistant templates easy actions: All Yaml tips (10) All topics

Link