python-kasa 0.6.2.1__py3-none-any.whl → 0.7.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. kasa/__init__.py +88 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +406 -0
  5. kasa/device_factory.py +83 -44
  6. kasa/device_type.py +7 -3
  7. kasa/deviceconfig.py +16 -9
  8. kasa/discover.py +100 -81
  9. kasa/emeterstatus.py +7 -5
  10. kasa/exceptions.py +41 -26
  11. kasa/feature.py +201 -0
  12. kasa/httpclient.py +21 -14
  13. kasa/interfaces/__init__.py +16 -0
  14. kasa/interfaces/fan.py +20 -0
  15. kasa/interfaces/led.py +38 -0
  16. kasa/interfaces/light.py +133 -0
  17. kasa/interfaces/lighteffect.py +80 -0
  18. kasa/interfaces/lightpreset.py +76 -0
  19. kasa/iot/__init__.py +18 -0
  20. kasa/{effects.py → iot/effects.py} +4 -2
  21. kasa/{smartbulb.py → iot/iotbulb.py} +100 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +157 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +42 -33
  24. kasa/iot/iotlightstrip.py +71 -0
  25. kasa/{modules/module.py → iot/iotmodule.py} +22 -42
  26. kasa/iot/iotplug.py +94 -0
  27. kasa/{smartstrip.py → iot/iotstrip.py} +57 -75
  28. kasa/{modules → iot/modules}/__init__.py +10 -2
  29. kasa/{modules → iot/modules}/ambientlight.py +31 -3
  30. kasa/{modules → iot/modules}/antitheft.py +1 -0
  31. kasa/{modules → iot/modules}/cloud.py +25 -6
  32. kasa/{modules → iot/modules}/countdown.py +1 -0
  33. kasa/iot/modules/emeter.py +210 -0
  34. kasa/iot/modules/led.py +32 -0
  35. kasa/iot/modules/light.py +221 -0
  36. kasa/iot/modules/lighteffect.py +122 -0
  37. kasa/iot/modules/lightpreset.py +151 -0
  38. kasa/{modules → iot/modules}/motion.py +8 -8
  39. kasa/{modules → iot/modules}/rulemodule.py +11 -12
  40. kasa/{modules → iot/modules}/schedule.py +1 -0
  41. kasa/{modules → iot/modules}/time.py +5 -4
  42. kasa/{modules → iot/modules}/usage.py +10 -8
  43. kasa/iotprotocol.py +22 -20
  44. kasa/klaptransport.py +25 -15
  45. kasa/module.py +136 -0
  46. kasa/modulemapping.py +25 -0
  47. kasa/modulemapping.pyi +96 -0
  48. kasa/protocol.py +6 -4
  49. kasa/smart/__init__.py +6 -0
  50. kasa/smart/effects.py +429 -0
  51. kasa/smart/modules/__init__.py +57 -0
  52. kasa/smart/modules/alarm.py +142 -0
  53. kasa/smart/modules/autooff.py +96 -0
  54. kasa/smart/modules/batterysensor.py +54 -0
  55. kasa/smart/modules/brightness.py +66 -0
  56. kasa/smart/modules/childdevice.py +10 -0
  57. kasa/smart/modules/cloud.py +42 -0
  58. kasa/smart/modules/color.py +96 -0
  59. kasa/smart/modules/colortemperature.py +78 -0
  60. kasa/smart/modules/contactsensor.py +42 -0
  61. kasa/smart/modules/devicemodule.py +22 -0
  62. kasa/smart/modules/energy.py +101 -0
  63. kasa/smart/modules/fan.py +80 -0
  64. kasa/smart/modules/firmware.py +216 -0
  65. kasa/smart/modules/frostprotection.py +59 -0
  66. kasa/smart/modules/humiditysensor.py +55 -0
  67. kasa/smart/modules/led.py +49 -0
  68. kasa/smart/modules/light.py +139 -0
  69. kasa/smart/modules/lighteffect.py +115 -0
  70. kasa/smart/modules/lightpreset.py +142 -0
  71. kasa/smart/modules/lightstripeffect.py +135 -0
  72. kasa/smart/modules/lighttransition.py +183 -0
  73. kasa/smart/modules/reportmode.py +36 -0
  74. kasa/smart/modules/temperaturecontrol.py +177 -0
  75. kasa/smart/modules/temperaturesensor.py +77 -0
  76. kasa/smart/modules/time.py +57 -0
  77. kasa/smart/modules/waterleaksensor.py +66 -0
  78. kasa/smart/smartchilddevice.py +65 -0
  79. kasa/smart/smartdevice.py +653 -0
  80. kasa/smart/smartmodule.py +112 -0
  81. kasa/smartprotocol.py +107 -41
  82. kasa/tests/conftest.py +27 -562
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/fakeprotocol_iot.py +64 -6
  86. kasa/tests/fakeprotocol_smart.py +215 -22
  87. kasa/tests/fixtureinfo.py +154 -0
  88. kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +221 -0
  89. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +547 -0
  90. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +391 -0
  91. kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +1557 -0
  92. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +899 -0
  93. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +479 -0
  94. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +449 -0
  95. kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +173 -0
  96. kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +204 -0
  97. kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +566 -0
  98. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  99. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  100. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  101. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  102. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  103. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  104. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  105. kasa/tests/smart/__init__.py +0 -0
  106. kasa/tests/smart/features/__init__.py +0 -0
  107. kasa/tests/smart/features/test_brightness.py +55 -0
  108. kasa/tests/smart/features/test_colortemp.py +30 -0
  109. kasa/tests/smart/modules/__init__.py +0 -0
  110. kasa/tests/smart/modules/test_contact.py +28 -0
  111. kasa/tests/smart/modules/test_fan.py +79 -0
  112. kasa/tests/smart/modules/test_firmware.py +108 -0
  113. kasa/tests/smart/modules/test_humidity.py +28 -0
  114. kasa/tests/smart/modules/test_light_effect.py +41 -0
  115. kasa/tests/smart/modules/test_temperature.py +47 -0
  116. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  117. kasa/tests/smart/modules/test_waterleak.py +42 -0
  118. kasa/tests/test_aestransport.py +115 -23
  119. kasa/tests/test_bulb.py +115 -85
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +216 -0
  123. kasa/tests/test_device.py +268 -0
  124. kasa/tests/test_device_factory.py +61 -35
  125. kasa/tests/test_device_type.py +1 -1
  126. kasa/tests/test_deviceconfig.py +2 -2
  127. kasa/tests/test_dimmer.py +33 -24
  128. kasa/tests/test_discovery.py +112 -63
  129. kasa/tests/test_emeter.py +14 -10
  130. kasa/tests/test_feature.py +205 -0
  131. kasa/tests/test_httpclient.py +9 -9
  132. kasa/tests/test_iotdevice.py +286 -0
  133. kasa/tests/test_klapprotocol.py +94 -37
  134. kasa/tests/test_lightstrip.py +24 -19
  135. kasa/tests/test_plug.py +46 -8
  136. kasa/tests/test_protocol.py +8 -10
  137. kasa/tests/test_readme_examples.py +87 -26
  138. kasa/tests/test_smartdevice.py +203 -311
  139. kasa/tests/test_smartprotocol.py +130 -25
  140. kasa/tests/test_strip.py +15 -6
  141. kasa/tests/test_usage.py +1 -1
  142. kasa/xortransport.py +15 -12
  143. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  145. kasa/modules/emeter.py +0 -111
  146. kasa/smartlightstrip.py +0 -143
  147. kasa/smartplug.py +0 -91
  148. kasa/tapo/__init__.py +0 -7
  149. kasa/tapo/childdevice.py +0 -41
  150. kasa/tapo/tapobulb.py +0 -262
  151. kasa/tapo/tapodevice.py +0 -409
  152. kasa/tapo/tapoplug.py +0 -45
  153. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  154. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  155. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  156. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  157. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  158. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  159. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  160. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  161. python_kasa-0.6.2.1.dist-info/RECORD +0 -167
  162. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
