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
@@ -11,43 +11,30 @@ Stroetmann which is licensed under the Apache License, Version 2.0.
11
11
  You may obtain a copy of the license at
12
12
  http://www.apache.org/licenses/LICENSE-2.0
13
13
  """
14
+
15
+ from __future__ import annotations
16
+
14
17
  import collections.abc
15
18
  import functools
16
19
  import inspect
17
20
  import logging
18
- from dataclasses import dataclass
19
21
  from datetime import datetime, timedelta
20
- from typing import Any, Dict, List, Optional, Set
21
-
22
- from .credentials import Credentials
23
- from .device_type import DeviceType
24
- from .deviceconfig import DeviceConfig
25
- from .emeterstatus import EmeterStatus
26
- from .exceptions import SmartDeviceException
27
- from .iotprotocol import IotProtocol
28
- from .modules import Emeter, Module
29
- from .protocol import BaseProtocol
30
- from .xortransport import XorTransport
22
+ from typing import TYPE_CHECKING, Any, Mapping, Sequence, cast
23
+
24
+ from ..device import Device, WifiNetwork
25
+ from ..deviceconfig import DeviceConfig
26
+ from ..emeterstatus import EmeterStatus
27
+ from ..exceptions import KasaException
28
+ from ..feature import Feature
29
+ from ..module import Module
30
+ from ..modulemapping import ModuleMapping, ModuleName
31
+ from ..protocol import BaseProtocol
32
+ from .iotmodule import IotModule
33
+ from .modules import Emeter
31
34
 
32
35
  _LOGGER = logging.getLogger(__name__)
33
36
 
34
37
 
35
- @dataclass
36
- class WifiNetwork:
37
- """Wifi network container."""
38
-
39
- ssid: str
40
- key_type: int
41
- # These are available only on softaponboarding
42
- cipher_type: Optional[int] = None
43
- bssid: Optional[str] = None
44
- channel: Optional[int] = None
45
- rssi: Optional[int] = None
46
-
47
- # For SMART devices
48
- signal_level: Optional[int] = None
49
-
50
-
51
38
  def merge(d, u):
52
39
  """Update dict recursively."""
53
40
  for k, v in u.items():
@@ -66,9 +53,7 @@ def requires_update(f):
66
53
  async def wrapped(*args, **kwargs):
67
54
  self = args[0]
68
55
  if self._last_update is None and f.__name__ not in self._sys_info:
69
- raise SmartDeviceException(
70
- "You need to await update() to access the data"
71
- )
56
+ raise KasaException("You need to await update() to access the data")
72
57
  return await f(*args, **kwargs)
73
58
 
74
59
  else:
@@ -77,9 +62,7 @@ def requires_update(f):
77
62
  def wrapped(*args, **kwargs):
78
63
  self = args[0]
79
64
  if self._last_update is None and f.__name__ not in self._sys_info:
80
- raise SmartDeviceException(
81
- "You need to await update() to access the data"
82
- )
65
+ raise KasaException("You need to await update() to access the data")
83
66
  return f(*args, **kwargs)
84
67
 
85
68
  f.requires_update = True
@@ -87,22 +70,22 @@ def requires_update(f):
87
70
 
88
71
 
89
72
  @functools.lru_cache
90
- def _parse_features(features: str) -> Set[str]:
73
+ def _parse_features(features: str) -> set[str]:
91
74
  """Parse features string."""
92
75
  return set(features.split(":"))
93
76
 
94
77
 
95
- class SmartDevice:
78
+ class IotDevice(Device):
96
79
  """Base class for all supported device types.
97
80
 
98
81
  You don't usually want to initialize this class manually,
99
82
  but either use :class:`Discover` class, or use one of the subclasses:
100
83
 
101
- * :class:`SmartPlug`
102
- * :class:`SmartBulb`
103
- * :class:`SmartStrip`
104
- * :class:`SmartDimmer`
105
- * :class:`SmartLightStrip`
84
+ * :class:`IotPlug`
85
+ * :class:`IotBulb`
86
+ * :class:`IotStrip`
87
+ * :class:`IotDimmer`
88
+ * :class:`IotLightStrip`
106
89
 
