diff --git a/homeassistant/components/unifiprotect/sensor.py b/homeassistant/components/unifiprotect/sensor.py index 0fcd4f5853d..ea2c84bb128 100644 --- a/homeassistant/components/unifiprotect/sensor.py +++ b/homeassistant/components/unifiprotect/sensor.py @@ -2,9 +2,10 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Callable, Sequence from dataclasses import dataclass from datetime import datetime +from functools import partial import logging from typing import Any @@ -62,12 +63,19 @@ class ProtectSensorEntityDescription( precision: int | None = None - def get_ufp_value(self, obj: T) -> Any: - """Return value from UniFi Protect device.""" - value = super().get_ufp_value(obj) - if self.precision and value is not None: - return round(value, self.precision) - return value + def __post_init__(self) -> None: + """Ensure values are rounded if precision is set.""" + super().__post_init__() + if precision := self.precision: + object.__setattr__( + self, + "get_ufp_value", + partial(self._rounded_value, precision, self.get_ufp_value), + ) + + def _rounded_value(self, precision: int, getter: Callable[[T], Any], obj: T) -> Any: + """Round value to precision if set.""" + return None if (v := getter(obj)) is None else round(v, precision) @dataclass(frozen=True, kw_only=True) diff --git a/tests/components/unifiprotect/test_sensor.py b/tests/components/unifiprotect/test_sensor.py index 1a1374390ae..a3155376a05 100644 --- a/tests/components/unifiprotect/test_sensor.py +++ b/tests/components/unifiprotect/test_sensor.py @@ -508,10 +508,10 @@ async def test_sensor_update_alarm_with_last_trip_time( assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION -async def test_camera_update_licenseplate( +async def test_camera_update_license_plate( hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera, fixed_now: datetime ) -> None: - """Test sensor motion entity.""" + """Test license plate sensor.""" camera.feature_flags.smart_detect_types.append(SmartDetectObjectType.LICENSE_PLATE) camera.feature_flags.has_smart_detect = True @@ -560,3 +560,17 @@ async def test_camera_update_licenseplate( state = hass.states.get(entity_id) assert state assert state.state == "ABCD1234" + + +async def test_sensor_precision( + hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor, fixed_now: datetime +) -> None: + """Test sensor precision value is respected.""" + + await init_entry(hass, ufp, [sensor_all]) + assert_entity_counts(hass, Platform.SENSOR, 22, 14) + nvr: NVR = ufp.api.bootstrap.nvr + + _, entity_id = ids_from_device_description(Platform.SENSOR, nvr, NVR_SENSORS[6]) + + assert hass.states.get(entity_id).state == "17.49"