kasa/feature.py ADDED
@@ -0,0 +1,201 @@
1
+ """Generic interface for defining device features."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from dataclasses import dataclass
7
+ from enum import Enum, auto
8
+ from typing import TYPE_CHECKING, Any, Callable
9
+
10
+ if TYPE_CHECKING:
11
+ from .device import Device
12
+
13
+
14
+ _LOGGER = logging.getLogger(__name__)
15
+
16
+
17
+ @dataclass
18
+ class Feature:
19
+ """Feature defines a generic interface for device features."""
20
+
21
+ class Type(Enum):
22
+ """Type to help decide how to present the feature."""
23
+
24
+ #: Sensor is an informative read-only value
25
+ Sensor = auto()
26
+ #: BinarySensor is a read-only boolean
27
+ BinarySensor = auto()
28
+ #: Switch is a boolean setting
29
+ Switch = auto()
30
+ #: Action triggers some action on device
31
+ Action = auto()
32
+ #: Number defines a numeric setting
33
+ #: See :ref:`range_getter`, :ref:`minimum_value`, and :ref:`maximum_value`
34
+ Number = auto()
35
+ #: Choice defines a setting with pre-defined values
36
+ Choice = auto()
37
+ Unknown = -1
38
+
39
+ # TODO: unsure if this is a great idea..
40
+ Sensor = Type.Sensor
41
+ BinarySensor = Type.BinarySensor
42
+ Switch = Type.Switch
43
+ Action = Type.Action
44
+ Number = Type.Number
45
+ Choice = Type.Choice
46
+
47
+ class Category(Enum):
48
+ """Category hint to allow feature grouping."""
49
+
50
+ #: Primary features control the device state directly.
51
+ #: Examples include turning the device on/off, or adjusting its brightness.
52
+ Primary = auto()
53
+ #: Config features change device behavior without immediate state changes.
54
+ Config = auto()
55
+ #: Informative/sensor features deliver some potentially interesting information.
56
+ Info = auto()
57
+ #: Debug features deliver more verbose information then informative features.
58
+ #: You may want to hide these per default to avoid cluttering your UI.
59
+ Debug = auto()
60
+ #: The default category if none is specified.
61
+ Unset = -1
62
+
63
+ #: Device instance required for getting and setting values
64
+ device: Device
65
+ #: Identifier
66
+ id: str
67
+ #: User-friendly short description
68
+ name: str
69
+ #: Name of the property that allows accessing the value
70
+ attribute_getter: str | Callable | None = None
71
+ #: Name of the method that allows changing the value
72
+ attribute_setter: str | None = None
73
+ #: Container storing the data, this overrides 'device' for getters
74
+ container: Any = None
75
+ #: Icon suggestion
76
+ icon: str | None = None
77
+ #: Unit, if applicable
78
+ unit: str | None = None
79
+ #: Category hint for downstreams
80
+ category: Feature.Category = Category.Unset
81
+ #: Type of the feature
82
+ type: Feature.Type = Type.Sensor
83
+
84
+ # Display hints offer a way suggest how the value should be shown to users
85
+ #: Hint to help rounding the sensor values to given after-comma digits
86
+ precision_hint: int | None = None
87
+
88
+ # Number-specific attributes
89
+ #: Minimum value
90
+ minimum_value: int = 0
91
+ #: Maximum value
92
+ maximum_value: int = 2**16 # Arbitrary max
93
+ #: Attribute containing the name of the range getter property.
94
+ #: If set, this property will be used to set *minimum_value* and *maximum_value*.
95
+ range_getter: str | None = None
96
+
97
+ # Choice-specific attributes
98
+ #: List of choices as enum
99
+ choices: list[str] | None = None
100
+ #: Attribute name of the choices getter property.
101
+ #: If set, this property will be used to set *choices*.
102
+ choices_getter: str | None = None
103
+
104
+ def __post_init__(self):
105
+ """Handle late-binding of members."""
106
+ # Populate minimum & maximum values, if range_getter is given
107
+ container = self.container if self.container is not None else self.device
108
+ if self.range_getter is not None:
109
+ self.minimum_value, self.maximum_value = getattr(
110
+ container, self.range_getter
111
+ )
112
+
113
+ # Populate choices, if choices_getter is given
114
+ if self.choices_getter is not None:
115
+ self.choices = getattr(container, self.choices_getter)
116
+
117
+ # Set the category, if unset
118
+ if self.category is Feature.Category.Unset:
119
+ if self.attribute_setter:
120
+ self.category = Feature.Category.Config
121
+ else:
122
+ self.category = Feature.Category.Info
123
+
124
+ if self.category == Feature.Category.Config and self.type in [
125
+ Feature.Type.Sensor,
126
+ Feature.Type.BinarySensor,
127
+ ]:
128
+ raise ValueError(
129
+ f"Invalid type for configurable feature: {self.name} ({self.id}):"
130
+ f" {self.type}"
131
+ )
132
+
133
+ @property
134
+ def value(self):
135
+ """Return the current value."""
136
+ if self.type == Feature.Type.Action:
137
+ return "<Action>"
138
+ if self.attribute_getter is None:
139
+ raise ValueError("Not an action and no attribute_getter set")
140
+
141
+ container = self.container if self.container is not None else self.device
142
+ if isinstance(self.attribute_getter, Callable):
143
+ return self.attribute_getter(container)
144
+ return getattr(container, self.attribute_getter)
145
+
146
+ async def set_value(self, value):
147
+ """Set the value."""
148
+ if self.attribute_setter is None:
149
+ raise ValueError("Tried to set read-only feature.")
150
+ if self.type == Feature.Type.Number: # noqa: SIM102
151
+ if value < self.minimum_value or value > self.maximum_value:
152
+ raise ValueError(
153
+ f"Value {value} out of range "
154
+ f"[{self.minimum_value}, {self.maximum_value}]"
155
+ )
156
+ elif self.type == Feature.Type.Choice: # noqa: SIM102
157
+ if value not in self.choices:
158
+ raise ValueError(
159
+ f"Unexpected value for {self.name}: {value}"
160
+ f" - allowed: {self.choices}"
161
+ )
162
+
163
+ container = self.container if self.container is not None else self.device
164
+ if self.type == Feature.Type.Action:
165
+ return await getattr(container, self.attribute_setter)()
166
+
167
+ return await getattr(container, self.attribute_setter)(value)
168
+
169
+ def __repr__(self):
170
+ try:
171
+ value = self.value
172
+ choices = self.choices
173
+ except Exception as ex:
174
+ return f"Unable to read value ({self.id}): {ex}"
175
+
176
+ if self.type == Feature.Type.Choice:
177
+ if not isinstance(choices, list) or value not in choices:
178
+ _LOGGER.warning(
179
+ "Invalid value for for choice %s (%s): %s not in %s",
180
+ self.name,
181
+ self.id,
182
+ value,
183
+ choices,
184
+ )
185
+ return (
186
+ f"{self.name} ({self.id}): invalid value '{value}' not in {choices}"
187
+ )
188
+ value = " ".join(
189
+ [f"*{choice}*" if choice == value else choice for choice in choices]
190
+ )
191
+ if self.precision_hint is not None and value is not None:
192
+ value = round(self.value, self.precision_hint)
193
+
194
+ s = f"{self.name} ({self.id}): {value}"
195
+ if self.unit is not None:
196
+ s += f" {self.unit}"
197
+
198
+ if self.type == Feature.Type.Number:
199
+ s += f" (range: {self.minimum_value}-{self.maximum_value})"
200
+
201
+ return s
kasa/httpclient.py CHANGED
@@ -1,18 +1,24 @@
1
1
  """Module for HttpClientSession class."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  import asyncio
