python-kasa 0.6.2.1__py3-none-any.whl → 0.7.0.dev1__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 +90 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +414 -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 +138 -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} +103 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +176 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +45 -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 +263 -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 +166 -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 +116 -86
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +242 -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 +42 -33
  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.dev1.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev1.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.dev1.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.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
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] = {}
239
195
 
240
196
  @property
241
- def port(self) -> int:
242
- """The device port."""
243
- return self.protocol._transport._port
197
+ def children(self) -> Sequence[IotDevice]:
198
+ """Return list of children."""
199
+ return list(self._children.values())
244
200
 
245
201
  @property
246
- def credentials(self) -> Optional[Credentials]:
247
- """The device credentials."""
248
- return self.protocol._transport._credentials
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
249
207
 
250
- @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
254
-
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,59 @@ 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
+ """Initialize common features."""
327
+ self._add_feature(
328
+ Feature(
329
+ self,
330
+ id="state",
331
+ name="State",
332
+ attribute_getter="is_on",
333
+ attribute_setter="set_state",
334
+ type=Feature.Type.Switch,
335
+ category=Feature.Category.Primary,
336
+ )
337
+ )
338
+ self._add_feature(
339
+ Feature(
340
+ device=self,
341
+ id="rssi",
342
+ name="RSSI",
343
+ attribute_getter="rssi",
344
+ icon="mdi:signal",
345
+ category=Feature.Category.Debug,
346
+ )
347
+ )
348
+ if "on_time" in self._sys_info:
349
+ self._add_feature(
350
+ Feature(
351
+ device=self,
352
+ id="on_since",
353
+ name="On since",
354
+ attribute_getter="on_since",
355
+ icon="mdi:clock",
356
+ )
357
+ )
358
+
359
+ for module in self._modules.values():
360
+ module._initialize_features()
361
+ for module_feat in module._module_features.values():
362
+ self._add_feature(module_feat)
359
363
 
360
364
  async def _modular_update(self, req: dict) -> None:
361
365
  """Execute an update query."""
@@ -363,11 +367,21 @@ class SmartDevice:
363
367
  _LOGGER.debug(
364
368
  "The device has emeter, querying its information along sysinfo"
365
369
  )
366
- self.add_module("emeter", Emeter(self, self.emeter_type))
370
+ self.add_module(Module.IotEmeter, Emeter(self, self.emeter_type))
371
+
372
+ # TODO: perhaps modules should not have unsupported modules,
373
+ # making separate handling for this unnecessary
374
+ if self._supported_modules is None:
375
+ supported = {}
376
+ for module in self._modules.values():
377
+ if module.is_supported:
378
+ supported[module._module] = module
379
+
380
+ self._supported_modules = supported
367
381
 
368
382
  request_list = []
369
383
  est_response_size = 1024 if "system" in req else 0
370
- for module in self.modules.values():
384
+ for module in self._modules.values():
371
385
  if not module.is_supported:
372
386
  _LOGGER.debug("Module %s not supported, skipping" % module)
373
387
  continue
@@ -391,12 +405,12 @@ class SmartDevice:
391
405
  # responses on top of it so we remember
392
406
  # which modules are not supported, otherwise
393
407
  # every other update will query for them
394
- update: Dict = self._last_update.copy() if self._last_update else {}
408
+ update: dict = self._last_update.copy() if self._last_update else {}
395
409
  for response in responses:
396
410
  update = {**update, **response}
397
411
  self._last_update = update
398
412
 
399
- def update_from_discover_info(self, info: Dict[str, Any]) -> None:
413
+ def update_from_discover_info(self, info: dict[str, Any]) -> None:
400
414
  """Update state from info from the discover call."""
401
415
  self._discovery_info = info
402
416
  if "system" in info and (sys_info := info["system"].get("get_sysinfo")):
@@ -408,17 +422,15 @@ class SmartDevice:
408
422
  # by the requires_update decorator