107
90
  To initialize, you have to await :func:`update()` at least once.
108
91
  This will allow accessing the properties using the exposed properties.
@@ -110,12 +93,13 @@ class SmartDevice:
110
93
  All changes to the device are done using awaitable methods,
111
94
  which will not change the cached values, but you must await update() separately.
112
95
 
113
- Errors reported by the device are raised as SmartDeviceExceptions,
96
+ Errors reported by the device are raised as
97
+ :class:`KasaException <kasa.exceptions.KasaException>`,
114
98
  and should be handled by the user of the library.
115
99
 
116
100
  Examples:
117
101
  >>> import asyncio
118
- >>> dev = SmartDevice("127.0.0.1")
102
+ >>> dev = IotDevice("127.0.0.1")
119
103
  >>> asyncio.run(dev.update())
120
104
 
121
105
  All devices provide several informational properties:
@@ -197,74 +181,43 @@ class SmartDevice:
197
181
  self,
198
182
  host: str,
199
183
  *,
200
- config: Optional[DeviceConfig] = None,
201
- protocol: Optional[BaseProtocol] = None,
184
+ config: DeviceConfig | None = None,
185
+ protocol: BaseProtocol | None = None,
202
186
  ) -> None:
203
- """Create a new SmartDevice instance.
204
-
205
- :param str host: host name or ip address on which the device listens
206
- """
207
- if config and protocol:
208
- protocol._transport._config = config
209
- self.protocol: BaseProtocol = protocol or IotProtocol(
210
- transport=XorTransport(config=config or DeviceConfig(host=host)),
211
- )
212
- _LOGGER.debug("Initializing %s of type %s", self.host, type(self))
213
- self._device_type = DeviceType.Unknown
214
- # TODO: typing Any is just as using Optional[Dict] would require separate
215
- # checks in accessors. the @updated_required decorator does not ensure
216
- # mypy that these are not accessed incorrectly.
217
- self._last_update: Any = None
218
- self._discovery_info: Optional[Dict[str, Any]] = None
187
+ """Create a new IotDevice instance."""
188
+ super().__init__(host=host, config=config, protocol=protocol)
219
189
 
220
190
  self._sys_info: Any = None # TODO: this is here to avoid changing tests
221
- self._features: Set[str] = set()
222
- self.modules: Dict[str, Any] = {}
223
-
224
- self.children: List["SmartDevice"] = []
225
-
226
- @property
227
- def host(self) -> str:
228
- """The device host."""
229
- return self.protocol._transport._host
230
-
231
- @host.setter
232
- def host(self, value):
233
- """Set the device host.
234
-
235
- Generally used by discovery to set the hostname after ip discovery.
236
- """
237
- self.protocol._transport._host = value
238
- self.protocol._transport._config.host = value
239
-
240
- @property
241
- def port(self) -> int:
242
- """The device port."""
243
- return self.protocol._transport._port
191
+ self._supported_modules: dict[str, IotModule] | None = None
192
+ self._legacy_features: set[str] = set()
193
+ self._children: Mapping[str, IotDevice] = {}
194
+ self._modules: dict[str | ModuleName[Module], IotModule] = {}
244
195
 
245
196
  @property
246
- def credentials(self) -> Optional[Credentials]:
247
- """The device credentials."""
248
- return self.protocol._transport._credentials
197
+ def children(self) -> Sequence[IotDevice]:
198
+ """Return list of children."""
199
+ return list(self._children.values())
249
200
 
250
201
  @property
251
- def credentials_hash(self) -> Optional[str]:
252
- """The protocol specific hash of the credentials the device is using."""
253
- return self.protocol._transport.credentials_hash
202
+ def modules(self) -> ModuleMapping[IotModule]:
203
+ """Return the device modules."""
204
+ if TYPE_CHECKING:
205
+ return cast(ModuleMapping[IotModule], self._modules)
206
+ return self._modules
254
207
 