3
- from typing import Any, Dict, Optional, Tuple, Union
6
+ import logging
7
+ from typing import Any, Dict
4
8
 
5
9
  import aiohttp
6
10
  from yarl import URL
7
11
 
8
12
  from .deviceconfig import DeviceConfig
9
13
  from .exceptions import (
10
- ConnectionException,
11
- SmartDeviceException,
12
- TimeoutException,
14
+ KasaException,
15
+ TimeoutError,
16
+ _ConnectionError,
13
17
  )
14
18
  from .json import loads as json_loads
15
19
 
20
+ _LOGGER = logging.getLogger(__name__)
21
+
16
22
 
17
23
  def get_cookie_jar() -> aiohttp.CookieJar:
18
24
  """Return a new cookie jar with the correct options for device communication."""
@@ -44,16 +50,17 @@ class HttpClient:
44
50
  self,
45
51
  url: URL,
46
52
  *,
47
- params: Optional[Dict[str, Any]] = None,
48
- data: Optional[bytes] = None,
49
- json: Optional[Union[Dict, Any]] = None,
50
- headers: Optional[Dict[str, str]] = None,
51
- cookies_dict: Optional[Dict[str, str]] = None,
52
- ) -> Tuple[int, Optional[Union[Dict, bytes]]]:
53
+ params: dict[str, Any] | None = None,
54
+ data: bytes | None = None,
55
+ json: dict | Any | None = None,
56
+ headers: dict[str, str] | None = None,
57
+ cookies_dict: dict[str, str] | None = None,
58
+ ) -> tuple[int, dict | bytes | None]:
53
59
  """Send an http post request to the device.
54
60
 
55
61
  If the request is provided via the json parameter json will be returned.
56
62
  """