409
423
  self._set_sys_info(info)
410
424
 
411
- def _set_sys_info(self, sys_info: Dict[str, Any]) -> None:
425
+ def _set_sys_info(self, sys_info: dict[str, Any]) -> None:
412
426
  """Set sys_info."""
413
427
  self._sys_info = sys_info
414
428
  if features := sys_info.get("feature"):
415
- self._features = _parse_features(features)
416
- else:
417
- self._features = set()
429
+ self._legacy_features = _parse_features(features)
418
430
 
419
431
  @property # type: ignore
420
432
  @requires_update
421
- def sys_info(self) -> Dict[str, Any]:
433
+ def sys_info(self) -> dict[str, Any]:
422
434
  """
423
435
  Return system information.
424
436
 
@@ -434,17 +446,8 @@ class SmartDevice:
434
446
  sys_info = self._sys_info
435
447
  return str(sys_info["model"])
436
448
 
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
449
  @property # type: ignore
447
- def alias(self) -> Optional[str]:
450
+ def alias(self) -> str | None:
448
451
  """Return device name (alias)."""
449
452
  sys_info = self._sys_info
450
453
  return sys_info.get("alias") if sys_info else None
@@ -453,35 +456,35 @@ class SmartDevice:
453
456
  """Set the device name (alias)."""
454
457
  return await self._query_helper("system", "set_dev_alias", {"alias": alias})
455
458
 
456
- @property # type: ignore
459
+ @property
457
460
  @requires_update
458
461
  def time(self) -> datetime:
459
462
  """Return current time from the device."""
460
- return self.modules["time"].time
463
+ return self.modules[Module.IotTime].time
461
464
 
462
- @property # type: ignore
465
+ @property
463
466
  @requires_update
464
- def timezone(self) -> Dict:
467
+ def timezone(self) -> dict:
465
468
  """Return the current timezone."""
466
- return self.modules["time"].timezone
469
+ return self.modules[Module.IotTime].timezone
467
470
 
468
- async def get_time(self) -> Optional[datetime]:
471
+ async def get_time(self) -> datetime | None:
469
472
  """Return current time from the device, if available."""
470
473
  _LOGGER.warning(
471
474
  "Use `time` property instead, this call will be removed in the future."
472
475
  )
473
- return await self.modules["time"].get_time()
476
+ return await self.modules[Module.IotTime].get_time()
474
477
 
475
- async def get_timezone(self) -> Dict:
478
+ async def get_timezone(self) -> dict:
476
479
  """Return timezone information."""
477
480
  _LOGGER.warning(
478
481
  "Use `timezone` property instead, this call will be removed in the future."
479
482
  )
480
- return await self.modules["time"].get_timezone()
483
+ return await self.modules[Module.IotTime].get_timezone()
481
484
 
482
485
  @property # type: ignore
483
486
  @requires_update
484
- def hw_info(self) -> Dict:
487
+ def hw_info(self) -> dict:
485
488
  """Return hardware information.
486
489
 
487
490
  This returns just a selection of sysinfo keys that are related to hardware.
@@ -503,7 +506,7 @@ class SmartDevice:
503
506
 
504
507
  @property # type: ignore
505
508
  @requires_update
506
- def location(self) -> Dict:
509
+ def location(self) -> dict:
507
510
  """Return geographical location."""
508
511
  sys_info = self._sys_info
509
512
  loc = {"latitude": None, "longitude": None}
@@ -521,7 +524,7 @@ class SmartDevice:
521
524
 
522
525
  @property # type: ignore
523
526
  @requires_update
524
- def rssi(self) -> Optional[int]:
527
+ def rssi(self) -> int | None:
525
528
  """Return WiFi signal strength (rssi)."""
526
529
  rssi = self._sys_info.get("rssi")
527
530
  return None if rssi is None else int(rssi)
@@ -536,7 +539,7 @@ class SmartDevice:
536
539
  sys_info = self._sys_info