255
- def add_module(self, name: str, module: Module):
208
+ def add_module(self, name: str | ModuleName[Module], module: IotModule):
256
209
  """Register a module."""
257
210
  if name in self.modules:
258
211
  _LOGGER.debug("Module %s already registered, ignoring..." % name)
259
212
  return
260
213
 
261
214
  _LOGGER.debug("Adding module %s", module)
262
- self.modules[name] = module
215
+ self._modules[name] = module
263
216
 
264
217
  def _create_request(
265
- self, target: str, cmd: str, arg: Optional[Dict] = None, child_ids=None
218
+ self, target: str, cmd: str, arg: dict | None = None, child_ids=None
266
219
  ):
267
- request: Dict[str, Any] = {target: {cmd: arg}}
220
+ request: dict[str, Any] = {target: {cmd: arg}}
268
221
  if child_ids is not None:
269
222
  request = {"context": {"child_ids": child_ids}, target: {cmd: arg}}
270
223
 
@@ -273,12 +226,12 @@ class SmartDevice:
273
226
  def _verify_emeter(self) -> None:
274
227
  """Raise an exception if there is no emeter."""
275
228
  if not self.has_emeter:
276
- raise SmartDeviceException("Device has no emeter")
229
+ raise KasaException("Device has no emeter")
277
230
  if self.emeter_type not in self._last_update:
278
- raise SmartDeviceException("update() required prior accessing emeter")
231
+ raise KasaException("update() required prior accessing emeter")
279
232
 
280
233
  async def _query_helper(
281
- self, target: str, cmd: str, arg: Optional[Dict] = None, child_ids=None
234
+ self, target: str, cmd: str, arg: dict | None = None, child_ids=None
282
235
  ) -> Any:
283
236
  """Query device, return results or raise an exception.
284
237
 
@@ -291,22 +244,22 @@ class SmartDevice:
291
244
  request = self._create_request(target, cmd, arg, child_ids)
292
245
 
293
246
  try:
294
- response = await self.protocol.query(request=request)
247
+ response = await self._raw_query(request=request)
295
248
  except Exception as ex:
296
- raise SmartDeviceException(f"Communication error on {target}:{cmd}") from ex
249
+ raise KasaException(f"Communication error on {target}:{cmd}") from ex
297
250
 
298
251
  if target not in response:
299
- raise SmartDeviceException(f"No required {target} in response: {response}")
252
+ raise KasaException(f"No required {target} in response: {response}")
300
253
 
301
254
  result = response[target]
302
255
  if "err_code" in result and result["err_code"] != 0:
303
- raise SmartDeviceException(f"Error on {target}.{cmd}: {result}")
256
+ raise KasaException(f"Error on {target}.{cmd}: {result}")
304
257
 
305
258
  if cmd not in result:
306
- raise SmartDeviceException(f"No command in response: {response}")
259
+ raise KasaException(f"No command in response: {response}")
307
260
  result = result[cmd]
308
261
  if "err_code" in result and result["err_code"] != 0:
309
- raise SmartDeviceException(f"Error on {target} {cmd}: {result}")
262
+ raise KasaException(f"Error on {target} {cmd}: {result}")
310
263
 
311
264
  if "err_code" in result:
312
265
  del result["err_code"]
@@ -315,25 +268,25 @@ class SmartDevice:
315
268
 
316
269
  @property # type: ignore
317
270
  @requires_update
318
- def features(self) -> Set[str]:
271
+ def features(self) -> dict[str, Feature]:
319
272
  """Return a set of features that the device supports."""
320
273
  return self._features
321
274
 
322
275
  @property # type: ignore
323
276
  @requires_update
324
- def supported_modules(self) -> List[str]:
277
+ def supported_modules(self) -> list[str | ModuleName[Module]]:
325
278
  """Return a set of modules supported by the device."""
326
279
  # TODO: this should rather be called `features`, but we don't want to break
327
280
  # the API now. Maybe just deprecate it and point the users to use this?
328
- return list(self.modules.keys())
281
+ return list(self._modules.keys())
329
282
 
330
283
  @property # type: ignore
331
284
  @requires_update
332
285
  def has_emeter(self) -> bool:
333
286
  """Return True if device has an energy meter."""
334
- return "ENE" in self.features
287
+ return "ENE" in self._legacy_features
335
288
 
336
- async def get_sys_info(self) -> Dict[str, Any]:
289
+ async def get_sys_info(self) -> dict[str, Any]:
337
290
  """Retrieve system information."""
338
291
  return await self._query_helper("system", "get_sysinfo")
339
292
 
@@ -354,8 +307,47 @@ class SmartDevice:
354
307
  self._last_update = response
355
308
  self._set_sys_info(response["system"]["get_sysinfo"])
356
309
 
310
+ if not self._modules:
311
+ await self._initialize_modules()
312
+
357
313
  await self._modular_update(req)
314
+
358
315
  self._set_sys_info(self._last_update["system"]["get_sysinfo"])
316
+ for module in self._modules.values():
317
+ module._post_update_hook()
318
+
319
+ if not self._features:
320
+ await self._initialize_features()
321
+
322
+ async def _initialize_modules(self):
323
+ """Initialize modules not added in init."""
324
+
325
+ async def _initialize_features(self):
326
+ self._add_feature(
327
+ Feature(
328
+ device=self,
329
+ id="rssi",
330
+ name="RSSI",
331
+ attribute_getter="rssi",
332
+ icon="mdi:signal",
333
+ category=Feature.Category.Debug,
334
+ )
335
+ )
336
+ if "on_time" in self._sys_info:
337
+ self._add_feature(
338
+ Feature(
339
+ device=self,
340
+ id="on_since",
341
+ name="On since",
342
+ attribute_getter="on_since",
343
+ icon="mdi:clock",
344
+ )
345
+ )
346
+
347
+ for module in self._modules.values():
348
+ module._initialize_features()
349
+ for module_feat in module._module_features.values():
350
+ self._add_feature(module_feat)
359
351
 
360
352
  async def _modular_update(self, req: dict) -> None:
361
353
  """Execute an update query."""
@@ -363,11 +355,21 @@ class SmartDevice:
363
355
  _LOGGER.debug(
364
356
  "The device has emeter, querying its information along sysinfo"
365
357
  )
366
- self.add_module("emeter", Emeter(self, self.emeter_type))
358
+ self.add_module(Module.IotEmeter, Emeter(self, self.emeter_type))
359
+
360
+ # TODO: perhaps modules should not have unsupported modules,
361
+ # making separate handling for this unnecessary
362
+ if self._supported_modules is None:
363
+ supported = {}
364
+ for module in self._modules.values():
365
+ if module.is_supported:
366
+ supported[module._module] = module
367
+
368
+ self._supported_modules = supported
367
369
 
368
370
  request_list = []
369
371
  est_response_size = 1024 if "system" in req else 0
370
- for module in self.modules.values():
372
+ for module in self._modules.values():
371
373
  if not module.is_supported:
372
374
  _LOGGER.debug("Module %s not supported, skipping" % module)
373
375
  continue
@@ -391,12 +393,12 @@ class SmartDevice:
391
393
  # responses on top of it so we remember
392
394
  # which modules are not supported, otherwise
393
395
  # every other update will query for them
394
- update: Dict = self._last_update.copy() if self._last_update else {}
396
+ update: dict = self._last_update.copy() if self._last_update else {}
395
397
  for response in responses:
396
398
  update = {**update, **response}
397
399
  self._last_update = update
398
400
 
399
- def update_from_discover_info(self, info: Dict[str, Any]) -> None:
401
+ def update_from_discover_info(self, info: dict[str, Any]) -> None:
400
402
  """Update state from info from the discover call."""
401
403
  self._discovery_info = info
402
404
  if "system" in info and (sys_info := info["system"].get("get_sysinfo")):
@@ -408,17 +410,15 @@ class SmartDevice:
408
410
  # by the requires_update decorator
409
411
  self._set_sys_info(info)
410
412
 
411
- def _set_sys_info(self, sys_info: Dict[str, Any]) -> None:
413
+ def _set_sys_info(self, sys_info: dict[str, Any]) -> None:
412
414
  """Set sys_info."""
413
415
  self._sys_info = sys_info
414
416
  if features := sys_info.get("feature"):
415
- self._features = _parse_features(features)
416
- else:
417
- self._features = set()
417
+ self._legacy_features = _parse_features(features)
418
418
 
419
419
  @property # type: ignore
420
420
  @requires_update
421
- def sys_info(self) -> Dict[str, Any]:
421
+ def sys_info(self) -> dict[str, Any]:
422
422
  """
