mirror of
https://github.com/python-kasa/python-kasa.git
synced 2026-10-08 05:43:53 +00:00
## [0.11.0](https://github.com/python-kasa/python-kasa/tree/0.11.0) (2026-10-04) [Full Changelog](https://github.com/python-kasa/python-kasa/compare/0.10.2...0.11.0) **Release summary:** This is a huge and long overdue release, coming more than a year and a half after the previous one. Hopefully the next one follows sooner, as the TPAP transport (which did not make it into this release) is used more and more on newer devices. This release brings broader camera support, new modules for lights, vacuums and cameras, and many connectivity fixes for newer firmware versions. Some other highlights: - Improved Tapo camera support: login version 3, presets, wifi handling, last alert detection, and more robust authentication and discovery. - Selective room cleaning for robot vacuums. - Configurable light strip length via the new strip segment module, and an exposed light transition state change flag. - Basic HomeKit module for Kasa (iot) devices. - Energy monitoring V2 support (S515D). - Better hub and thermostat state reporting (hold, summer mode, low battery). - Connection fixes for newer Tapo firmware and older SSL devices, plus KLAP v2 for iot devices. - More resilient time handling, with failover and UTC fallback for iot devices. - Python 3.14 is now supported. - Inclusion of fixtures for 29 devices or firmware versions, including the Tapo C460, C200 and C101 cameras and the KH100 hub with KE100/KE110 thermostats. **Thank you to all contributors!** A big thank you to everyone who contributed to this release, whether through code, device fixtures, bug reports or testing. Special thanks to @ZeliardM for a huge effort on both features and project maintenance, including but not limited to: - Features like the HomeKit module for iot devices, iot time module failover, wifi handling and credential improvements for cameras, Tapo login version 3, and V2 energy monitoring for S515D. - A lot of necessary maintenance work including type annotations and cleanups throughout the test suite, modernized docstrings, CI hardening with SHA-pinned actions, and many bug fixes. This helps us to keep the library maintainable and open to new contributions. A warm welcome to our new contributors, with special thanks to those who contributed improvements and fixes: - @alams154: discovery on port 20004 - @bluntman001: iot device classification fix - @bm1549: KLAP v2 transport for iot devices - @darylldelfin: cipher support for newer Tapo firmware - @davidefiocco: vacuum mop water level fix - @epg-pers: selective room cleaning for vacuums - @freeKC: camera discovery and authentication fixes - @gpongelli: extended camera detection - @Ikstar: KL420 color temperature range - @juherr: last alert detection module for cameras, camera error codes and a C200 fixture - @kad: SSL connections to older devices - @KaloyanNaumov: multi-request timeout handling - @loganrosen: KL400L5 color temperature range - @markvanpraet: Tapo C460 support and camera battery fix - @monteccarlos: iot timezone mapping fix - @mrwogu: preset support for Tapo cameras - @nopoz: strip segment module, light transition flag and credentials hash fix - @tk1475: UTC fallback for unset iot device clocks - @wh1t3f1r3: non-retryable network error handling Thanks also to our new contributors who provided device fixtures to help future development efforts: @emanueleg, @fantandrea, @HarryPehkonen, @ijaron, @Krotu, @LostLuma, @mjbohr and @TheLinuxGuy. **This release in numbers:** - 68 merged pull requests from 29 contributors, 27 of them first-time contributors - 8 new modules - 29 new device fixtures - 203 files changed, with 25,199 lines added and 2,585 removed **Implemented enhancements:** - \[Feature Request\] C220 camera line crossing detection on-off switch [\#1551](https://github.com/python-kasa/python-kasa/issues/1551) - SslAesTransport: handshake again when a camera answers 401 to passthrough [\#1771](https://github.com/python-kasa/python-kasa/pull/1771) (@freeKC) - Add LastAlertDetection module for smartcam devices [\#1762](https://github.com/python-kasa/python-kasa/pull/1762) (@juherr) - Add KL420 to TPLINK\_KELVIN color temperature ranges [\#1757](https://github.com/python-kasa/python-kasa/pull/1757) (@Ikstar) - Do not authenticate with a credentials\_hash from a different transport [\#1749](https://github.com/python-kasa/python-kasa/pull/1749) (@nopoz) - Expose the light transition state change flag [\#1745](https://github.com/python-kasa/python-kasa/pull/1745) (@nopoz) - Add strip segment module for configurable light strip length [\#1744](https://github.com/python-kasa/python-kasa/pull/1744) (@nopoz) - Add KL400L5 color temperature range [\#1719](https://github.com/python-kasa/python-kasa/pull/1719) (@loganrosen) - Update smartcam credential handling and tests [\#1664](https://github.com/python-kasa/python-kasa/pull/1664) (@ZeliardM) - Add support for V2 Energy Monitoring for S515D [\#1663](https://github.com/python-kasa/python-kasa/pull/1663) (@ZeliardM) - Add selective room cleaning to vacuum clean module [\#1660](https://github.com/python-kasa/python-kasa/pull/1660) (@epg-pers) - New Wi-Fi handling for SMARTCAM devices [\#1639](https://github.com/python-kasa/python-kasa/pull/1639) (@ZeliardM) - Add support for tapo login\_version 3 in sslaestransport [\#1638](https://github.com/python-kasa/python-kasa/pull/1638) (@ZeliardM) - Add preset support for Tapo cameras [\#1615](https://github.com/python-kasa/python-kasa/pull/1615) (@mrwogu) - Add python 3.14 to supported versions [\#1599](https://github.com/python-kasa/python-kasa/pull/1599) (@rytilahti) - Add discovery port 20004 [\#1595](https://github.com/python-kasa/python-kasa/pull/1595) (@alams154) - Implement IOT Time Module Failover [\#1583](https://github.com/python-kasa/python-kasa/pull/1583) (@ZeliardM) - Add bare bones homekit module for iot devices [\#1566](https://github.com/python-kasa/python-kasa/pull/1566) (@ZeliardM) - Extend smartcam detection support [\#1552](https://github.com/python-kasa/python-kasa/pull/1552) (@gpongelli) **Fixed bugs:** - Time module unavailable for waterleak sensor [\#1613](https://github.com/python-kasa/python-kasa/issues/1613) - 'No time zone found with key EST' in debian 13 [\#1579](https://github.com/python-kasa/python-kasa/issues/1579) - Discovery: accept cameras that only send the encrypt\_type list [\#1770](https://github.com/python-kasa/python-kasa/pull/1770) (@freeKC) - Classify IOT devices via sysinfo regardless of transport \(fixes \#1740\) [\#1769](https://github.com/python-kasa/python-kasa/pull/1769) (@bluntman001) - Fall back to UTC for iot time when the device clock is not set [\#1768](https://github.com/python-kasa/python-kasa/pull/1768) (@tk1475) - Add UNKNOWN\_USERNAME \(-60502\) camera error code [\#1761](https://github.com/python-kasa/python-kasa/pull/1761) (@juherr) - Disable multi requests on timeout during multi-request [\#1759](https://github.com/python-kasa/python-kasa/pull/1759) (@KaloyanNaumov) - Add ECDHE-RSA-AES256 cipher for newer Tapo firmware [\#1755](https://github.com/python-kasa/python-kasa/pull/1755) (@darylldelfin) - Map iot timezone index 18 to America/New\_York instead of EST [\#1743](https://github.com/python-kasa/python-kasa/pull/1743) (@monteccarlos) - fix: use KLAP v2 transport for IOT devices with login version 2 [\#1731](https://github.com/python-kasa/python-kasa/pull/1731) (@bm1549) - Add ENETUNREACH to non-retryable errors in XorTransport [\#1668](https://github.com/python-kasa/python-kasa/pull/1668) (@wh1t3f1r3) - Fix mop set\_waterlevel sending setCleanAttr without type field [\#1667](https://github.com/python-kasa/python-kasa/pull/1667) (@davidefiocco) - Fix SMARTCAM Time module and update tests [\#1659](https://github.com/python-kasa/python-kasa/pull/1659) (@ZeliardM) - Fix camera login version in CLI [\#1658](https://github.com/python-kasa/python-kasa/pull/1658) (@ZeliardM) - Allow SSL connections to older devices [\#1654](https://github.com/python-kasa/python-kasa/pull/1654) (@kad) - waterleaksensor: use parent's Time for alert timestamp [\#1614](https://github.com/python-kasa/python-kasa/pull/1614) (@rytilahti) - Add hold state to thermostatstate [\#1609](https://github.com/python-kasa/python-kasa/pull/1609) (@rytilahti) - Fix thermostat idle reporting on low battery [\#1598](https://github.com/python-kasa/python-kasa/pull/1598) (@rytilahti) - Add shutdown \(summer mode\) to thermostatstate [\#1588](https://github.com/python-kasa/python-kasa/pull/1588) (@rytilahti) - Fix iotstrip child device time handling [\#1584](https://github.com/python-kasa/python-kasa/pull/1584) (@ZeliardM) **Added support for devices:** - Add C200 device fixture [\#1760](https://github.com/python-kasa/python-kasa/pull/1760) (@juherr) - Add P125M fixture for firmware 1.4.4 [\#1746](https://github.com/python-kasa/python-kasa/pull/1746) (@HarryPehkonen) - Add fixtures for KH100, KE100 and KE110 and simulate TRV states [\#1726](https://github.com/python-kasa/python-kasa/pull/1726) (@Krotu) - Add L530EA\(EU\) device fixture [\#1694](https://github.com/python-kasa/python-kasa/pull/1694) (@ZeliardM) - Add C101 test fixture [\#1673](https://github.com/python-kasa/python-kasa/pull/1673) (@ijaron) - Add LB130\(US\) device fixture [\#1669](https://github.com/python-kasa/python-kasa/pull/1669) (@ZeliardM) - Add KL110B\(UN\) device fixture [\#1657](https://github.com/python-kasa/python-kasa/pull/1657) (@ZeliardM) - Add TS15\(US\) device fixture [\#1649](https://github.com/python-kasa/python-kasa/pull/1649) (@ZeliardM) - Add Tapo C460 support [\#1645](https://github.com/python-kasa/python-kasa/pull/1645) (@markvanpraet) - Add P105\(US\) device fixture [\#1644](https://github.com/python-kasa/python-kasa/pull/1644) (@ZeliardM) - Add L430C\(EU\) device fixture [\#1643](https://github.com/python-kasa/python-kasa/pull/1643) (@ZeliardM) - Add L430P\(EU\) device fixture [\#1607](https://github.com/python-kasa/python-kasa/pull/1607) (@LostLuma) - Add S500\(US\)\_1.0\_1.2.0 fixture [\#1569](https://github.com/python-kasa/python-kasa/pull/1569) (@ZeliardM) - Add device fixture for P316M\(US\) [\#1568](https://github.com/python-kasa/python-kasa/pull/1568) (@TheLinuxGuy) - Add L535E\(EU\) 3.0 1.1.8 fixture [\#1545](https://github.com/python-kasa/python-kasa/pull/1545) (@fantandrea) - Adding KL400L10\(US\)\_1.0\_1.0.10 fixture [\#1539](https://github.com/python-kasa/python-kasa/pull/1539) (@mjbohr) - Add TP10\(IT\) 1.0 1.2.5 fixture [\#1538](https://github.com/python-kasa/python-kasa/pull/1538) (@emanueleg) - Add LB100\(US\)\_1.0\_1.8.11 fixture file [\#1515](https://github.com/python-kasa/python-kasa/pull/1515) (@ZeliardM) - Add KS225\(US\)\_1.0\_1.1.1 and L930-5\(EU\)\_1.0\_1.2.5 [\#1509](https://github.com/python-kasa/python-kasa/pull/1509) (@ZeliardM) **Documentation updates:** - How to hash credentials to make use of --credentials-hash flag? [\#1517](https://github.com/python-kasa/python-kasa/issues/1517) - docs: modernize docstrings across the repository [\#1682](https://github.com/python-kasa/python-kasa/pull/1682) (@ZeliardM) - Add a note to emeter guide being kasa-only [\#1512](https://github.com/python-kasa/python-kasa/pull/1512) (@rytilahti) **Project maintenance:** - tests: add type annotations to top-level test files [\#1688](https://github.com/python-kasa/python-kasa/pull/1688) (@ZeliardM) - tests: add type annotations to CLI, protocol, and smartcam tests [\#1687](https://github.com/python-kasa/python-kasa/pull/1687) (@ZeliardM) - tests: add type annotations to Smart tests [\#1686](https://github.com/python-kasa/python-kasa/pull/1686) (@ZeliardM) - tests: add type annotations to IoT tests [\#1685](https://github.com/python-kasa/python-kasa/pull/1685) (@ZeliardM) - tests: add type annotations to transport tests [\#1684](https://github.com/python-kasa/python-kasa/pull/1684) (@ZeliardM) - tests: centralize transport and session cleanup in conftest [\#1683](https://github.com/python-kasa/python-kasa/pull/1683) (@ZeliardM) - ci: pin all GitHub Actions to SHA hashes and update versions [\#1681](https://github.com/python-kasa/python-kasa/pull/1681) (@ZeliardM) - tests: fix typos, child device subtype, CLI patch path, and deprecation test logic [\#1677](https://github.com/python-kasa/python-kasa/pull/1677) (@ZeliardM) - Update GitHub Workflows and Actions [\#1622](https://github.com/python-kasa/python-kasa/pull/1622) (@ZeliardM) - Use log-level debug for smartdevice query error reporting [\#1587](https://github.com/python-kasa/python-kasa/pull/1587) (@rytilahti) - Use Device instead of SmartDevice where feasible [\#1585](https://github.com/python-kasa/python-kasa/pull/1585) (@ZeliardM) **Closed issues:** - Python 3.14 Support [\#1597](https://github.com/python-kasa/python-kasa/issues/1597) - HS300 Child State - Time Module Error [\#1445](https://github.com/python-kasa/python-kasa/issues/1445)
547 lines
19 KiB
Python
547 lines
19 KiB
Python
"""Module for bulbs (LB*, KL*, KB*)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import re
|
|
from dataclasses import dataclass
|
|
from enum import Enum
|
|
from typing import Annotated, cast
|
|
|
|
from mashumaro import DataClassDictMixin
|
|
from mashumaro.config import BaseConfig
|
|
from mashumaro.types import Alias
|
|
|
|
from ..device_type import DeviceType
|
|
from ..deviceconfig import DeviceConfig
|
|
from ..interfaces.light import HSV, ColorTempRange
|
|
from ..module import Module
|
|
from ..protocols import BaseProtocol
|
|
from .iotdevice import IotDevice, KasaException, requires_update
|
|
from .modules import (
|
|
Antitheft,
|
|
Cloud,
|
|
Countdown,
|
|
Emeter,
|
|
Light,
|
|
LightPreset,
|
|
Schedule,
|
|
Time,
|
|
Usage,
|
|
)
|
|
|
|
|
|
class BehaviorMode(str, Enum): # noqa: UP042 TODO: revisit, StrEnum changes str() output
|
|
"""Enum to present type of turn on behavior."""
|
|
|
|
#: Return to the last state known state.
|
|
Last = "last_status"
|
|
#: Use chosen preset.
|
|
Preset = "customize_preset"
|
|
#: Circadian
|
|
Circadian = "circadian"
|
|
|
|
|
|
@dataclass
|
|
class TurnOnBehavior(DataClassDictMixin):
|
|
"""Model to present a single turn on behavior.
|
|
|
|
:param int preset: the index number of wanted preset.
|
|
:param BehaviorMode mode: last status or preset mode.
|
|
If you are changing existing settings, you should not set this manually.
|
|
|
|
To change the behavior, it is only necessary to change the :attr:`preset` field
|
|
to contain either the preset index, or ``None`` for the last known state.
|
|
"""
|
|
|
|
class Config(BaseConfig):
|
|
"""Serialization config."""
|
|
|
|
omit_none = True
|
|
serialize_by_alias = True
|
|
|
|
#: Wanted behavior
|
|
mode: BehaviorMode
|
|
#: Index of preset to use, or ``None`` for the last known state.
|
|
preset: Annotated[int | None, Alias("index")] = None
|
|
brightness: int | None = None
|
|
color_temp: int | None = None
|
|
hue: int | None = None
|
|
saturation: int | None = None
|
|
|
|
|
|
@dataclass
|
|
class TurnOnBehaviors(DataClassDictMixin):
|
|
"""Model to contain turn on behaviors."""
|
|
|
|
#: The behavior when the bulb is turned on programmatically.
|
|
soft: Annotated[TurnOnBehavior, Alias("soft_on")]
|
|
#: The behavior when the bulb has been off from mains power.
|
|
hard: Annotated[TurnOnBehavior, Alias("hard_on")]
|
|
|
|
|
|
TPLINK_KELVIN = {
|
|
"LB130": ColorTempRange(2500, 9000),
|
|
"LB120": ColorTempRange(2700, 6500),
|
|
"LB230": ColorTempRange(2500, 9000),
|
|
"KB130": ColorTempRange(2500, 9000),
|
|
"KL130": ColorTempRange(2500, 9000),
|
|
"KL125": ColorTempRange(2500, 6500),
|
|
"KL135": ColorTempRange(2500, 9000),
|
|
r"KL120\(EU\)": ColorTempRange(2700, 6500),
|
|
r"KL120\(US\)": ColorTempRange(2700, 5000),
|
|
r"KL400L5": ColorTempRange(2500, 9000),
|
|
r"KL420": ColorTempRange(2500, 9000),
|
|
r"KL430": ColorTempRange(2500, 9000),
|
|
}
|
|
|
|
|
|
NON_COLOR_MODE_FLAGS = {"transition_period", "on_off"}
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
class IotBulb(IotDevice):
|
|
r"""Representation of a TP-Link Smart Bulb.
|
|
|
|
To initialize, you have to await :meth:`update()` at least once.
|
|
This will allow accessing the properties using the exposed properties.
|
|
|
|
All changes to the device are done using awaitable methods,
|
|
which will not change the cached values,
|
|
so you must await :meth:`update()` to fetch updated values from the device.
|
|
|
|
Errors reported by the device are raised as
|
|
:class:`KasaException <kasa.exceptions.KasaException>`,
|
|
and should be handled by the user of the library.
|
|
|
|
Examples:
|
|
>>> import asyncio
|
|
>>> bulb = IotBulb("127.0.0.1")
|
|
>>> asyncio.run(bulb.update())
|
|
>>> print(bulb.alias)
|
|
Bedroom Bulb
|
|
|
|
Bulbs, like any other supported devices, can be turned on and off:
|
|
|
|
>>> asyncio.run(bulb.turn_off())
|
|
>>> asyncio.run(bulb.turn_on())
|
|
>>> asyncio.run(bulb.update())
|
|
>>> print(bulb.is_on)
|
|
True
|
|
|
|
Get the light module to interact with light-specific features:
|
|
|
|
>>> light = bulb.modules[Module.Light]
|
|
|
|
You can use the :meth:`~kasa.module.Module.has_feature` method to check for supported light features:
|
|
|
|
>>> light.has_feature("brightness")
|
|
True
|
|
>>> light.has_feature("hsv")
|
|
True
|
|
>>> light.has_feature("color_temp")
|
|
True
|
|
|
|
All known bulbs support changing the brightness:
|
|
|
|
>>> light.brightness
|
|
30
|
|
>>> asyncio.run(light.set_brightness(50))
|
|
>>> asyncio.run(bulb.update())
|
|
>>> light.brightness
|
|
50
|
|
|
|
Bulbs supporting color temperature can be queried for the supported range:
|
|
|
|
>>> if color_temp_feature := light.get_feature("color_temp"):
|
|
... print(
|
|
... f"{color_temp_feature.minimum_value}, "
|
|
... f"{color_temp_feature.maximum_value}"
|
|
... )
|
|
2500, 9000
|
|
>>> asyncio.run(light.set_color_temp(3000))
|
|
>>> asyncio.run(bulb.update())
|
|
>>> light.color_temp
|
|
3000
|
|
|
|
Color bulbs can be adjusted by passing hue, saturation and value:
|
|
|
|
>>> asyncio.run(light.set_hsv(180, 100, 80))
|
|
>>> asyncio.run(bulb.update())
|
|
>>> light.hsv
|
|
HSV(hue=180, saturation=100, value=80)
|
|
|
|
If you don't want to use the default transitions,
|
|
you can pass `transition` in milliseconds.
|
|
All methods changing the light state support this parameter:
|
|
|
|
* :meth:`turn_on`
|
|
* :meth:`turn_off`
|
|
* :meth:`set_hsv`
|
|
* :meth:`set_color_temp`
|
|
* :meth:`set_brightness`
|
|
|
|
Light strips (e.g., KL420L5) do not support this feature,
|
|
but silently ignore the parameter.
|
|
The following changes the brightness over a period of 10 seconds:
|
|
|
|
>>> asyncio.run(light.set_brightness(100, transition=10_000))
|
|
|
|
Bulb configuration presets can be accessed using the light preset module:
|
|
|
|
>>> light_preset = bulb.modules[Module.LightPreset]
|
|
>>> light_preset.preset_states_list[0]
|
|
IotLightPreset(light_on=None, brightness=50, hue=0, saturation=0, color_temp=2700, transition=None)
|
|
|
|
To modify an existing preset, update one of the entries in
|
|
``preset_states_list`` and pass it to
|
|
:meth:`~kasa.interfaces.lightpreset.LightPreset.save_preset`:
|
|
|
|
>>> preset = light_preset.preset_states_list[0]
|
|
>>> preset.brightness
|
|
50
|
|
>>> preset.brightness = 100
|
|
>>> asyncio.run(light_preset.save_preset("Light preset 1", preset))
|
|
>>> asyncio.run(bulb.update())
|
|
>>> light_preset.preset_states_list[0]
|
|
IotLightPreset(light_on=None, brightness=100, hue=0, saturation=0, color_temp=2700, transition=None)
|
|
|
|
""" # noqa: E501
|
|
|
|
LIGHT_SERVICE = "smartlife.iot.smartbulb.lightingservice"
|
|
SET_LIGHT_METHOD = "transition_light_state"
|
|
emeter_type = "smartlife.iot.common.emeter"
|
|
|
|
def __init__(
|
|
self,
|
|
host: str,
|
|
*,
|
|
config: DeviceConfig | None = None,
|
|
protocol: BaseProtocol | None = None,
|
|
) -> None:
|
|
super().__init__(host=host, config=config, protocol=protocol)
|
|
self._device_type = DeviceType.Bulb
|
|
|
|
async def _initialize_modules(self) -> None:
|
|
"""Initialize modules not added in init."""
|
|
await super()._initialize_modules()
|
|
self.add_module(
|
|
Module.IotSchedule, Schedule(self, "smartlife.iot.common.schedule")
|
|
)
|
|
self.add_module(Module.IotUsage, Usage(self, "smartlife.iot.common.schedule"))
|
|
self.add_module(
|
|
Module.IotAntitheft, Antitheft(self, "smartlife.iot.common.anti_theft")
|
|
)
|
|
self.add_module(Module.Time, Time(self, "smartlife.iot.common.timesetting"))
|
|
self.add_module(Module.Energy, Emeter(self, self.emeter_type))
|
|
self.add_module(Module.IotCountdown, Countdown(self, "countdown"))
|
|
self.add_module(Module.IotCloud, Cloud(self, "smartlife.iot.common.cloud"))
|
|
self.add_module(Module.Light, Light(self, self.LIGHT_SERVICE))
|
|
self.add_module(Module.LightPreset, LightPreset(self, self.LIGHT_SERVICE))
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _is_color(self) -> bool:
|
|
"""Whether the bulb supports color changes."""
|
|
sys_info = self.sys_info
|
|
return bool(sys_info["is_color"])
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _is_dimmable(self) -> bool:
|
|
"""Whether the bulb supports brightness changes."""
|
|
sys_info = self.sys_info
|
|
return bool(sys_info["is_dimmable"])
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _is_variable_color_temp(self) -> bool:
|
|
"""Whether the bulb supports color temperature changes."""
|
|
sys_info = self.sys_info
|
|
return bool(sys_info["is_variable_color_temp"])
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _valid_temperature_range(self) -> ColorTempRange:
|
|
"""Return the device-specific white temperature range (in Kelvin).
|
|
|
|
:return: White temperature range in Kelvin (minimum, maximum)
|
|
"""
|
|
if not self._is_variable_color_temp:
|
|
raise KasaException("Color temperature not supported")
|
|
|
|
for model, temp_range in TPLINK_KELVIN.items():
|
|
sys_info = self.sys_info
|
|
if re.match(model, sys_info["model"]):
|
|
return temp_range
|
|
|
|
_LOGGER.warning("Unknown color temperature range, fallback to 2700-5000")
|
|
return ColorTempRange(2700, 5000)
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def light_state(self) -> dict[str, str]:
|
|
"""Query the light state."""
|
|
light_state = self.sys_info["light_state"]
|
|
if light_state is None:
|
|
raise KasaException(
|
|
"The device has no light_state or you have not called update()"
|
|
)
|
|
|
|
# if the bulb is off, its state is stored under a different key
|
|
# as is_on property depends on on_off itself, we check it here manually
|
|
is_on = light_state["on_off"]
|
|
if not is_on:
|
|
off_state = {**light_state["dft_on_state"], "on_off": is_on}
|
|
return cast(dict, off_state)
|
|
|
|
return light_state
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _has_effects(self) -> bool:
|
|
"""Return True if the device supports effects."""
|
|
return "lighting_effect_state" in self.sys_info
|
|
|
|
async def get_light_details(self) -> dict[str, int]:
|
|
"""Return light details.
|
|
|
|
Example::
|
|
|
|
{'lamp_beam_angle': 290, 'min_voltage': 220, 'max_voltage': 240,
|
|
'wattage': 5, 'incandescent_equivalent': 40, 'max_lumens': 450,
|
|
'color_rendering_index': 80}
|
|
"""
|
|
return await self._query_helper(self.LIGHT_SERVICE, "get_light_details")
|
|
|
|
async def get_turn_on_behavior(self) -> TurnOnBehaviors:
|
|
"""Return the behavior for turning the bulb on."""
|
|
return TurnOnBehaviors.from_dict(
|
|
await self._query_helper(self.LIGHT_SERVICE, "get_default_behavior")
|
|
)
|
|
|
|
async def set_turn_on_behavior(self, behavior: TurnOnBehaviors) -> dict:
|
|
"""Set the behavior for turning the bulb on.
|
|
|
|
If you do not want to manually construct the behavior object,
|
|
you should use :func:`get_turn_on_behavior` to get the current settings.
|
|
"""
|
|
return await self._query_helper(
|
|
self.LIGHT_SERVICE, "set_default_behavior", behavior.to_dict()
|
|
)
|
|
|
|
async def get_light_state(self) -> dict[str, dict]:
|
|
"""Query the light state."""
|
|
# TODO: add warning and refer to use light.state?
|
|
return await self._query_helper(self.LIGHT_SERVICE, "get_light_state")
|
|
|
|
async def _set_light_state(
|
|
self, state: dict, *, transition: int | None = None
|
|
) -> dict:
|
|
"""Set the light state."""
|
|
state = {**state}
|
|
if transition is not None:
|
|
state["transition_period"] = transition
|
|
|
|
if "brightness" in state:
|
|
self._raise_for_invalid_brightness(state["brightness"])
|
|
|
|
# if no on/off is defined, turn on the light
|
|
if "on_off" not in state:
|
|
state["on_off"] = 1
|
|
|
|
# If we are turning on without any color mode flags,
|
|
# we do not want to set ignore_default to ensure
|
|
# we restore the previous state.
|
|
if state["on_off"] and NON_COLOR_MODE_FLAGS.issuperset(state):
|
|
state["ignore_default"] = 0
|
|
else:
|
|
# This is necessary to allow turning on into a specific state
|
|
state["ignore_default"] = 1
|
|
|
|
light_state = await self._query_helper(
|
|
self.LIGHT_SERVICE, self.SET_LIGHT_METHOD, state
|
|
)
|
|
return light_state
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _hsv(self) -> HSV:
|
|
"""Return the current HSV state of the bulb.
|
|
|
|
:return: hue, saturation and value (degrees, %, %)
|
|
"""
|
|
if not self._is_color:
|
|
raise KasaException("Bulb does not support color.")
|
|
|
|
light_state = cast(dict, self.light_state)
|
|
|
|
hue = light_state["hue"]
|
|
saturation = light_state["saturation"]
|
|
value = self._brightness
|
|
|
|
# Simple HSV(hue, saturation, value) is less efficent than below
|
|
# due to the cpython implementation.
|
|
return tuple.__new__(HSV, (hue, saturation, value))
|
|
|
|
@requires_update
|
|
async def _set_hsv(
|
|
self,
|
|
hue: int,
|
|
saturation: int,
|
|
value: int | None = None,
|
|
*,
|
|
transition: int | None = None,
|
|
) -> dict:
|
|
"""Set new HSV.
|
|
|
|
:param int hue: hue in degrees
|
|
:param int saturation: saturation in percentage [0,100]
|
|
:param int value: value in percentage [0, 100]
|
|
:param int transition: transition in milliseconds.
|
|
"""
|
|
if not self._is_color:
|
|
raise KasaException("Bulb does not support color.")
|
|
|
|
if not isinstance(hue, int):
|
|
raise TypeError("Hue must be an integer.")
|
|
if not (0 <= hue <= 360):
|
|
raise ValueError(f"Invalid hue value: {hue} (valid range: 0-360)")
|
|
|
|
if not isinstance(saturation, int):
|
|
raise TypeError("Saturation must be an integer.")
|
|
if not (0 <= saturation <= 100):
|
|
raise ValueError(
|
|
f"Invalid saturation value: {saturation} (valid range: 0-100%)"
|
|
)
|
|
|
|
light_state = {
|
|
"hue": hue,
|
|
"saturation": saturation,
|
|
"color_temp": 0,
|
|
}
|
|
|
|
if value is not None:
|
|
self._raise_for_invalid_brightness(value)
|
|
light_state["brightness"] = value
|
|
|
|
return await self._set_light_state(light_state, transition=transition)
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _color_temp(self) -> int:
|
|
"""Return color temperature of the device in kelvin."""
|
|
if not self._is_variable_color_temp:
|
|
raise KasaException("Bulb does not support colortemp.")
|
|
|
|
light_state = self.light_state
|
|
return int(light_state["color_temp"])
|
|
|
|
@requires_update
|
|
async def _set_color_temp(
|
|
self, temp: int, *, brightness: int | None = None, transition: int | None = None
|
|
) -> dict:
|
|
"""Set the color temperature of the device in kelvin.
|
|
|
|
:param int temp: The new color temperature, in Kelvin
|
|
:param int transition: transition in milliseconds.
|
|
"""
|
|
if not self._is_variable_color_temp:
|
|
raise KasaException("Bulb does not support colortemp.")
|
|
|
|
valid_temperature_range = self._valid_temperature_range
|
|
if temp < valid_temperature_range[0] or temp > valid_temperature_range[1]:
|
|
raise ValueError(
|
|
"Temperature should be between {} and {}, was {}".format(
|
|
*valid_temperature_range, temp
|
|
)
|
|
)
|
|
|
|
light_state = {"color_temp": temp}
|
|
if brightness is not None:
|
|
light_state["brightness"] = brightness
|
|
|
|
return await self._set_light_state(light_state, transition=transition)
|
|
|
|
def _raise_for_invalid_brightness(self, value: int) -> None:
|
|
if not isinstance(value, int):
|
|
raise TypeError("Brightness must be an integer")
|
|
if not (0 <= value <= 100):
|
|
raise ValueError(f"Invalid brightness value: {value} (valid range: 0-100%)")
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def _brightness(self) -> int:
|
|
"""Return the current brightness in percentage."""
|
|
if not self._is_dimmable: # pragma: no cover
|
|
raise KasaException("Bulb is not dimmable.")
|
|
|
|
# If the device supports effects and one is active, we get the brightness
|
|
# from the effect. This is not required when setting the brightness as
|
|
# the device handles it via set_light_state
|
|
if (
|
|
light_effect := self.modules.get(Module.IotLightEffect)
|
|
) is not None and light_effect.effect != light_effect.LIGHT_EFFECTS_OFF:
|
|
return light_effect.brightness
|
|
light_state = self.light_state
|
|
return int(light_state["brightness"])
|
|
|
|
@requires_update
|
|
async def _set_brightness(
|
|
self, brightness: int, *, transition: int | None = None
|
|
) -> dict:
|
|
"""Set the brightness in percentage.
|
|
|
|
:param int brightness: brightness in percent
|
|
:param int transition: transition in milliseconds.
|
|
"""
|
|
if not self._is_dimmable: # pragma: no cover
|
|
raise KasaException("Bulb is not dimmable.")
|
|
|
|
self._raise_for_invalid_brightness(brightness)
|
|
|
|
light_state = {"brightness": brightness}
|
|
return await self._set_light_state(light_state, transition=transition)
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def is_on(self) -> bool:
|
|
"""Return whether the device is on."""
|
|
light_state = self.light_state
|
|
return bool(light_state["on_off"])
|
|
|
|
async def turn_off(self, *, transition: int | None = None, **kwargs) -> dict:
|
|
"""Turn the bulb off.
|
|
|
|
:param int transition: transition in milliseconds.
|
|
"""
|
|
return await self._set_light_state({"on_off": 0}, transition=transition)
|
|
|
|
async def turn_on(self, *, transition: int | None = None, **kwargs) -> dict:
|
|
"""Turn the bulb on.
|
|
|
|
:param int transition: transition in milliseconds.
|
|
"""
|
|
return await self._set_light_state({"on_off": 1}, transition=transition)
|
|
|
|
@property # type: ignore
|
|
@requires_update
|
|
def has_emeter(self) -> bool:
|
|
"""Return that the bulb has an emeter."""
|
|
return True
|
|
|
|
async def set_alias(self, alias: str) -> dict:
|
|
"""Set the device name (alias).
|
|
|
|
Overridden to use a different module name.
|
|
"""
|
|
return await self._query_helper(
|
|
"smartlife.iot.common.system", "set_dev_alias", {"alias": alias}
|
|
)
|
|
|
|
@property
|
|
def max_device_response_size(self) -> int:
|
|
"""Returns the maximum response size the device can safely construct."""
|
|
return 4096
|