Support numeric sensors with no unit_of_measurement in prometheus (#60157)

This commit is contained in:
alim4r 2021-11-24 22:30:08 +01:00 committed by GitHub
parent 5853d81944
commit 42389fc81b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 5 deletions

View File

@ -418,9 +418,11 @@ class PrometheusMetrics:
break
if metric is not None:
_metric = self._metric(
metric, self.prometheus_cli.Gauge, f"Sensor data measured in {unit}"
)
documentation = "State of the sensor"
if unit:
documentation = f"Sensor data measured in {unit}"
_metric = self._metric(metric, self.prometheus_cli.Gauge, documentation)
try:
value = self.state_as_number(state)
@ -458,8 +460,12 @@ class PrometheusMetrics:
def _sensor_fallback_metric(state, unit):
"""Get metric from fallback logic for compatibility."""
if unit in (None, ""):
_LOGGER.debug("Unsupported sensor: %s", state.entity_id)
return None
try:
state_helper.state_as_number(state)
except ValueError:
_LOGGER.debug("Unsupported sensor: %s", state.entity_id)
return None
return "sensor_state"
return f"sensor_unit_{unit}"
@staticmethod

View File

@ -100,6 +100,21 @@ async def prometheus_client(hass, hass_client, namespace):
sensor5.entity_id = "sensor.sps30_pm_1um_weight_concentration"
await sensor5.async_update_ha_state()
sensor6 = DemoSensor(None, "Trend Gradient", 0.002, None, None, None, None)
sensor6.hass = hass
sensor6.entity_id = "sensor.trend_gradient"
await sensor6.async_update_ha_state()
sensor7 = DemoSensor(None, "Text", "should_not_work", None, None, None, None)
sensor7.hass = hass
sensor7.entity_id = "sensor.text"
await sensor7.async_update_ha_state()
sensor8 = DemoSensor(None, "Text Unit", "should_not_work", None, None, "Text", None)
sensor8.hass = hass
sensor8.entity_id = "sensor.text_unit"
await sensor8.async_update_ha_state()
number1 = DemoNumber(None, "Threshold", 5.2, None, False, 0, 10, 0.1)
number1.hass = hass
number1.entity_id = "input_number.threshold"
@ -241,6 +256,24 @@ async def test_view_empty_namespace(hass, hass_client):
'friendly_name="SPS30 PM <1µm Weight concentration"} 3.7069' in body
)
assert (
'sensor_state{domain="sensor",'
'entity="sensor.trend_gradient",'
'friendly_name="Trend Gradient"} 0.002' in body
)
assert (
'sensor_state{domain="sensor",'
'entity="sensor.text",'
'friendly_name="Text"} 0' not in body
)
assert (
'sensor_unit_text{domain="sensor",'
'entity="sensor.text_unit",'
'friendly_name="Text Unit"} 0' not in body
)
assert (
'input_number_state{domain="input_number",'
'entity="input_number.threshold",'