423
423
  Return system information.
424
424
 
@@ -434,17 +434,8 @@ class SmartDevice:
434
434
  sys_info = self._sys_info
435
435
  return str(sys_info["model"])
436
436
 
437
- @property
438
- def has_children(self) -> bool:
439
- """Return true if the device has children devices."""
440
- # Ideally we would check for the 'child_num' key in sys_info,
441
- # but devices that speak klap do not populate this key via
442
- # update_from_discover_info so we check for the devices
443
- # we know have children instead.
444
- return self.is_strip
445
-
446
437
  @property # type: ignore
447
- def alias(self) -> Optional[str]:
438
+ def alias(self) -> str | None:
448
439
  """Return device name (alias)."""
449
440
  sys_info = self._sys_info
450
441
  return sys_info.get("alias") if sys_info else None
@@ -453,35 +444,35 @@ class SmartDevice:
453
444
  """Set the device name (alias)."""
454
445
  return await self._query_helper("system", "set_dev_alias", {"alias": alias})
455
446
 
456
- @property # type: ignore
447
+ @property
457
448
  @requires_update
458
449
  def time(self) -> datetime:
459
450
  """Return current time from the device."""
460
- return self.modules["time"].time
451
+ return self.modules[Module.IotTime].time
461
452
 
462
- @property # type: ignore
453
+ @property
463
454
  @requires_update
464
- def timezone(self) -> Dict:
455
+ def timezone(self) -> dict:
465
456
  """Return the current timezone."""
466
- return self.modules["time"].timezone
457
+ return self.modules[Module.IotTime].timezone
467
458
 
468
- async def get_time(self) -> Optional[datetime]:
459
+ async def get_time(self) -> datetime | None:
469
460
  """Return current time from the device, if available."""
470
461
  _LOGGER.warning(
471
462
  "Use `time` property instead, this call will be removed in the future."
472
463
  )
473
- return await self.modules["time"].get_time()
464
+ return await self.modules[Module.IotTime].get_time()
474
465
 
475
- async def get_timezone(self) -> Dict:
466
+ async def get_timezone(self) -> dict:
476
467
  """Return timezone information."""
477
468
  _LOGGER.warning(
478
469
  "Use `timezone` property instead, this call will be removed in the future."
479
470
  )
480
- return await self.modules["time"].get_timezone()
471
+ return await self.modules[Module.IotTime].get_timezone()
481
472
 
482
473
  @property # type: ignore
483
474
  @requires_update
484
- def hw_info(self) -> Dict:
475
+ def hw_info(self) -> dict:
485
476
  """Return hardware information.
486
477
 
487
478
  This returns just a selection of sysinfo keys that are related to hardware.
@@ -503,7 +494,7 @@ class SmartDevice:
503
494
 
504
495
  @property # type: ignore
505
496
  @requires_update
506
- def location(self) -> Dict:
497
+ def location(self) -> dict:
507
498
  """Return geographical location."""
508
499
  sys_info = self._sys_info
509
500
  loc = {"latitude": None, "longitude": None}
@@ -521,7 +512,7 @@ class SmartDevice:
521
512
 
522
513
  @property # type: ignore
523
514
  @requires_update
524
- def rssi(self) -> Optional[int]:
515
+ def rssi(self) -> int | None:
525
516
  """Return WiFi signal strength (rssi)."""
526
517
  rssi = self._sys_info.get("rssi")
527
518
  return None if rssi is None else int(rssi)
@@ -536,7 +527,7 @@ class SmartDevice:
536
527
  sys_info = self._sys_info
537
528
  mac = sys_info.get("mac", sys_info.get("mic_mac"))
538
529
  if not mac:
539
- raise SmartDeviceException(
530
+ raise KasaException(
540
531
  "Unknown mac, please submit a bug report with sys_info output."
541
532
  )
542
533
  mac = mac.replace("-", ":")
@@ -553,35 +544,35 @@ class SmartDevice:
553
544
  """
