2024-02-19 17:01:31 +00:00
|
|
|
"""Base implementation for SMART modules."""
|
2024-04-16 18:21:20 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
import logging
|
2024-07-11 15:21:59 +00:00
|
|
|
from collections.abc import Awaitable, Callable, Coroutine
|
2024-11-18 18:46:36 +00:00
|
|
|
from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar
|
2024-02-19 17:01:31 +00:00
|
|
|
|
2024-07-04 07:02:50 +00:00
|
|
|
from ..exceptions import DeviceError, KasaException, SmartErrorCode
|
2024-02-19 17:01:31 +00:00
|
|
|
from ..module import Module
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from .smartdevice import SmartDevice
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2024-07-11 15:21:59 +00:00
|
|
|
_T = TypeVar("_T", bound="SmartModule")
|
|
|
|
_P = ParamSpec("_P")
|
2024-07-30 18:23:07 +00:00
|
|
|
_R = TypeVar("_R")
|
2024-07-11 15:21:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
def allow_update_after(
|
2024-11-10 18:55:13 +00:00
|
|
|
func: Callable[Concatenate[_T, _P], Awaitable[dict]],
|
|
|
|
) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, dict]]:
|
2024-07-11 15:21:59 +00:00
|
|
|
"""Define a wrapper to set _last_update_time to None.
|
|
|
|
|
|
|
|
This will ensure that a module is updated in the next update cycle after
|
|
|
|
a value has been changed.
|
|
|
|
"""
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def _async_wrap(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> dict:
|
2024-07-11 15:21:59 +00:00
|
|
|
try:
|
2024-11-10 18:55:13 +00:00
|
|
|
return await func(self, *args, **kwargs)
|
2024-07-11 15:21:59 +00:00
|
|
|
finally:
|
|
|
|
self._last_update_time = None
|
|
|
|
|
|
|
|
return _async_wrap
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
|
2024-07-30 18:23:07 +00:00
|
|
|
def raise_if_update_error(func: Callable[[_T], _R]) -> Callable[[_T], _R]:
|
|
|
|
"""Define a wrapper to raise an error if the last module update was an error."""
|
|
|
|
|
|
|
|
def _wrap(self: _T) -> _R:
|
|
|
|
if err := self._last_update_error:
|
|
|
|
raise err
|
|
|
|
return func(self)
|
|
|
|
|
|
|
|
return _wrap
|
|
|
|
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
class SmartModule(Module):
|
|
|
|
"""Base class for SMART modules."""
|
|
|
|
|
|
|
|
NAME: str
|
2024-05-07 18:58:18 +00:00
|
|
|
#: Module is initialized, if the given component is available
|
|
|
|
REQUIRED_COMPONENT: str | None = None
|
|
|
|
#: Module is initialized, if the given key available in the main sysinfo
|
|
|
|
REQUIRED_KEY_ON_PARENT: str | None = None
|
|
|
|
#: Query to execute during the main update cycle
|
2024-02-19 17:01:31 +00:00
|
|
|
QUERY_GETTER_NAME: str
|
2024-05-07 18:58:18 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
REGISTERED_MODULES: dict[str, type[SmartModule]] = {}
|
2024-02-19 17:01:31 +00:00
|
|
|
|
2024-07-11 15:21:59 +00:00
|
|
|
MINIMUM_UPDATE_INTERVAL_SECS = 0
|
2024-07-30 18:23:07 +00:00
|
|
|
UPDATE_INTERVAL_AFTER_ERROR_SECS = 30
|
|
|
|
|
|
|
|
DISABLE_AFTER_ERROR_COUNT = 10
|
2024-07-11 15:21:59 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def __init__(self, device: SmartDevice, module: str) -> None:
|
2024-02-19 17:01:31 +00:00
|
|
|
self._device: SmartDevice
|
|
|
|
super().__init__(device, module)
|
2024-07-11 15:21:59 +00:00
|
|
|
self._last_update_time: float | None = None
|
2024-07-30 18:23:07 +00:00
|
|
|
self._last_update_error: KasaException | None = None
|
|
|
|
self._error_count = 0
|
2024-02-19 17:01:31 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def __init_subclass__(cls, **kwargs) -> None:
|
2024-10-23 20:42:01 +00:00
|
|
|
# We only want to register submodules in a modules package so that
|
|
|
|
# other classes can inherit from smartmodule and not be registered
|
|
|
|
if cls.__module__.split(".")[-2] == "modules":
|
|
|
|
_LOGGER.debug("Registering %s", cls)
|
2024-10-24 16:22:45 +00:00
|
|
|
cls.REGISTERED_MODULES[cls._module_name()] = cls
|
2024-02-19 17:01:31 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def _set_error(self, err: Exception | None) -> None:
|
2024-07-30 18:23:07 +00:00
|
|
|
if err is None:
|
|
|
|
self._error_count = 0
|
|
|
|
self._last_update_error = None
|
|
|
|
else:
|
|
|
|
self._last_update_error = KasaException("Module update error", err)
|
|
|
|
self._error_count += 1
|
|
|
|
if self._error_count == self.DISABLE_AFTER_ERROR_COUNT:
|
|
|
|
_LOGGER.error(
|
|
|
|
"Error processing %s for device %s, module will be disabled: %s",
|
|
|
|
self.name,
|
|
|
|
self._device.host,
|
|
|
|
err,
|
|
|
|
)
|
|
|
|
if self._error_count > self.DISABLE_AFTER_ERROR_COUNT:
|
|
|
|
_LOGGER.error( # pragma: no cover
|
|
|
|
"Unexpected error processing %s for device %s, "
|
|
|
|
"module should be disabled: %s",
|
|
|
|
self.name,
|
|
|
|
self._device.host,
|
|
|
|
err,
|
|
|
|
)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def update_interval(self) -> int:
|
|
|
|
"""Time to wait between updates."""
|
|
|
|
if self._last_update_error is None:
|
|
|
|
return self.MINIMUM_UPDATE_INTERVAL_SECS
|
|
|
|
|
|
|
|
return self.UPDATE_INTERVAL_AFTER_ERROR_SECS * self._error_count
|
|
|
|
|
|
|
|
@property
|
|
|
|
def disabled(self) -> bool:
|
|
|
|
"""Return true if the module is disabled due to errors."""
|
|
|
|
return self._error_count >= self.DISABLE_AFTER_ERROR_COUNT
|
|
|
|
|
2024-10-24 16:22:45 +00:00
|
|
|
@classmethod
|
2024-11-10 18:55:13 +00:00
|
|
|
def _module_name(cls) -> str:
|
2024-10-24 16:22:45 +00:00
|
|
|
return getattr(cls, "NAME", cls.__name__)
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
@property
|
|
|
|
def name(self) -> str:
|
|
|
|
"""Name of the module."""
|
2024-10-24 16:22:45 +00:00
|
|
|
return self._module_name()
|
2024-02-19 17:01:31 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def _post_update_hook(self) -> None: # noqa: B027
|
2024-07-04 07:02:50 +00:00
|
|
|
"""Perform actions after a device update.
|
|
|
|
|
|
|
|
Any modules overriding this should ensure that self.data is
|
|
|
|
accessed unless the module should remain active despite errors.
|
|
|
|
"""
|
|
|
|
assert self.data # noqa: S101
|
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
def query(self) -> dict:
|
2024-02-19 17:01:31 +00:00
|
|
|
"""Query to execute during the update cycle.
|
|
|
|
|
|
|
|
Default implementation uses the raw query getter w/o parameters.
|
|
|
|
"""
|
|
|
|
return {self.QUERY_GETTER_NAME: None}
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def call(self, method: str, params: dict | None = None) -> dict:
|
2024-02-19 17:01:31 +00:00
|
|
|
"""Call a method.
|
|
|
|
|
|
|
|
Just a helper method.
|
|
|
|
"""
|
2024-10-02 15:00:27 +00:00
|
|
|
return await self._device._query_helper(method, params)
|
2024-02-19 17:01:31 +00:00
|
|
|
|
|
|
|
@property
|
2024-11-10 18:55:13 +00:00
|
|
|
def data(self) -> dict[str, Any]:
|
2024-02-19 17:01:31 +00:00
|
|
|
"""Return response data for the module.
|
|
|
|
|
2024-03-05 14:41:40 +00:00
|
|
|
If the module performs only a single query, the resulting response is unwrapped.
|
|
|
|
If the module does not define a query, this property returns a reference
|
|
|
|
to the main "get_device_info" response.
|
2024-02-19 17:01:31 +00:00
|
|
|
"""
|
2024-03-05 14:41:40 +00:00
|
|
|
dev = self._device
|
2024-02-19 17:01:31 +00:00
|
|
|
q = self.query()
|
2024-03-05 14:41:40 +00:00
|
|
|
|
|
|
|
if not q:
|
2024-04-17 10:07:16 +00:00
|
|
|
return dev.sys_info
|
2024-03-05 14:41:40 +00:00
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
q_keys = list(q.keys())
|
2024-02-22 19:46:19 +00:00
|
|
|
query_key = q_keys[0]
|
|
|
|
|
2024-02-19 17:01:31 +00:00
|
|
|
# TODO: hacky way to check if update has been called.
|
2024-02-22 19:46:19 +00:00
|
|
|
# The way this falls back to parent may not always be wanted.
|
|
|
|
# Especially, devices can have their own firmware updates.
|
|
|
|
if query_key not in dev._last_update:
|
|
|
|
if dev._parent and query_key in dev._parent._last_update:
|
|
|
|
_LOGGER.debug("%s not found child, but found on parent", query_key)
|
|
|
|
dev = dev._parent
|
|
|
|
else:
|
|
|
|
raise KasaException(
|
|
|
|
f"You need to call update() prior accessing module data"
|
|
|
|
f" for '{self._module}'"
|
|
|
|
)
|
|
|
|
|
|
|
|
filtered_data = {k: v for k, v in dev._last_update.items() if k in q_keys}
|
|
|
|
|
2024-07-04 07:02:50 +00:00
|
|
|
for data_item in filtered_data:
|
|
|
|
if isinstance(filtered_data[data_item], SmartErrorCode):
|
|
|
|
raise DeviceError(
|
|
|
|
f"{data_item} for {self.name}", error_code=filtered_data[data_item]
|
|
|
|
)
|
2024-02-19 17:01:31 +00:00
|
|
|
if len(filtered_data) == 1:
|
|
|
|
return next(iter(filtered_data.values()))
|
|
|
|
|
|
|
|
return filtered_data
|
2024-02-24 01:16:43 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def supported_version(self) -> int:
|
2024-05-07 18:58:18 +00:00
|
|
|
"""Return version supported by the device.
|
|
|
|
|
|
|
|
If the module has no required component, this will return -1.
|
|
|
|
"""
|
|
|
|
if self.REQUIRED_COMPONENT is not None:
|
|
|
|
return self._device._components[self.REQUIRED_COMPONENT]
|
|
|
|
return -1
|
2024-04-20 15:18:35 +00:00
|
|
|
|
|
|
|
async def _check_supported(self) -> bool:
|
|
|
|
"""Additional check to see if the module is supported by the device.
|
|
|
|
|
|
|
|
Used for parents who report components on the parent that are only available
|
|
|
|
on the child or for modules where the device has a pointless component like
|
|
|
|
color_temp_range but only supports one value.
|
|
|
|
"""
|
|
|
|
return True
|
2024-07-04 07:02:50 +00:00
|
|
|
|
|
|
|
def _has_data_error(self) -> bool:
|
|
|
|
try:
|
|
|
|
assert self.data # noqa: S101
|
|
|
|
return False
|
|
|
|
except DeviceError:
|
|
|
|
return True
|