537
540
  mac = sys_info.get("mac", sys_info.get("mic_mac"))
538
541
  if not mac:
539
- raise SmartDeviceException(
542
+ raise KasaException(
540
543
  "Unknown mac, please submit a bug report with sys_info output."
541
544
  )
542
545
  mac = mac.replace("-", ":")
@@ -553,35 +556,35 @@ class SmartDevice:
553
556
  """
554
557
  return await self._query_helper("system", "set_mac_addr", {"mac": mac})
555
558
 
556
- @property # type: ignore
559
+ @property
557
560
  @requires_update
558
561
  def emeter_realtime(self) -> EmeterStatus:
559
562
  """Return current energy readings."""
560
563
  self._verify_emeter()
561
- return EmeterStatus(self.modules["emeter"].realtime)
564
+ return EmeterStatus(self.modules[Module.IotEmeter].realtime)
562
565
 
563
566
  async def get_emeter_realtime(self) -> EmeterStatus:
564
567
  """Retrieve current energy readings."""
565
568
  self._verify_emeter()
566
- return EmeterStatus(await self.modules["emeter"].get_realtime())
569
+ return EmeterStatus(await self.modules[Module.IotEmeter].get_realtime())
567
570
 
568
- @property # type: ignore
571
+ @property
569
572
  @requires_update
570
- def emeter_today(self) -> Optional[float]:
573
+ def emeter_today(self) -> float | None:
571
574
  """Return today's energy consumption in kWh."""
572
575
  self._verify_emeter()
573
- return self.modules["emeter"].emeter_today
576
+ return self.modules[Module.IotEmeter].emeter_today
574
577
 
575
- @property # type: ignore
578
+ @property
576
579
  @requires_update
577
- def emeter_this_month(self) -> Optional[float]:
580
+ def emeter_this_month(self) -> float | None:
578
581
  """Return this month's energy consumption in kWh."""
579
582
  self._verify_emeter()
580
- return self.modules["emeter"].emeter_this_month
583
+ return self.modules[Module.IotEmeter].emeter_this_month
581
584
 
582
585
  async def get_emeter_daily(
583
- self, year: Optional[int] = None, month: Optional[int] = None, kwh: bool = True
584
- ) -> Dict:
586
+ self, year: int | None = None, month: int | None = None, kwh: bool = True
587
+ ) -> dict:
585
588
  """Retrieve daily statistics for a given month.
586
589
 
587
590
  :param year: year for which to retrieve statistics (default: this year)
@@ -591,12 +594,14 @@ class SmartDevice:
591
594
  :return: mapping of day of month to value
592
595
  """
593
596
  self._verify_emeter()
594
- return await self.modules["emeter"].get_daystat(year=year, month=month, kwh=kwh)
597
+ return await self.modules[Module.IotEmeter].get_daystat(
598
+ year=year, month=month, kwh=kwh
599
+ )
595
600
 
596
601
  @requires_update
597
602
  async def get_emeter_monthly(
598
- self, year: Optional[int] = None, kwh: bool = True
599
- ) -> Dict:
603
+ self, year: int | None = None, kwh: bool = True
604
+ ) -> dict:
600
605
  """Retrieve monthly statistics for a given year.
601
606
 
602
607
  :param year: year for which to retrieve statistics (default: this year)
@@ -604,13 +609,13 @@ class SmartDevice:
604
609
  :return: dict: mapping of month to value
605
610
  """
606
611
  self._verify_emeter()
607
- return await self.modules["emeter"].get_monthstat(year=year, kwh=kwh)
612
+ return await self.modules[Module.IotEmeter].get_monthstat(year=year, kwh=kwh)
608
613
 
609
614
  @requires_update
610
- async def erase_emeter_stats(self) -> Dict:
615
+ async def erase_emeter_stats(self) -> dict:
611
616
  """Erase energy meter statistics."""
612
617
  self._verify_emeter()