554
545
  return await self._query_helper("system", "set_mac_addr", {"mac": mac})
555
546
 
556
- @property # type: ignore
547
+ @property
557
548
  @requires_update
558
549
  def emeter_realtime(self) -> EmeterStatus:
559
550
  """Return current energy readings."""
560
551
  self._verify_emeter()
561
- return EmeterStatus(self.modules["emeter"].realtime)
552
+ return EmeterStatus(self.modules[Module.IotEmeter].realtime)
562
553
 
563
554
  async def get_emeter_realtime(self) -> EmeterStatus:
564
555
  """Retrieve current energy readings."""
565
556
  self._verify_emeter()
566
- return EmeterStatus(await self.modules["emeter"].get_realtime())
557
+ return EmeterStatus(await self.modules[Module.IotEmeter].get_realtime())
567
558
 
568
- @property # type: ignore
559
+ @property
569
560
  @requires_update
570
- def emeter_today(self) -> Optional[float]:
561
+ def emeter_today(self) -> float | None:
571
562
  """Return today's energy consumption in kWh."""
572
563
  self._verify_emeter()
573
- return self.modules["emeter"].emeter_today
564
+ return self.modules[Module.IotEmeter].emeter_today
574
565
 
575
- @property # type: ignore
566
+ @property
576
567
  @requires_update
577
- def emeter_this_month(self) -> Optional[float]:
568
+ def emeter_this_month(self) -> float | None:
578
569
  """Return this month's energy consumption in kWh."""
579
570
  self._verify_emeter()
580
- return self.modules["emeter"].emeter_this_month
571
+ return self.modules[Module.IotEmeter].emeter_this_month
581
572
 
582
573
  async def get_emeter_daily(
583
- self, year: Optional[int] = None, month: Optional[int] = None, kwh: bool = True
584
- ) -> Dict:
574
+ self, year: int | None = None, month: int | None = None, kwh: bool = True
575
+ ) -> dict:
585
576
  """Retrieve daily statistics for a given month.
586
577
 
587
578
  :param year: year for which to retrieve statistics (default: this year)
@@ -591,12 +582,14 @@ class SmartDevice:
591
582
  :return: mapping of day of month to value
592
583
  """
593
584
  self._verify_emeter()
594
- return await self.modules["emeter"].get_daystat(year=year, month=month, kwh=kwh)
585
+ return await self.modules[Module.IotEmeter].get_daystat(
586
+ year=year, month=month, kwh=kwh
587
+ )
595
588
 
596
589
  @requires_update
597
590
  async def get_emeter_monthly(
598
- self, year: Optional[int] = None, kwh: bool = True
599
- ) -> Dict:
591
+ self, year: int | None = None, kwh: bool = True
592
+ ) -> dict:
600
593
  """Retrieve monthly statistics for a given year.
601
594
 
602
595
  :param year: year for which to retrieve statistics (default: this year)
@@ -604,13 +597,13 @@ class SmartDevice:
604
597
  :return: dict: mapping of month to value
605
598
  """
606
599
  self._verify_emeter()
607
- return await self.modules["emeter"].get_monthstat(year=year, kwh=kwh)
600
+ return await self.modules[Module.IotEmeter].get_monthstat(year=year, kwh=kwh)
608
601
 
609
602
  @requires_update
