Implement action feature (#849)

Adds `FeatureType.Action` making it possible to expose features like
"reboot", "test alarm", "pair" etc.

The `attribute_getter` is no longer mandatory, but it will raise an
exception if not defined for other types than actions.
Trying to read returns a static string `<Action>`.
This overloads the `set_value` to call the given callable on any value.

This also fixes the `play` and `stop` coroutines of the alarm module to
await the call.
This commit is contained in:
Teemu R
2024-04-23 19:49:04 +02:00
committed by GitHub
parent b860c32d5f
commit 6e5cae1f47
3 changed files with 50 additions and 6 deletions

View File

@@ -17,7 +17,7 @@ class FeatureType(Enum):
Sensor = auto()
BinarySensor = auto()
Switch = auto()
Button = auto()
Action = auto()
Number = auto()
@@ -46,7 +46,7 @@ class Feature:
#: User-friendly short description
name: str
#: Name of the property that allows accessing the value
attribute_getter: str | Callable
attribute_getter: str | Callable | None = None
#: Name of the method that allows changing the value
attribute_setter: str | None = None
#: Container storing the data, this overrides 'device' for getters
@@ -95,6 +95,11 @@ class Feature:
@property
def value(self):
"""Return the current value."""
if self.type == FeatureType.Action:
return "<Action>"
if self.attribute_getter is None:
raise ValueError("Not an action and no attribute_getter set")
container = self.container if self.container is not None else self.device
if isinstance(self.attribute_getter, Callable):
return self.attribute_getter(container)
@@ -112,6 +117,9 @@ class Feature:
)
container = self.container if self.container is not None else self.device
if self.type == FeatureType.Action:
return await getattr(container, self.attribute_setter)()
return await getattr(container, self.attribute_setter)(value)
def __repr__(self):