613
- return await self.modules["emeter"].erase_stats()
618
+ return await self.modules[Module.IotEmeter].erase_stats()
614
619
 
615
620
  @requires_update
616
621
  async def current_consumption(self) -> float:
@@ -627,17 +632,11 @@ class SmartDevice:
627
632
  """
628
633
  await self._query_helper("system", "reboot", {"delay": delay})
629
634
 
630
- async def turn_off(self, **kwargs) -> Dict:
635
+ async def turn_off(self, **kwargs) -> dict:
631
636
  """Turn off the device."""
632
637
  raise NotImplementedError("Device subclass needs to implement this.")
633
638
 
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:
639
+ async def turn_on(self, **kwargs) -> dict | None:
641
640
  """Turn device on."""
642
641
  raise NotImplementedError("Device subclass needs to implement this.")
643
642
 
@@ -647,9 +646,16 @@ class SmartDevice:
647
646
  """Return True if the device is on."""
648
647
  raise NotImplementedError("Device subclass needs to implement this.")
649
648
 
649
+ async def set_state(self, on: bool):
650
+ """Set the device state."""
651
+ if on:
652
+ return await self.turn_on()
653
+ else:
654
+ return await self.turn_off()
655
+
650
656
  @property # type: ignore
651
657
  @requires_update
652
- def on_since(self) -> Optional[datetime]:
658
+ def on_since(self) -> datetime | None:
653
659
  """Return pretty-printed on-time, or None if not available."""
654
660
  if "on_time" not in self._sys_info:
655
661
  return None
@@ -661,12 +667,6 @@ class SmartDevice:
661
667
 
662
668
  return datetime.now().replace(microsecond=0) - timedelta(seconds=on_time)
663
669
 
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
670
  @property # type: ignore
671
671
  @requires_update
672
672
  def device_id(self) -> str:
@@ -677,7 +677,7 @@ class SmartDevice:
677
677
  """
678
678
  return self.mac
679
679
 
680
- async def wifi_scan(self) -> List[WifiNetwork]: # noqa: D202
680
+ async def wifi_scan(self) -> list[WifiNetwork]: # noqa: D202
681
681
  """Scan for available wifi networks."""
682
682
 
683
683
  async def _scan(target):
@@ -685,14 +685,14 @@ class SmartDevice:
685
685
 
686
686
  try:
687
687
  info = await _scan("netif")
688
- except SmartDeviceException as ex:
688
+ except KasaException as ex:
689
689
  _LOGGER.debug(
690
690
  "Unable to scan using 'netif', retrying with 'softaponboarding': %s", ex
691
691
  )
692
692
  info = await _scan("smartlife.iot.common.softaponboarding")
693
693
 
694
694
  if "ap_list" not in info:
695
- raise SmartDeviceException("Invalid response for wifi scan: %s" % info)
695
+ raise KasaException("Invalid response for wifi scan: %s" % info)
696
696
 
697
697
  return [WifiNetwork(**x) for x in info["ap_list"]]
698
698
 
@@ -708,83 +708,17 @@ class SmartDevice:
708
708
  payload = {"ssid": ssid, "password": password, "key_type": int(keytype)}
709
709
  try:
710
710
  return await _join("netif", payload)
711
- except SmartDeviceException as ex:
711
+ except KasaException as ex:
712
712
  _LOGGER.debug(
713
713
  "Unable to join using 'netif', retrying with 'softaponboarding': %s", ex
714
714
  )
715
715
  return await _join("smartlife.iot.common.softaponboarding", payload)
716
716
 
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
717
  @property
734
718
  def max_device_response_size(self) -> int:
735
719
  """Returns the maximum response size the device can safely construct."""
736
720
  return 16 * 1024
737
721
 
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
722
  @property
789
723
  def internal_state(self) -> Any:
790
724
  """Return the internal state of the instance.
@@ -793,47 +727,3 @@ class SmartDevice:
793
727
  This should only be used for debugging purposes.
794
728
  """
795
729
  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]