610
- async def erase_emeter_stats(self) -> Dict:
603
+ async def erase_emeter_stats(self) -> dict:
611
604
  """Erase energy meter statistics."""
612
605
  self._verify_emeter()
613
- return await self.modules["emeter"].erase_stats()
606
+ return await self.modules[Module.IotEmeter].erase_stats()
614
607
 
615
608
  @requires_update
616
609
  async def current_consumption(self) -> float:
@@ -627,17 +620,11 @@ class SmartDevice:
627
620
  """
628
621
  await self._query_helper("system", "reboot", {"delay": delay})
629
622
 
630
- async def turn_off(self, **kwargs) -> Dict:
623
+ async def turn_off(self, **kwargs) -> dict:
631
624
  """Turn off the device."""
632
625
  raise NotImplementedError("Device subclass needs to implement this.")
633
626
 
634
- @property # type: ignore
635
- @requires_update
636
- def is_off(self) -> bool:
637
- """Return True if device is off."""
638
- return not self.is_on
639
-
640
- async def turn_on(self, **kwargs) -> Dict:
627
+ async def turn_on(self, **kwargs) -> dict | None:
641
628
  """Turn device on."""
642
629
  raise NotImplementedError("Device subclass needs to implement this.")
643
630
 
@@ -649,7 +636,7 @@ class SmartDevice:
649
636
 
650
637
  @property # type: ignore
651
638
  @requires_update
652
- def on_since(self) -> Optional[datetime]:
639
+ def on_since(self) -> datetime | None:
653
640
  """Return pretty-printed on-time, or None if not available."""
654
641
  if "on_time" not in self._sys_info:
655
642
  return None
@@ -661,12 +648,6 @@ class SmartDevice:
661
648
 
662
649
  return datetime.now().replace(microsecond=0) - timedelta(seconds=on_time)
663
650
 
664
- @property # type: ignore
665
- @requires_update
666
- def state_information(self) -> Dict[str, Any]:
667
- """Return device-type specific, end-user friendly state information."""
668
- raise NotImplementedError("Device subclass needs to implement this.")
669
-
670
651
  @property # type: ignore
671
652
  @requires_update
672
653
  def device_id(self) -> str:
@@ -677,7 +658,7 @@ class SmartDevice:
677
658
  """
678
659
  return self.mac
679
660
 
680
- async def wifi_scan(self) -> List[WifiNetwork]: # noqa: D202
661
+ async def wifi_scan(self) -> list[WifiNetwork]: # noqa: D202
681
662
  """Scan for available wifi networks."""
682
663
 
683
664
  async def _scan(target):
@@ -685,14 +666,14 @@ class SmartDevice:
685
666
 
686
667
  try:
687
668
  info = await _scan("netif")
688
- except SmartDeviceException as ex:
669
+ except KasaException as ex:
689
670
  _LOGGER.debug(
690
671
  "Unable to scan using 'netif', retrying with 'softaponboarding': %s", ex
691
672
  )
692
673
  info = await _scan("smartlife.iot.common.softaponboarding")
693
674
 
694
675
  if "ap_list" not in info:
695
- raise SmartDeviceException("Invalid response for wifi scan: %s" % info)
676
+ raise KasaException("Invalid response for wifi scan: %s" % info)
696
677
 
697
678
  return [WifiNetwork(**x) for x in info["ap_list"]]
698
679
 
@@ -708,83 +689,17 @@ class SmartDevice:
708
689
  payload = {"ssid": ssid, "password": password, "key_type": int(keytype)}
709
690
  try:
710
691
  return await _join("netif", payload)
711
- except SmartDeviceException as ex:
692
+ except KasaException as ex:
712
693
  _LOGGER.debug(
713
694
  "Unable to join using 'netif', retrying with 'softaponboarding': %s", ex
714
695
  )
715
696
  return await _join("smartlife.iot.common.softaponboarding", payload)
716
697
 
