2024-02-03 18:42:08 +00:00
|
|
|
"""Generic interface for defining device features."""
|
|
|
|
from dataclasses import dataclass
|
|
|
|
from enum import Enum, auto
|
2024-02-14 17:59:11 +00:00
|
|
|
from typing import TYPE_CHECKING, Any, Callable
|
2024-02-03 18:42:08 +00:00
|
|
|
|
2024-02-14 17:59:11 +00:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from .device import Device
|
2024-02-03 18:42:08 +00:00
|
|
|
|
2024-02-14 17:59:11 +00:00
|
|
|
|
|
|
|
class FeatureCategory(Enum):
|
2024-02-14 18:14:35 +00:00
|
|
|
"""Feature category."""
|
2024-02-03 18:42:08 +00:00
|
|
|
|
|
|
|
# TODO: we could probably do better than using the scheme homeassistant is using
|
|
|
|
Config = auto()
|
|
|
|
Diagnostic = auto()
|
|
|
|
|
|
|
|
|
2024-02-14 17:59:11 +00:00
|
|
|
class FeatureType(Enum):
|
|
|
|
"""Type to help decide how to present the feature."""
|
2024-02-03 18:42:08 +00:00
|
|
|
|
|
|
|
Sensor = auto()
|
|
|
|
BinarySensor = auto()
|
|
|
|
Switch = auto()
|
|
|
|
Button = auto()
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
2024-02-14 17:59:11 +00:00
|
|
|
class Feature:
|
|
|
|
"""Feature defines a generic interface for device features."""
|
2024-02-03 18:42:08 +00:00
|
|
|
|
2024-02-14 17:59:11 +00:00
|
|
|
#: Device instance required for getting and setting values
|
|
|
|
device: "Device"
|
2024-02-03 18:42:08 +00:00
|
|
|
#: User-friendly short description
|
|
|
|
name: str
|
|
|
|
#: Name of the property that allows accessing the value
|
|
|
|
attribute_getter: str | Callable
|
|
|
|
#: Name of the method that allows changing the value
|
|
|
|
attribute_setter: str | None = None
|
2024-02-14 17:59:11 +00:00
|
|
|
#: Container storing the data, this overrides 'device' for getters
|
|
|
|
container: Any = None
|
|
|
|
#: Icon suggestion
|
2024-02-03 18:42:08 +00:00
|
|
|
icon: str | None = None
|
|
|
|
#: Hint for homeassistant
|
|
|
|
#: TODO: Replace with a set of flags to allow homeassistant make its own decision?
|
|
|
|
show_in_hass: bool = True
|
2024-02-14 17:59:11 +00:00
|
|
|
category: FeatureCategory = FeatureCategory.Diagnostic
|
|
|
|
type: FeatureType = FeatureType.Sensor
|
2024-02-03 18:42:08 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def value(self):
|
|
|
|
"""Return the current value."""
|
2024-02-14 17:59:11 +00:00
|
|
|
container = self.container if self.container is not None else self.device
|
2024-02-03 18:42:08 +00:00
|
|
|
if isinstance(self.attribute_getter, Callable):
|
2024-02-14 17:59:11 +00:00
|
|
|
return self.attribute_getter(container)
|
|
|
|
return getattr(container, self.attribute_getter)
|
2024-02-03 18:42:08 +00:00
|
|
|
|
|
|
|
async def set_value(self, value):
|
|
|
|
"""Set the value."""
|
2024-02-14 17:59:11 +00:00
|
|
|
if self.attribute_setter is None:
|
|
|
|
raise ValueError("Tried to set read-only feature.")
|
2024-02-03 18:42:08 +00:00
|
|
|
return await getattr(self.device, self.attribute_setter)(value)
|