Fix precision for unifiprotect sensors (#119781)

This commit is contained in:
J. Nick Koston 2024-06-16 13:54:58 -05:00 committed by GitHub
parent 54e6459a41
commit 03027893ff
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 31 additions and 9 deletions

View File

@ -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)

View File

@ -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"