717
- def get_plug_by_name(self, name: str) -> "SmartDevice":
718
- """Return child device for the given name."""
719
- for p in self.children:
720
- if p.alias == name:
721
- return p
722
-
723
- raise SmartDeviceException(f"Device has no child with {name}")
724
-
725
- def get_plug_by_index(self, index: int) -> "SmartDevice":
726
- """Return child device for the given index."""
727
- if index + 1 > len(self.children) or index < 0:
728
- raise SmartDeviceException(
729
- f"Invalid index {index}, device has {len(self.children)} plugs"
730
- )
731
- return self.children[index]
732
-
733
698
  @property
734
699
  def max_device_response_size(self) -> int:
735
700
  """Returns the maximum response size the device can safely construct."""
736
701
  return 16 * 1024
737
702
 
738
- @property
739
- def device_type(self) -> DeviceType:
740
- """Return the device type."""
741
- return self._device_type
742
-
743
- @property
744
- def is_bulb(self) -> bool:
745
- """Return True if the device is a bulb."""
746
- return self._device_type == DeviceType.Bulb
747
-
748
- @property
749
- def is_light_strip(self) -> bool:
750
- """Return True if the device is a led strip."""
751
- return self._device_type == DeviceType.LightStrip
752
-
753
- @property
754
- def is_plug(self) -> bool:
755
- """Return True if the device is a plug."""
756
- return self._device_type == DeviceType.Plug
757
-
758
- @property
759
- def is_strip(self) -> bool:
760
- """Return True if the device is a strip."""
761
- return self._device_type == DeviceType.Strip
762
-
763
- @property
764
- def is_strip_socket(self) -> bool:
765
- """Return True if the device is a strip socket."""
766
- return self._device_type == DeviceType.StripSocket
767
-
768
- @property
769
- def is_dimmer(self) -> bool:
770
- """Return True if the device is a dimmer."""
771
- return self._device_type == DeviceType.Dimmer
772
-
773
- @property
774
- def is_dimmable(self) -> bool:
775
- """Return True if the device is dimmable."""
776
- return False
777
-
778
- @property
779
- def is_variable_color_temp(self) -> bool:
780
- """Return True if the device supports color temperature."""
781
- return False
782
-
783
- @property
784
- def is_color(self) -> bool:
785
- """Return True if the device supports color changes."""
786
- return False
787
-
788
703
  @property
789
704
  def internal_state(self) -> Any:
790
705
  """Return the internal state of the instance.
@@ -793,47 +708,3 @@ class SmartDevice:
793
708
  This should only be used for debugging purposes.
794
709
  """
795
710
  return self._last_update or self._discovery_info
796
-
797
- def __repr__(self):
798
- if self._last_update is None:
799
- return f"<{self._device_type} at {self.host} - update() needed>"
800
- return (
801
- f"<{self._device_type} model {self.model} at {self.host}"
802
- f" ({self.alias}), is_on: {self.is_on}"
803
- f" - dev specific: {self.state_information}>"
804
- )
805
-
806
- @property
807
- def config(self) -> DeviceConfig:
808
- """Return the device configuration."""
809
- return self.protocol.config
810
-
811
- async def disconnect(self):
812
- """Disconnect and close any underlying connection resources."""
813
- await self.protocol.close()
814
-
815
- @staticmethod
816
- async def connect(
817
- *,
818
- host: Optional[str] = None,
819
- config: Optional[DeviceConfig] = None,
820
- ) -> "SmartDevice":
821
- """Connect to a single device by the given hostname or device configuration.
822
-
823
- This method avoids the UDP based discovery process and
824
- will connect directly to the device.
825
-
826
- It is generally preferred to avoid :func:`discover_single()` and
827
- use this function instead as it should perform better when
828
- the WiFi network is congested or the device is not responding
829
- to discovery requests.
830
-
831
- :param host: Hostname of device to query
832
- :param config: Connection parameters to ensure the correct protocol
833
- and connection options are used.
834
- :rtype: SmartDevice
835
- :return: Object for querying/controlling found device.
836
- """
837
- from .device_factory import connect # pylint: disable=import-outside-toplevel
838
-
839
- return await connect(host=host, config=config) # type: ignore[arg-type]