8000 Deprecate legacy light module is_capability checks by sdb9696 · Pull Request #1297 · python-kasa/python-kasa · GitHub
[go: up one dir, main page]

Skip to content

Deprecate legacy light module is_capability checks #1297

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 42 additions & 6 deletions kasa/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@

import logging
from abc import ABC, abstractmethod
from collections.abc import Mapping, Sequence
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, tzinfo
from typing import TYPE_CHECKING, Any, TypeAlias
Expand Down Expand Up @@ -537,19 +537,52 @@ def _get_replacing_attr(

return None

def _get_deprecated_callable_attribute(self, name: str) -> Any | None:
vals: dict[str, tuple[ModuleName, Callable[[Any], Any], str]] = {
"is_dimmable": (
Module.Light,
lambda c: c.has_feature("brightness"),
'light_module.has_feature("brightness")',
),
"is_color": (
Module.Light,
lambda c: c.has_feature("hsv"),
'light_module.has_feature("hsv")',
),
"is_variable_color_temp": (
Module.Light,
lambda c: c.has_feature("color_temp"),
'light_module.has_feature("color_temp")',
),
"valid_temperature_range": (
Module.Light,
lambda c: c._deprecated_valid_temperature_range(),
'minimum and maximum value of get_feature("color_temp")',
),
"has_effects": (
Module.Light,
lambda c: Module.LightEffect in c._device.modules,
"Module.LightEffect in device.modules",
),
}
if mod_call_msg := vals.get(name):
mod, call, msg = mod_call_msg
msg = f"{name} is deprecated, use: {msg} instead"
warn(msg, DeprecationWarning, stacklevel=2)
if (module := self.modules.get(mod)) is None:
raise AttributeError(f"Device has no attribute {name!r}")
return call(module)

return None

_deprecated_other_attributes = {
# light attributes
"is_color": (Module.Light, ["is_color"]),
"is_dimmable": (Module.Light, ["is_dimmable"]),
"is_variable_color_temp": (Module.Light, ["is_variable_color_temp"]),
"brightness": (Module.Light, ["brightness"]),
"set_brightness": (Module.Light, ["set_brightness"]),
"hsv": (Module.Light, ["hsv"]),
"set_hsv": (Module.Light, ["set_hsv"]),
"color_temp": (Module.Light, ["color_temp"]),
"set_color_temp": (Module.Light, ["set_color_temp"]),
"valid_temperature_range": (Module.Light, ["valid_temperature_range"]),
"has_effects": (Module.Light, ["has_effects"]),
"_deprecated_set_light_state": (Module.Light, ["has_effects"]),
# led attributes
"led": (Module.Led, ["led"]),
Expand Down Expand Up @@ -588,6 +621,9 @@ def __getattr__(self, name: str) -> Any:
msg = f"{name} is deprecated, use device_type property instead"
warn(msg, DeprecationWarning, stacklevel=2)
return self.device_type == dep_device_type_attr[1]
# callable
if (result := self._get_deprecated_callable_attribute(name)) is not None:
return result
# Other deprecated attributes
if (dep_attr := self._deprecated_other_attributes.get(name)) and (
(replacing_attr := self._get_replacing_attr(dep_attr[0], *dep_attr[1]))
Expand Down
72 changes: 43 additions & 29 deletions kasa/interfaces/light.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,12 @@
from __future__ import annotations

from abc import ABC, abstractmethod
from collections.abc import Callable
from dataclasses import dataclass
from typing import Annotated, NamedTuple
from typing import Annotated, Any, NamedTuple
from warnings import warn

from ..exceptions import KasaException
from ..module import FeatureAttribute, Module


Expand Down Expand Up @@ -100,34 +103,6 @@
class Light(Module, ABC):
"""Base class for TP-Link Light."""

@property
@abstractmethod
def is_dimmable(self) -> bool:
"""Whether the light supports brightness changes."""

@property
@abstractmethod
def is_color(self) -> bool:
"""Whether the bulb supports color changes."""

@property
@abstractmethod
def is_variable_color_temp(self) -> bool:
"""Whether the bulb supports color temperature changes."""

@property
@abstractmethod
def valid_temperature_range(self) -> ColorTempRange:
"""Return the device-specific white temperature range (in Kelvin).

:return: White temperature range in Kelvin (minimum, maximum)
"""

@property
@abstractmethod
def has_effects(self) -> bool:
"""Return True if the device supports effects."""

@property
@abstractmethod
def hsv(self) -> Annotated[HSV, FeatureAttribute()]:
Expand Down Expand Up @@ -197,3 +172,42 @@
@abstractmethod
async def set_state(self, state: LightState) -> dict:
"""Set the light state."""

def _deprecated_valid_temperature_range(self) -> ColorTempRange:
if not (temp := self.get_feature("color_temp")):
raise KasaException("Color temperature not supported")
return ColorTempRange(temp.minimum_value, temp.maximum_value)

def _deprecated_attributes(self, dep_name: str) -> Callable | None:
map: dict[str, Callable] = {
"is_color": self.set_hsv,
"is_dimmable": self.set_brightness,
"is_variable_color_temp": self.set_color_temp,
}
return map.get(dep_name)

def __getattr__(self, name: str) -> Any:
if name == "valid_temperature_range":
res = self._deprecated_valid_temperature_range()
msg = (

Check warning on line 192 in kasa/interfaces/light.py

View check run for this annotation

Codecov / codecov/patch

kasa/interfaces/light.py#L191-L192

Added lines #L191 - L192 were not covered by tests
"valid_temperature_range is deprecated, use "
'get_feature("color_temp") minimum_value '
" and maximum_value instead"
)
warn(msg, DeprecationWarning, stacklevel=2)
return res

Check warning on line 198 in kasa/interfaces/light.py

View check run for this annotation

Codecov / codecov/patch

kasa/interfaces/light.py#L197-L198

Added lines #L197 - L198 were not covered by tests

if name == "has_effects":
msg = (

Check warning on line 201 in kasa/interfaces/light.py

View check run for this annotation

Codecov / codecov/patch

kasa/interfaces/light.py#L201

Added line #L201 was not covered by tests
"has_effects is deprecated, check `Module.LightEffect "
"in device.modules` instead"
)
warn(msg, DeprecationWarning, stacklevel=2)
return Module.LightEffect in self._device.modules

Check warning on line 206 in kasa/interfaces/light.py

View check run for this annotation

Codecov / codecov/patch

kasa/interfaces/light.py#L205-L206

Added lines #L205 - L206 were not covered by tests

if attr := self._deprecated_attributes(name):
msg = f"{name} is deprecated, use has_feature({attr}) instead"
warn(msg, DeprecationWarning, stacklevel=2)
return self.has_feature(attr)

Check warning on line 211 in kasa/interfaces/light.py

View check run for this annotation

Codecov / codecov/patch

kasa/interfaces/light.py#L209-L211

Added lines #L209 - L211 were not covered by tests

raise AttributeError(f"Energy module has no attribute {name!r}")
44 changes: 4 additions & 40 deletions kasa/iot/modules/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from ...device_type import DeviceType
from ...exceptions import KasaException
from ...feature import Feature
from ...interfaces.light import HSV, ColorTempRange, LightState
from ...interfaces.light import HSV, LightState
from ...interfaces.light import Light as LightInterface
from ...module import FeatureAttribute
from ..iotmodule import IotModule
Expand Down Expand Up @@ -48,6 +48,8 @@ def _initialize_features(self) -> None:
)
)
if device._is_variable_color_temp:
if TYPE_CHECKING:
assert isinstance(device, IotBulb)
self._add_feature(
Feature(
device=device,
Expand All @@ -56,7 +58,7 @@ def _initialize_features(self) -> None:
container=self,
attribute_getter="color_temp",
attribute_setter="set_color_temp",
range_getter="valid_temperature_range",
range_getter=lambda: device._valid_temperature_range,
category=Feature.Category.Primary,
type=Feature.Type.Number,
)
Expand Down Expand Up @@ -90,11 +92,6 @@ def _get_bulb_device(self) -> IotBulb | None:
return cast("IotBulb", self._device)
return None

@property # type: ignore
def is_dimmable(self) -> int:
"""Whether the bulb supports brightness changes."""
return self._device._is_dimmable

@property # type: ignore
def brightness(self) -> Annotated[int, FeatureAttribute()]:
"""Return the current brightness in percentage."""
Expand All @@ -112,27 +109,6 @@ async def set_brightness(
LightState(brightness=brightness, transition=transition)
)

@property
def is_color(self) -> bool:
"""Whether the light supports color changes."""
if (bulb := self._get_bulb_device()) is None:
return False
return bulb._is_color

@property
def is_variable_color_temp(self) -> bool:
"""Whether the bulb supports color temperature changes."""
if (bulb := self._get_bulb_device()) is None:
return False
return bulb._is_variable_color_temp

@property
def has_effects(self) -> bool:
"""Return True if the device supports effects."""
if (bulb := self._get_bulb_device()) is None:
return False
return bulb._has_effects

@property
def hsv(self) -> Annotated[HSV, FeatureAttribute()]:
"""Return the current HSV state of the bulb.
Expand Down Expand Up @@ -164,18 +140,6 @@ async def set_hsv(
raise KasaException("Light does not support color.")
return await bulb._set_hsv(hue, saturation, value, transition=transition)

@property
def valid_temperature_range(self) -> ColorTempRange:
"""Return the device-specific white temperature range (in Kelvin).

:return: White temperature range in Kelvin (minimum, maximum)
"""
if (
bulb := self._get_bulb_device()
) is None or not bulb._is_variable_color_temp:
raise KasaException("Light does not support colortemp.")
return bulb._valid_temperature_range

@property
def color_temp(self) -> Annotated[int, FeatureAttribute()]:
"""Whether the bulb supports color temperature changes."""
Expand Down
37 changes: 3 additions & 34 deletions kasa/smart/modules/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from ...exceptions import KasaException
from ...feature import Feature
from ...interfaces.light import HSV, ColorTempRange, LightState
from ...interfaces.light import HSV, LightState
from ...interfaces.light import Light as LightInterface
from ...module import FeatureAttribute, Module
from ..smartmodule import SmartModule
Expand All @@ -34,32 +34,6 @@ def query(self) -> dict:
"""Query to execute during the update cycle."""
return {}

@property
def is_color(self) -> bool:
"""Whether the bulb supports color changes."""
return Module.Color in self._device.modules

@property
def is_dimmable(self) -> bool:
"""Whether the bulb supports brightness changes."""
return Module.Brightness in self._device.modules

@property
def is_variable_color_temp(self) -> bool:
"""Whether the bulb supports color temperature changes."""
return Module.ColorTemperature in self._device.modules

@property
def valid_temperature_range(self) -> ColorTempRange:
"""Return the device-specific white temperature range (in Kelvin).

:return: White temperature range in Kelvin (minimum, maximum)
"""
if Module.ColorTemperature not in self._device.modules:
raise KasaException("Color temperature not supported")

return self._device.modules[Module.ColorTemperature].valid_temperature_range

@property
def hsv(self) -> Annotated[HSV, FeatureAttribute()]:
"""Return the current HSV state of the bulb.
Expand All @@ -82,7 +56,7 @@ def color_temp(self) -> Annotated[int, FeatureAttribute()]:
@property
def brightness(self) -> Annotated[int, FeatureAttribute()]:
"""Return the current brightness in percentage."""
if Module.Brightness not in self._device.modules:
if Module.Brightness not in self._device.modules: # pragma: no cover
raise KasaException("Bulb is not dimmable.")

return self._device.modules[Module.Brightness].brightness
Expand Down Expand Up @@ -135,16 +109,11 @@ async def set_brightness(
:param int brightness: brightness in percent
:param int transition: transition in milliseconds.
"""
if Module.Brightness not in self._device.modules:
if Module.Brightness not in self._device.modules: # pragma: no cover
raise KasaException("Bulb is not dimmable.")

return await self._device.modules[Module.Brightness].set_brightness(brightness)

@property
def has_effects(self) -> bool:
"""Return True if the device supports effects."""
return Module.LightEffect in self._device.modules

async def set_state(self, state: LightState) -> dict:
"""Set the light state."""
state_dict = asdict(state)
Expand Down
Loading
0