2024-06-19 08:53:40 +00:00
|
|
|
"""Interact with feature.
|
|
|
|
|
|
|
|
Features are implemented by devices to represent individual pieces of functionality like
|
|
|
|
state, time, firmware.
|
|
|
|
|
|
|
|
>>> from kasa import Discover, Module
|
|
|
|
>>>
|
|
|
|
>>> dev = await Discover.discover_single(
|
|
|
|
>>> "127.0.0.3",
|
|
|
|
>>> username="user@example.com",
|
|
|
|
>>> password="great_password"
|
|
|
|
>>> )
|
|
|
|
>>> await dev.update()
|
|
|
|
>>> print(dev.alias)
|
|
|
|
Living Room Bulb
|
|
|
|
|
|
|
|
Features allow for instrospection and can be interacted with as new features are added
|
|
|
|
to the API:
|
|
|
|
|
|
|
|
>>> for feature_id, feature in dev.features.items():
|
|
|
|
>>> print(f"{feature.name} ({feature_id}): {feature.value}")
|
|
|
|
Device ID (device_id): 0000000000000000000000000000000000000000
|
|
|
|
State (state): True
|
|
|
|
Signal Level (signal_level): 2
|
|
|
|
RSSI (rssi): -52
|
|
|
|
SSID (ssid): #MASKED_SSID#
|
|
|
|
Overheated (overheated): False
|
2024-07-24 13:47:38 +00:00
|
|
|
Reboot (reboot): <Action>
|
2024-06-19 08:53:40 +00:00
|
|
|
Brightness (brightness): 100
|
|
|
|
Cloud connection (cloud_connection): True
|
|
|
|
HSV (hsv): HSV(hue=0, saturation=100, value=100)
|
|
|
|
Color temperature (color_temperature): 2700
|
|
|
|
Auto update enabled (auto_update_enabled): False
|
2024-08-30 17:01:54 +00:00
|
|
|
Update available (update_available): None
|
2024-06-19 08:53:40 +00:00
|
|
|
Current firmware version (current_firmware_version): 1.1.6 Build 240130 Rel.173828
|
2024-08-30 17:01:54 +00:00
|
|
|
Available firmware version (available_firmware_version): None
|
|
|
|
Check latest firmware (check_latest_firmware): <Action>
|
2024-06-19 08:53:40 +00:00
|
|
|
Light effect (light_effect): Off
|
|
|
|
Light preset (light_preset): Not set
|
|
|
|
Smooth transition on (smooth_transition_on): 2
|
|
|
|
Smooth transition off (smooth_transition_off): 2
|
2024-06-21 16:42:43 +00:00
|
|
|
Device time (device_time): 2024-02-23 02:40:15+01:00
|
2024-06-19 08:53:40 +00:00
|
|
|
|
|
|
|
To see whether a device supports a feature, check for the existence of it:
|
|
|
|
|
|
|
|
>>> if feature := dev.features.get("brightness"):
|
|
|
|
>>> print(feature.value)
|
|
|
|
100
|
|
|
|
|
|
|
|
You can update the value of a feature
|
|
|
|
|
|
|
|
>>> await feature.set_value(50)
|
|
|
|
>>> await dev.update()
|
|
|
|
>>> print(feature.value)
|
|
|
|
50
|
|
|
|
|
|
|
|
Features have types that can be used for introspection:
|
|
|
|
|
|
|
|
>>> feature = dev.features["light_preset"]
|
|
|
|
>>> print(feature.type)
|
|
|
|
Type.Choice
|
|
|
|
|
|
|
|
>>> print(feature.choices)
|
|
|
|
['Not set', 'Light preset 1', 'Light preset 2', 'Light preset 3',\
|
|
|
|
'Light preset 4', 'Light preset 5', 'Light preset 6', 'Light preset 7']
|
|
|
|
"""
|
2024-04-16 18:21:20 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-04-24 16:38:52 +00:00
|
|
|
import logging
|
2024-11-18 18:46:36 +00:00
|
|
|
from collections.abc import Callable, Coroutine
|
2024-02-15 15:25:08 +00:00
|
|
|
from dataclasses import dataclass
|
|
|
|
from enum import Enum, auto
|
2024-07-30 18:23:07 +00:00
|
|
|
from functools import cached_property
|
2024-11-18 18:46:36 +00:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2024-02-15 15:25:08 +00:00
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from .device import Device
|
|
|
|
|
2024-04-24 16:38:52 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2024-02-15 15:25:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Feature:
|
|
|
|
"""Feature defines a generic interface for device features."""
|
|
|
|
|
2024-04-24 16:38:52 +00:00
|
|
|
class Type(Enum):
|
|
|
|
"""Type to help decide how to present the feature."""
|
|
|
|
|
|
|
|
#: Sensor is an informative read-only value
|
|
|
|
Sensor = auto()
|
|
|
|
#: BinarySensor is a read-only boolean
|
|
|
|
BinarySensor = auto()
|
|
|
|
#: Switch is a boolean setting
|
|
|
|
Switch = auto()
|
|
|
|
#: Action triggers some action on device
|
|
|
|
Action = auto()
|
|
|
|
#: Number defines a numeric setting
|
2024-06-03 09:14:10 +00:00
|
|
|
#: See :attr:`range_getter`, :attr:`Feature.minimum_value`,
|
|
|
|
#: and :attr:`maximum_value`
|
2024-04-24 16:38:52 +00:00
|
|
|
Number = auto()
|
|
|
|
#: Choice defines a setting with pre-defined values
|
|
|
|
Choice = auto()
|
|
|
|
Unknown = -1
|
|
|
|
|
2024-06-21 12:51:56 +00:00
|
|
|
# Aliases for easy access
|
2024-04-24 16:38:52 +00:00
|
|
|
Sensor = Type.Sensor
|
|
|
|
BinarySensor = Type.BinarySensor
|
|
|
|
Switch = Type.Switch
|
|
|
|
Action = Type.Action
|
|
|
|
Number = Type.Number
|
|
|
|
Choice = Type.Choice
|
|
|
|
|
2024-06-27 17:52:54 +00:00
|
|
|
DEFAULT_MAX = 2**16 # Arbitrary max
|
|
|
|
|
2024-04-23 17:20:12 +00:00
|
|
|
class Category(Enum):
|
2024-04-24 16:38:52 +00:00
|
|
|
"""Category hint to allow feature grouping."""
|
2024-04-23 17:20:12 +00:00
|
|
|
|
|
|
|
#: Primary features control the device state directly.
|
2024-04-24 16:38:52 +00:00
|
|
|
#: Examples include turning the device on/off, or adjusting its brightness.
|
2024-04-23 17:20:12 +00:00
|
|
|
Primary = auto()
|
|
|
|
#: Config features change device behavior without immediate state changes.
|
|
|
|
Config = auto()
|
|
|
|
#: Informative/sensor features deliver some potentially interesting information.
|
|
|
|
Info = auto()
|
|
|
|
#: Debug features deliver more verbose information then informative features.
|
|
|
|
#: You may want to hide these per default to avoid cluttering your UI.
|
|
|
|
Debug = auto()
|
|
|
|
#: The default category if none is specified.
|
|
|
|
Unset = -1
|
|
|
|
|
2024-02-15 15:25:08 +00:00
|
|
|
#: Device instance required for getting and setting values
|
2024-04-17 13:39:24 +00:00
|
|
|
device: Device
|
2024-05-07 09:13:35 +00:00
|
|
|
#: Identifier
|
|
|
|
id: str
|
2024-02-15 15:25:08 +00:00
|
|
|
#: User-friendly short description
|
|
|
|
name: str
|
2024-06-25 16:30:36 +00:00
|
|
|
#: Type of the feature
|
|
|
|
type: Feature.Type
|
2024-11-18 14:53:49 +00:00
|
|
|
#: Callable or name of the property that allows accessing the value
|
2024-04-23 17:49:04 +00:00
|
|
|
attribute_getter: str | Callable | None = None
|
2024-11-18 14:53:49 +00:00
|
|
|
#: Callable coroutine or name of the method that allows changing the value
|
|
|
|
attribute_setter: str | Callable[..., Coroutine[Any, Any, Any]] | None = None
|
2024-02-15 15:25:08 +00:00
|
|
|
#: Container storing the data, this overrides 'device' for getters
|
|
|
|
container: Any = None
|
|
|
|
#: Icon suggestion
|
2024-04-17 13:39:24 +00:00
|
|
|
icon: str | None = None
|
2024-06-21 12:51:56 +00:00
|
|
|
#: Attribute containing the name of the unit getter property.
|
2024-07-30 18:23:07 +00:00
|
|
|
#: If set, this property will be used to get the *unit*.
|
|
|
|
unit_getter: str | Callable[[], str] | None = None
|
2024-04-23 17:20:12 +00:00
|
|
|
#: Category hint for downstreams
|
|
|
|
category: Feature.Category = Category.Unset
|
2024-02-15 15:25:08 +00:00
|
|
|
|
2024-04-29 11:31:42 +00:00
|
|
|
# Display hints offer a way suggest how the value should be shown to users
|
|
|
|
#: Hint to help rounding the sensor values to given after-comma digits
|
|
|
|
precision_hint: int | None = None
|
|
|
|
|
2024-03-15 16:36:07 +00:00
|
|
|
#: Attribute containing the name of the range getter property.
|
|
|
|
#: If set, this property will be used to set *minimum_value* and *maximum_value*.
|
2024-07-30 18:23:07 +00:00
|
|
|
range_getter: str | Callable[[], tuple[int, int]] | None = None
|
2024-03-15 16:36:07 +00:00
|
|
|
|
2024-04-30 06:56:09 +00:00
|
|
|
#: Attribute name of the choices getter property.
|
2024-07-30 18:23:07 +00:00
|
|
|
#: If set, this property will be used to get *choices*.
|
|
|
|
choices_getter: str | Callable[[], list[str]] | None = None
|
2024-04-30 06:56:09 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def __post_init__(self) -> None:
|
2024-03-15 16:36:07 +00:00
|
|
|
"""Handle late-binding of members."""
|
2024-04-23 17:20:12 +00:00
|
|
|
# Populate minimum & maximum values, if range_getter is given
|
2024-07-30 18:23:07 +00:00
|
|
|
self._container = self.container if self.container is not None else self.device
|
2024-06-21 12:51:56 +00:00
|
|
|
|
2024-04-23 17:20:12 +00:00
|
|
|
# Set the category, if unset
|
|
|
|
if self.category is Feature.Category.Unset:
|
|
|
|
if self.attribute_setter:
|
|
|
|
self.category = Feature.Category.Config
|
|
|
|
else:
|
|
|
|
self.category = Feature.Category.Info
|
|
|
|
|
2024-06-25 16:30:36 +00:00
|
|
|
if self.type in (
|
2024-04-24 16:38:52 +00:00
|
|
|
Feature.Type.Sensor,
|
|
|
|
Feature.Type.BinarySensor,
|
2024-06-25 16:30:36 +00:00
|
|
|
):
|
|
|
|
if self.category == Feature.Category.Config:
|
|
|
|
raise ValueError(
|
|
|
|
f"Invalid type for configurable feature: {self.name} ({self.id}):"
|
|
|
|
f" {self.type}"
|
|
|
|
)
|
|
|
|
elif self.attribute_setter is not None:
|
|
|
|
raise ValueError(
|
|
|
|
f"Read-only feat defines attribute_setter: {self.name} ({self.id}):"
|
|
|
|
)
|
2024-04-24 16:38:52 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def _get_property_value(self, getter: str | Callable | None) -> Any:
|
2024-07-30 18:23:07 +00:00
|
|
|
if getter is None:
|
|
|
|
return None
|
|
|
|
if isinstance(getter, str):
|
|
|
|
return getattr(self._container, getter)
|
|
|
|
if callable(getter):
|
|
|
|
return getter()
|
|
|
|
raise ValueError("Invalid getter: %s", getter) # pragma: no cover
|
|
|
|
|
|
|
|
@property
|
|
|
|
def choices(self) -> list[str] | None:
|
|
|
|
"""List of choices."""
|
|
|
|
return self._get_property_value(self.choices_getter)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def unit(self) -> str | None:
|
|
|
|
"""Unit if applicable."""
|
|
|
|
return self._get_property_value(self.unit_getter)
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def range(self) -> tuple[int, int] | None:
|
|
|
|
"""Range of values if applicable."""
|
|
|
|
return self._get_property_value(self.range_getter)
|
|
|
|
|
2024-07-31 14:52:27 +00:00
|
|
|
@property
|
2024-07-30 18:23:07 +00:00
|
|
|
def maximum_value(self) -> int:
|
|
|
|
"""Maximum value."""
|
|
|
|
if range := self.range:
|
|
|
|
return range[1]
|
|
|
|
return self.DEFAULT_MAX
|
|
|
|
|
2024-07-31 14:52:27 +00:00
|
|
|
@property
|
2024-07-30 18:23:07 +00:00
|
|
|
def minimum_value(self) -> int:
|
|
|
|
"""Minimum value."""
|
|
|
|
if range := self.range:
|
|
|
|
return range[0]
|
|
|
|
return 0
|
|
|
|
|
2024-02-15 15:25:08 +00:00
|
|
|
@property
|
2024-11-10 18:55:13 +00:00
|
|
|
def value(self) -> int | float | bool | str | Enum | None:
|
2024-02-15 15:25:08 +00:00
|
|
|
"""Return the current value."""
|
2024-04-24 16:38:52 +00:00
|
|
|
if self.type == Feature.Type.Action:
|
2024-04-23 17:49:04 +00:00
|
|
|
return "<Action>"
|
|
|
|
if self.attribute_getter is None:
|
|
|
|
raise ValueError("Not an action and no attribute_getter set")
|
|
|
|
|
2024-02-15 15:25:08 +00:00
|
|
|
container = self.container if self.container is not None else self.device
|
2024-06-12 19:58:21 +00:00
|
|
|
if callable(self.attribute_getter):
|
2024-02-15 15:25:08 +00:00
|
|
|
return self.attribute_getter(container)
|
|
|
|
return getattr(container, self.attribute_getter)
|
|
|
|
|
2024-06-12 19:58:21 +00:00
|
|
|
async def set_value(self, value: int | float | bool | str | Enum | None) -> Any:
|
2024-02-15 15:25:08 +00:00
|
|
|
"""Set the value."""
|
|
|
|
if self.attribute_setter is None:
|
|
|
|
raise ValueError("Tried to set read-only feature.")
|
2024-04-24 16:38:52 +00:00
|
|
|
if self.type == Feature.Type.Number: # noqa: SIM102
|
2024-11-18 18:46:36 +00:00
|
|
|
if not isinstance(value, int | float):
|
2024-06-12 19:58:21 +00:00
|
|
|
raise ValueError("value must be a number")
|
2024-02-24 01:16:43 +00:00
|
|
|
if value < self.minimum_value or value > self.maximum_value:
|
|
|
|
raise ValueError(
|
|
|
|
f"Value {value} out of range "
|
|
|
|
f"[{self.minimum_value}, {self.maximum_value}]"
|
|
|
|
)
|
2024-04-30 06:56:09 +00:00
|
|
|
elif self.type == Feature.Type.Choice: # noqa: SIM102
|
2024-06-12 19:58:21 +00:00
|
|
|
if not self.choices or value not in self.choices:
|
2024-04-30 06:56:09 +00:00
|
|
|
raise ValueError(
|
|
|
|
f"Unexpected value for {self.name}: {value}"
|
|
|
|
f" - allowed: {self.choices}"
|
|
|
|
)
|
2024-02-24 01:16:43 +00:00
|
|
|
|
2024-11-18 14:53:49 +00:00
|
|
|
if callable(self.attribute_setter):
|
|
|
|
attribute_setter = self.attribute_setter
|
|
|
|
else:
|
|
|
|
container = self.container if self.container is not None else self.device
|
|
|
|
attribute_setter = getattr(container, self.attribute_setter)
|
|
|
|
|
2024-04-24 16:38:52 +00:00
|
|
|
if self.type == Feature.Type.Action:
|
2024-11-18 14:53:49 +00:00
|
|
|
return await attribute_setter()
|
2024-04-23 17:49:04 +00:00
|
|
|
|
2024-11-18 14:53:49 +00:00
|
|
|
return await attribute_setter(value)
|
2024-04-23 17:20:12 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def __repr__(self) -> str:
|
2024-05-02 13:32:06 +00:00
|
|
|
try:
|
|
|
|
value = self.value
|
2024-05-02 14:31:12 +00:00
|
|
|
choices = self.choices
|
2024-05-02 13:32:06 +00:00
|
|
|
except Exception as ex:
|
|
|
|
return f"Unable to read value ({self.id}): {ex}"
|
|
|
|
|
2024-05-02 14:31:12 +00:00
|
|
|
if self.type == Feature.Type.Choice:
|
|
|
|
if not isinstance(choices, list) or value not in choices:
|
2024-05-07 08:38:09 +00:00
|
|
|
_LOGGER.warning(
|
|
|
|
"Invalid value for for choice %s (%s): %s not in %s",
|
|
|
|
self.name,
|
|
|
|
self.id,
|
|
|
|
value,
|
|
|
|
choices,
|
|
|
|
)
|
|
|
|
return (
|
|
|
|
f"{self.name} ({self.id}): invalid value '{value}' not in {choices}"
|
|
|
|
)
|
2024-05-02 14:31:12 +00:00
|
|
|
value = " ".join(
|
|
|
|
[f"*{choice}*" if choice == value else choice for choice in choices]
|
|
|
|
)
|
2024-11-10 18:55:13 +00:00
|
|
|
if self.precision_hint is not None and isinstance(value, float):
|
|
|
|
value = round(value, self.precision_hint)
|
2024-05-02 13:32:06 +00:00
|
|
|
|
2024-04-29 11:31:42 +00:00
|
|
|
s = f"{self.name} ({self.id}): {value}"
|
2024-04-23 17:20:12 +00:00
|
|
|
if self.unit is not None:
|
|
|
|
s += f" {self.unit}"
|
|
|
|
|
2024-04-24 16:38:52 +00:00
|
|
|
if self.type == Feature.Type.Number:
|
2024-04-23 17:20:12 +00:00
|
|
|
s += f" (range: {self.minimum_value}-{self.maximum_value})"
|
|
|
|
|
|
|
|
return s
|