63
+ _LOGGER.debug("Posting to %s", url)
57
64
  response_data = None
58
65
  self._last_url = url
59
66
  self.client.cookie_jar.clear()
@@ -82,23 +89,23 @@ class HttpClient:
82
89
  response_data = json_loads(response_data.decode())
83
90
 
84
91
  except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError) as ex:
85
- raise ConnectionException(
92
+ raise _ConnectionError(
86
93
  f"Device connection error: {self._config.host}: {ex}", ex
87
94
  ) from ex
88
95
  except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as ex:
89
- raise TimeoutException(
96
+ raise TimeoutError(
90
97
  "Unable to query the device, "
91
98
  + f"timed out: {self._config.host}: {ex}",
92
99
  ex,
93
100
  ) from ex
94
101
  except Exception as ex:
95
- raise SmartDeviceException(
102
+ raise KasaException(
96
103
  f"Unable to query the device: {self._config.host}: {ex}", ex
97
104
  ) from ex
98
105
 
99
106
  return resp.status, response_data
100
107
 
101
- def get_cookie(self, cookie_name: str) -> Optional[str]:
108
+ def get_cookie(self, cookie_name: str) -> str | None:
102
109
  """Return the cookie with cookie_name."""
103
110
  if cookie := self.client.cookie_jar.filter_cookies(self._last_url).get(
104
111
  cookie_name
@@ -0,0 +1,16 @@
1
+ """Package for interfaces."""
2
+
3
+ from .fan import Fan
4
+ from .led import Led
5
+ from .light import Light, LightState
6
+ from .lighteffect import LightEffect
7
+ from .lightpreset import LightPreset
8
+
9
+ __all__ = [
10
+ "Fan",
11
+ "Led",
12
+ "Light",
13
+ "LightEffect",
14
+ "LightState",
15
+ "LightPreset",
16
+ ]
kasa/interfaces/fan.py ADDED
@@ -0,0 +1,20 @@
1
+ """Module for Fan Interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+ from ..module import Module
8
+
9
+
10
+ class Fan(Module, ABC):
11
+ """Interface for a Fan."""
12
+
13
+ @property
14
+ @abstractmethod
15
+ def fan_speed_level(self) -> int:
16
+ """Return fan speed level."""
17
+
18
+ @abstractmethod
19
+ async def set_fan_speed_level(self, level: int):
20
+ """Set fan speed level."""
kasa/interfaces/led.py ADDED
@@ -0,0 +1,38 @@
1
+ """Module for base light effect module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+ from ..feature import Feature
8
+ from ..module import Module
9
+
10
+
11
+ class Led(Module, ABC):
12
+ """Base interface to represent a LED module."""
13
+
14
+ def _initialize_features(self):
15
+ """Initialize features."""
16
+ device = self._device
17
+ self._add_feature(
18
+ Feature(
19
+ device=device,
20
+ container=self,
21
+ name="LED",
22
+ id="led",
23
+ icon="mdi:led",
24
+ attribute_getter="led",
25
+ attribute_setter="set_led",
26
+ type=Feature.Type.Switch,
27
+ category=Feature.Category.Config,
28
+ )
29
+ )
30
+
31
+ @property
32
+ @abstractmethod
33
+ def led(self) -> bool:
34
+ """Return current led status."""
35
+
36
+ @abstractmethod
37
+ async def set_led(self, enable: bool) -> None:
38
+ """Set led."""
@@ -0,0 +1,133 @@
1
+ """Module for Device base class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass
7
+ from typing import NamedTuple
8
+
9
+ from ..module import Module
10
+
11
+
12
+ @dataclass
13
+ class LightState:
14
+ """Class for smart light preset info."""
15
+
16
+ light_on: bool | None = None
17
+ brightness: int | None = None
18
+ hue: int | None = None
19
+ saturation: int | None = None
20
+ color_temp: int | None = None
21
+ transition: bool | None = None
22
+
23
+
24
+ class ColorTempRange(NamedTuple):
25
+ """Color temperature range."""
26
+
27
+ min: int
28
+ max: int
29
+
30
+
31
+ class HSV(NamedTuple):
32
+ """Hue-saturation-value."""
33
+
34
+ hue: int
35
+ saturation: int
36
+ value: int
37
+
38
+
39
+ class Light(Module, ABC):
40
+ """Base class for TP-Link Light."""
41
+
42
+ @property
43
+ @abstractmethod
44
+ def is_dimmable(self) -> bool:
45
+ """Whether the light supports brightness changes."""
46
+
47
+ @property
48
+ @abstractmethod
49
+ def is_color(self) -> bool:
50
+ """Whether the bulb supports color changes."""
51
+
52
+ @property
53
+ @abstractmethod
54
+ def is_variable_color_temp(self) -> bool:
55
+ """Whether the bulb supports color temperature changes."""
56
+
57
+ @property
58
+ @abstractmethod
59
+ def valid_temperature_range(self) -> ColorTempRange:
60
+ """Return the device-specific white temperature range (in Kelvin).
61
+
62
+ :return: White temperature range in Kelvin (minimum, maximum)
63
+ """
64
+
65
+ @property
66
+ @abstractmethod
67
+ def has_effects(self) -> bool:
68
+ """Return True if the device supports effects."""
69
+
70
+ @property
71
+ @abstractmethod
72
+ def hsv(self) -> HSV:
73
+ """Return the current HSV state of the bulb.
74
+
75
+ :return: hue, saturation and value (degrees, %, %)
76
+ """
77
+
78
+ @property
79
+ @abstractmethod
80
+ def color_temp(self) -> int:
81
+ """Whether the bulb supports color temperature changes."""
82
+
83
+ @property
84
+ @abstractmethod
85
+ def brightness(self) -> int:
86
+ """Return the current brightness in percentage."""
87
+
88
+ @abstractmethod
89
+ async def set_hsv(
90
+ self,
91
+ hue: int,
92
+ saturation: int,
93
+ value: int | None = None,
94
+ *,
95
+ transition: int | None = None,
96
+ ) -> dict:
97
+ """Set new HSV.
98
+
99
+ Note, transition is not supported and will be ignored.
100
+
101
+ :param int hue: hue in degrees
102
+ :param int saturation: saturation in percentage [0,100]
103
+ :param int value: value in percentage [0, 100]
104
+ :param int transition: transition in milliseconds.
105
+ """
106
+
107
+ @abstractmethod
108
+ async def set_color_temp(
109
+ self, temp: int, *, brightness=None, transition: int | None = None
110
+ ) -> dict:
111
+ """Set the color temperature of the device in kelvin.
112
+
113
+ Note, transition is not supported and will be ignored.
114
+
115
+ :param int temp: The new color temperature, in Kelvin
116
+ :param int transition: transition in milliseconds.
117
+ """
118
+
119
+ @abstractmethod
120
+ async def set_brightness(
121
+ self, brightness: int, *, transition: int | None = None
122
+ ) -> dict:
123
+ """Set the brightness in percentage.
124
+
125
+ Note, transition is not supported and will be ignored.
126
+
127
+ :param int brightness: brightness in percent
128
+ :param int transition: transition in milliseconds.
129
+ """
130
+
131
+ @abstractmethod
132
+ async def set_state(self, state: LightState) -> dict:
133
+ """Set the light state."""
@@ -0,0 +1,80 @@
1
+ """Module for base light effect module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+ from ..feature import Feature
8
+ from ..module import Module
9
+
10
+
11
+ class LightEffect(Module, ABC):
12
+ """Interface to represent a light effect module."""
13
+
14
+ LIGHT_EFFECTS_OFF = "Off"
15
+
16
+ def _initialize_features(self):
17
+ """Initialize features."""
18
+ device = self._device
19
+ self._add_feature(
20
+ Feature(
21
+ device,
22
+ id="light_effect",
23
+ name="Light effect",
24
+ container=self,
25
+ attribute_getter="effect",
26
+ attribute_setter="set_effect",
27
+ category=Feature.Category.Primary,
28
+ type=Feature.Type.Choice,
29
+ choices_getter="effect_list",
30
+ )
31
+ )
32
+
33
+ @property
34
+ @abstractmethod
35
+ def has_custom_effects(self) -> bool:
36
+ """Return True if the device supports setting custom effects."""
37
+
38
+ @property
39
+ @abstractmethod
40
+ def effect(self) -> str:
41
+ """Return effect state or name."""
42
+
43
+ @property
44
+ @abstractmethod
45
+ def effect_list(self) -> list[str]:
46
+ """Return built-in effects list.
47
+
48
+ Example:
49
+ ['Aurora', 'Bubbling Cauldron', ...]
50
+ """
51
+
52
+ @abstractmethod
53
+ async def set_effect(
54
+ self,
55
+ effect: str,
56
+ *,
57
+ brightness: int | None = None,
58
+ transition: int | None = None,
59
+ ) -> None:
60
+ """Set an effect on the device.
61
+
62
+ If brightness or transition is defined,
63
+ its value will be used instead of the effect-specific default.
64
+
65
+ See :meth:`effect_list` for available effects,
66
+ or use :meth:`set_custom_effect` for custom effects.
67
+
68
+ :param str effect: The effect to set
69
+ :param int brightness: The wanted brightness
70
+ :param int transition: The wanted transition time
71
+ """
72
+
73
+ async def set_custom_effect(
74
+ self,
75
+ effect_dict: dict,
76
+ ) -> None:
77
+ """Set a custom effect on the device.
78
+
79
+ :param str effect_dict: The custom effect dict to set
80
+ """
@@ -0,0 +1,76 @@
1
+ """Module for LightPreset base class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import abstractmethod
6
+ from typing import Sequence
7
+
8
+ from ..feature import Feature
9
+ from ..module import Module
10
+ from .light import LightState
11
+
12
+
13
+ class LightPreset(Module):
14
+ """Base interface for light preset module."""
15
+
16
+ PRESET_NOT_SET = "Not set"
17
+
18
+ def _initialize_features(self):
19
+ """Initialize features."""
20
+ device = self._device
21
+ self._add_feature(
22
+ Feature(
23
+ device,
24
+ id="light_preset",
25
+ name="Light preset",
26
+ container=self,
27
+ attribute_getter="preset",
28
+ attribute_setter="set_preset",
29
+ category=Feature.Category.Config,
30
+ type=Feature.Type.Choice,
31
+ choices_getter="preset_list",
32
+ )
33
+ )
34
+
35
+ @property
36
+ @abstractmethod
37
+ def preset_list(self) -> list[str]:
38
+ """Return list of preset names.
39
+
40
+ Example:
41
+ ['Off', 'Preset 1', 'Preset 2', ...]
42
+ """
43
+
44
+ @property
45
+ @abstractmethod
46
+ def preset_states_list(self) -> Sequence[LightState]:
47
+ """Return list of preset states.
48
+
49
+ Example:
50
+ ['Off', 'Preset 1', 'Preset 2', ...]
51
+ """
52
+
53
+ @property
54
+ @abstractmethod
55
+ def preset(self) -> str:
56
+ """Return current preset name."""
57
+
58
+ @abstractmethod
59
+ async def set_preset(
60
+ self,
61
+ preset_name: str,
62
+ ) -> None:
63
+ """Set a light preset for the device."""
64
+
65
+ @abstractmethod
66
+ async def save_preset(
67
+ self,
68
+ preset_name: str,
69
+ preset_info: LightState,
70
+ ) -> None:
71
+ """Update the preset with *preset_name* with the new *preset_info*."""
72
+
73
+ @property
74
+ @abstractmethod
75
+ def has_save_preset(self) -> bool:
76
+ """Return True if the device supports updating presets."""
kasa/iot/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """Package for supporting legacy kasa devices."""
2
+
3
+ from .iotbulb import IotBulb
4
+ from .iotdevice import IotDevice
5
+ from .iotdimmer import IotDimmer
6
+ from .iotlightstrip import IotLightStrip
7
+ from .iotplug import IotPlug, IotWallSwitch
8
+ from .iotstrip import IotStrip
9
+
10
+ __all__ = [
11
+ "IotDevice",
12
+ "IotPlug",
13
+ "IotBulb",
14
+ "IotStrip",
15
+ "IotDimmer",
16
+ "IotLightStrip",
17
+ "IotWallSwitch",
18
+ ]
@@ -1,6 +1,8 @@
1
1
  """Module for light strip effects (LB*, KL*, KB*)."""
2
2
 
3
- from typing import List, cast
3
+ from __future__ import annotations
4
+
5
+ from typing import cast
4
6
 
5
7
  EFFECT_AURORA = {
6
8
  "custom": 0,
@@ -292,5 +294,5 @@ EFFECTS_LIST_V1 = [
292
294
  EFFECT_VALENTINES,
293
295
  ]
294
296
 
295
- EFFECT_NAMES_V1: List[str] = [cast(str, effect["name"]) for effect in EFFECTS_LIST_V1]
297
+ EFFECT_NAMES_V1: list[str] = [cast(str, effect["name"]) for effect in EFFECTS_LIST_V1]
296
298
  EFFECT_MAPPING_V1 = {effect["name"]: effect for effect in EFFECTS_LIST_V1}