diff --git a/homeassistant/components/prometheus/__init__.py b/homeassistant/components/prometheus/__init__.py index e0c82061c2c..2eb4193377d 100644 --- a/homeassistant/components/prometheus/__init__.py +++ b/homeassistant/components/prometheus/__init__.py @@ -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 diff --git a/tests/components/prometheus/test_init.py b/tests/components/prometheus/test_init.py index 0fdbc23bb07..f9f6ebbf0f5 100644 --- a/tests/components/prometheus/test_init.py +++ b/tests/components/prometheus/test_init.py @@ -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",'