Ignore STATE_UNKNOWN in prometheus (#47840)

Giving a value of 0 by default can lead to erroneous
data being exported. For example, if a MQTT temperature
sensor is in `STATE_UNKNOWN` (which can happen after a
HASS restart), a temperature of 0°C will be exported.
Some user might prefer no value rather than a wrong one.
This commit is contained in:
Antoine Meillet 2021-03-16 16:11:51 +01:00 committed by GitHub
parent 673ebe2911
commit 4dc0cdbb5f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -29,6 +29,7 @@ from homeassistant.const import (
PERCENTAGE, PERCENTAGE,
STATE_ON, STATE_ON,
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
STATE_UNKNOWN,
TEMP_CELSIUS, TEMP_CELSIUS,
TEMP_FAHRENHEIT, TEMP_FAHRENHEIT,
) )
@ -154,9 +155,11 @@ class PrometheusMetrics:
if not self._filter(state.entity_id): if not self._filter(state.entity_id):
return return
ignored_states = (STATE_UNAVAILABLE, STATE_UNKNOWN)
handler = f"_handle_{domain}" handler = f"_handle_{domain}"
if hasattr(self, handler) and state.state != STATE_UNAVAILABLE: if hasattr(self, handler) and state.state not in ignored_states:
getattr(self, handler)(state) getattr(self, handler)(state)
labels = self._labels(state) labels = self._labels(state)
@ -168,9 +171,9 @@ class PrometheusMetrics:
entity_available = self._metric( entity_available = self._metric(
"entity_available", "entity_available",
self.prometheus_cli.Gauge, self.prometheus_cli.Gauge,
"Entity is available (not in the unavailable state)", "Entity is available (not in the unavailable or unknown state)",
) )
entity_available.labels(**labels).set(float(state.state != STATE_UNAVAILABLE)) entity_available.labels(**labels).set(float(state.state not in ignored_states))
last_updated_time_seconds = self._metric( last_updated_time_seconds = self._metric(
"last_updated_time_seconds", "last_updated_time_seconds",