Skip to content

Commit

Permalink
Setting extra_state_attributes on sensor
Browse files Browse the repository at this point in the history
  • Loading branch information
iprak committed Aug 28, 2024
1 parent e26d294 commit 6021369
Showing 1 changed file with 24 additions and 16 deletions.
40 changes: 24 additions & 16 deletions custom_components/sensi/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from collections.abc import Callable
from dataclasses import dataclass
from typing import Final
from typing import Any, Final

from homeassistant.components.sensor import (
ENTITY_ID_FORMAT,
Expand All @@ -25,19 +25,13 @@
from .coordinator import SensiDevice, SensiUpdateCoordinator


@dataclass
class SensiSensorEntityDescriptionMixin:
"""Mixin for Sensi thermostat sensor."""

value_fn: Callable[[SensiDevice], StateType]


@dataclass
class SensiSensorEntityDescription(
SensorEntityDescription, SensiSensorEntityDescriptionMixin
):
@dataclass(frozen=True)
class SensiSensorEntityDescription(SensorEntityDescription):
"""Representation of a Sensi thermostat sensor."""

extra_state_attributes_fn: Callable[[Any], dict[str, str]] | None = None
value_fn: Callable[[SensiDevice], StateType] = None


SENSOR_TYPES: Final = (
SensiSensorEntityDescription(
Expand Down Expand Up @@ -124,12 +118,26 @@ def __init__(
@property
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
return self.entity_description.value_fn(self._device)
return (
self.entity_description.value_fn(self._device)
if self.entity_description.value_fn
else None
)

@property
def native_unit_of_measurement(self) -> str | None:
"""Return the unit of measurement of the sensor, if any."""
if self.entity_description.device_class == SensorDeviceClass.TEMPERATURE:
return self._device.temperature_unit
return (
self._device.temperature_unit
if self.entity_description.device_class == SensorDeviceClass.TEMPERATURE
else self.entity_description.native_unit_of_measurement
)

return self.entity_description.native_unit_of_measurement
@property
def extra_state_attributes(self) -> dict[str, str] | None:
"""Return the state attributes."""
return (
self.entity_description.extra_state_attributes_fn(self._device)
if self.entity_description.extra_state_attributes_fn
else None
)

0 comments on commit 6021369

Please sign in to comment.