python-kasa 0.6.2__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 (168) 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 +12 -7
  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 -551
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/{newfakes.py → fakeprotocol_iot.py} +61 -291
  86. kasa/tests/fakeprotocol_smart.py +318 -0
  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/P300(EU)_1.0_1.0.13.json +13 -23
  99. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +6 -6
  100. kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +295 -0
  101. kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +423 -0
  102. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  103. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  104. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  105. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  106. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  107. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  108. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  109. kasa/tests/smart/__init__.py +0 -0
  110. kasa/tests/smart/features/__init__.py +0 -0
  111. kasa/tests/smart/features/test_brightness.py +55 -0
  112. kasa/tests/smart/features/test_colortemp.py +30 -0
  113. kasa/tests/smart/modules/__init__.py +0 -0
  114. kasa/tests/smart/modules/test_contact.py +28 -0
  115. kasa/tests/smart/modules/test_fan.py +79 -0
  116. kasa/tests/smart/modules/test_firmware.py +108 -0
  117. kasa/tests/smart/modules/test_humidity.py +28 -0
  118. kasa/tests/smart/modules/test_light_effect.py +41 -0
  119. kasa/tests/smart/modules/test_temperature.py +47 -0
  120. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  121. kasa/tests/smart/modules/test_waterleak.py +42 -0
  122. kasa/tests/test_aestransport.py +115 -25
  123. kasa/tests/test_bulb.py +169 -86
  124. kasa/tests/test_childdevice.py +84 -0
  125. kasa/tests/test_cli.py +452 -100
  126. kasa/tests/test_common_modules.py +216 -0
  127. kasa/tests/test_device.py +268 -0
  128. kasa/tests/test_device_factory.py +61 -41
  129. kasa/tests/test_device_type.py +1 -1
  130. kasa/tests/test_deviceconfig.py +2 -5
  131. kasa/tests/test_dimmer.py +33 -24
  132. kasa/tests/test_discovery.py +112 -69
  133. kasa/tests/test_emeter.py +39 -12
  134. kasa/tests/test_feature.py +205 -0
  135. kasa/tests/test_httpclient.py +9 -9
  136. kasa/tests/test_iotdevice.py +286 -0
  137. kasa/tests/test_klapprotocol.py +94 -41
  138. kasa/tests/test_lightstrip.py +24 -19
  139. kasa/tests/test_plug.py +51 -9
  140. kasa/tests/test_protocol.py +8 -12
  141. kasa/tests/test_readme_examples.py +86 -27
  142. kasa/tests/test_smartdevice.py +211 -247
  143. kasa/tests/test_smartprotocol.py +129 -26
  144. kasa/tests/test_strip.py +15 -6
  145. kasa/tests/test_usage.py +1 -3
  146. kasa/xortransport.py +15 -12
  147. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -141
  148. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  149. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +1 -1
  150. kasa/modules/emeter.py +0 -111
  151. kasa/smartlightstrip.py +0 -143
  152. kasa/smartplug.py +0 -91
  153. kasa/tapo/__init__.py +0 -7
  154. kasa/tapo/childdevice.py +0 -44
  155. kasa/tapo/tapobulb.py +0 -262
  156. kasa/tapo/tapodevice.py +0 -383
  157. kasa/tapo/tapoplug.py +0 -45
  158. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  159. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  160. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  161. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  162. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  163. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  164. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  165. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  166. python_kasa-0.6.2.dist-info/RECORD +0 -163
  167. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  168. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,653 @@
1
+ """Module for a SMART device."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import logging
7
+ from datetime import datetime, timedelta
8
+ from typing import TYPE_CHECKING, Any, Mapping, Sequence, cast
9
+
10
+ from ..aestransport import AesTransport
11
+ from ..device import Device, WifiNetwork
12
+ from ..device_type import DeviceType
13
+ from ..deviceconfig import DeviceConfig
14
+ from ..emeterstatus import EmeterStatus
15
+ from ..exceptions import AuthenticationError, DeviceError, KasaException, SmartErrorCode
16
+ from ..feature import Feature
17
+ from ..module import Module
18
+ from ..modulemapping import ModuleMapping, ModuleName
19
+ from ..smartprotocol import SmartProtocol
20
+ from .modules import (
21
+ Cloud,
22
+ DeviceModule,
23
+ Firmware,
24
+ Light,
25
+ Time,
26
+ )
27
+ from .smartmodule import SmartModule
28
+
29
+ _LOGGER = logging.getLogger(__name__)
30
+
31
+
32
+ # List of modules that wall switches with children, i.e. ks240 report on
33
+ # the child but only work on the parent. See longer note below in _initialize_modules.
34
+ # This list should be updated when creating new modules that could have the
35
+ # same issue, homekit perhaps?
36
+ WALL_SWITCH_PARENT_ONLY_MODULES = [DeviceModule, Time, Firmware, Cloud]
37
+
38
+
39
+ # Device must go last as the other interfaces also inherit Device
40
+ # and python needs a consistent method resolution order.
41
+ class SmartDevice(Device):
42
+ """Base class to represent a SMART protocol based device."""
43
+
44
+ def __init__(
45
+ self,
46
+ host: str,
47
+ *,
48
+ config: DeviceConfig | None = None,
49
+ protocol: SmartProtocol | None = None,
50
+ ) -> None:
51
+ _protocol = protocol or SmartProtocol(
52
+ transport=AesTransport(config=config or DeviceConfig(host=host)),
53
+ )
54
+ super().__init__(host=host, config=config, protocol=_protocol)
55
+ self.protocol: SmartProtocol
56
+ self._components_raw: dict[str, Any] | None = None
57
+ self._components: dict[str, int] = {}
58
+ self._state_information: dict[str, Any] = {}
59
+ self._modules: dict[str | ModuleName[Module], SmartModule] = {}
60
+ self._exposes_child_modules = False
61
+ self._parent: SmartDevice | None = None
62
+ self._children: Mapping[str, SmartDevice] = {}
63
+ self._last_update = {}
64
+
65
+ async def _initialize_children(self):
66
+ """Initialize children for power strips."""
67
+ child_info_query = {
68
+ "get_child_device_component_list": None,
69
+ "get_child_device_list": None,
70
+ }
71
+ resp = await self.protocol.query(child_info_query)
72
+ self.internal_state.update(resp)
73
+
74
+ children = self.internal_state["get_child_device_list"]["child_device_list"]
75
+ children_components = {
76
+ child["device_id"]: {
77
+ comp["id"]: int(comp["ver_code"]) for comp in child["component_list"]
78
+ }
79
+ for child in self.internal_state["get_child_device_component_list"][
80
+ "child_component_list"
81
+ ]
82
+ }
83
+ from .smartchilddevice import SmartChildDevice
84
+
85
+ self._children = {
86
+ child_info["device_id"]: await SmartChildDevice.create(
87
+ parent=self,
88
+ child_info=child_info,
89
+ child_components=children_components[child_info["device_id"]],
90
+ )
91
+ for child_info in children
92
+ }
93
+
94
+ @property
95
+ def children(self) -> Sequence[SmartDevice]:
96
+ """Return list of children."""
97
+ return list(self._children.values())
98
+
99
+ @property
100
+ def modules(self) -> ModuleMapping[SmartModule]:
101
+ """Return the device modules."""
102
+ if self._exposes_child_modules:
103
+ modules = {k: v for k, v in self._modules.items()}
104
+ for child in self._children.values():
105
+ for k, v in child._modules.items():
106
+ if k not in modules:
107
+ modules[k] = v
108
+ if TYPE_CHECKING:
109
+ return cast(ModuleMapping[SmartModule], modules)
110
+ return modules
111
+
112
+ if TYPE_CHECKING: # Needed for python 3.8
113
+ return cast(ModuleMapping[SmartModule], self._modules)
114
+ return self._modules
115
+
116
+ def _try_get_response(self, responses: dict, request: str, default=None) -> dict:
117
+ response = responses.get(request)
118
+ if isinstance(response, SmartErrorCode):
119
+ _LOGGER.debug(
120
+ "Error %s getting request %s for device %s",
121
+ response,
122
+ request,
123
+ self.host,
124
+ )
125
+ response = None
126
+ if response is not None:
127
+ return response
128
+ if default is not None:
129
+ return default
130
+ raise KasaException(
131
+ f"{request} not found in {responses} for device {self.host}"
132
+ )
133
+
134
+ async def _negotiate(self):
135
+ """Perform initialization.
136
+
137
+ We fetch the device info and the available components as early as possible.
138
+ If the device reports supporting child devices, they are also initialized.
139
+ """
140
+ initial_query = {
141
+ "component_nego": None,
142
+ "get_device_info": None,
143
+ "get_connect_cloud_state": None,
144
+ }
145
+ resp = await self.protocol.query(initial_query)
146
+
147
+ # Save the initial state to allow modules access the device info already
148
+ # during the initialization, which is necessary as some information like the
149
+ # supported color temperature range is contained within the response.
150
+ self._last_update.update(resp)
151
+ self._info = self._try_get_response(resp, "get_device_info")
152
+
153
+ # Create our internal presentation of available components
154
+ self._components_raw = resp["component_nego"]
155
+ self._components = {
156
+ comp["id"]: int(comp["ver_code"])
157
+ for comp in self._components_raw["component_list"]
158
+ }
159
+
160
+ if "child_device" in self._components and not self.children:
161
+ await self._initialize_children()
162
+
163
+ async def update(self, update_children: bool = True):
164
+ """Update the device."""
165
+ if self.credentials is None and self.credentials_hash is None:
166
+ raise AuthenticationError("Tapo plug requires authentication.")
167
+
168
+ if self._components_raw is None:
169
+ await self._negotiate()
170
+ await self._initialize_modules()
171
+
172
+ req: dict[str, Any] = {}
173
+
174
+ # TODO: this could be optimized by constructing the query only once
175
+ for module in self._modules.values():
176
+ req.update(module.query())
177
+
178
+ self._last_update = resp = await self.protocol.query(req)
179
+
180
+ self._info = self._try_get_response(resp, "get_device_info")
181
+ if child_info := self._try_get_response(resp, "get_child_device_list", {}):
182
+ # TODO: we don't currently perform queries on children based on modules,
183
+ # but just update the information that is returned in the main query.
184
+ for info in child_info["child_device_list"]:
185
+ self._children[info["device_id"]]._update_internal_state(info)
186
+
187
+ # Call handle update for modules that want to update internal data
188
+ for module in self._modules.values():
189
+ module._post_update_hook()
190
+ for child in self._children.values():
191
+ for child_module in child._modules.values():
192
+ child_module._post_update_hook()
193
+
194
+ # We can first initialize the features after the first update.
195
+ # We make here an assumption that every device has at least a single feature.
196
+ if not self._features:
197
+ await self._initialize_features()
198
+
199
+ _LOGGER.debug("Got an update: %s", self._last_update)
200
+
201
+ async def _initialize_modules(self):
202
+ """Initialize modules based on component negotiation response."""
203
+ from .smartmodule import SmartModule
204
+
205
+ # Some wall switches (like ks240) are internally presented as having child
206
+ # devices which report the child's components on the parent's sysinfo, even
207
+ # when they need to be accessed through the children.
208
+ # The logic below ensures that such devices add all but whitelisted, only on
209
+ # the child device.
210
+ skip_parent_only_modules = False
211
+ child_modules_to_skip = {}
212
+ if self._parent and self._parent.device_type == DeviceType.WallSwitch:
213
+ skip_parent_only_modules = True
214
+ elif self._children and self.device_type == DeviceType.WallSwitch:
215
+ # _initialize_modules is called on the parent after the children
216
+ self._exposes_child_modules = True
217
+ for child in self._children.values():
218
+ child_modules_to_skip.update(**child.modules)
219
+
220
+ for mod in SmartModule.REGISTERED_MODULES.values():
221
+ _LOGGER.debug("%s requires %s", mod, mod.REQUIRED_COMPONENT)
222
+
223
+ if (
224
+ skip_parent_only_modules and mod in WALL_SWITCH_PARENT_ONLY_MODULES
225
+ ) or mod.__name__ in child_modules_to_skip:
226
+ continue
227
+ if (
228
+ mod.REQUIRED_COMPONENT in self._components
229
+ or self.sys_info.get(mod.REQUIRED_KEY_ON_PARENT) is not None
230
+ ):
231
+ _LOGGER.debug(
232
+ "Found required %s, adding %s to modules.",
233
+ mod.REQUIRED_COMPONENT,
234
+ mod.__name__,
235
+ )
236
+ module = mod(self, mod.REQUIRED_COMPONENT)
237
+ if await module._check_supported():
238
+ self._modules[module.name] = module
239
+
240
+ if (
241
+ Module.Brightness in self._modules
242
+ or Module.Color in self._modules
243
+ or Module.ColorTemperature in self._modules
244
+ ):
245
+ self._modules[Light.__name__] = Light(self, "light")
246
+
247
+ async def _initialize_features(self):
248
+ """Initialize device features."""
249
+ self._add_feature(
250
+ Feature(
251
+ self,
252
+ id="device_id",
253
+ name="Device ID",
254
+ attribute_getter="device_id",
255
+ category=Feature.Category.Debug,
256
+ )
257
+ )
258
+ if "device_on" in self._info:
259
+ self._add_feature(
260
+ Feature(
261
+ self,
262
+ id="state",
263
+ name="State",
264
+ attribute_getter="is_on",
265
+ attribute_setter="set_state",
266
+ type=Feature.Type.Switch,
267
+ category=Feature.Category.Primary,
268
+ )
269
+ )
270
+
271
+ if "signal_level" in self._info:
272
+ self._add_feature(
273
+ Feature(
274
+ self,
275
+ id="signal_level",
276
+ name="Signal Level",
277
+ attribute_getter=lambda x: x._info["signal_level"],
278
+ icon="mdi:signal",
279
+ category=Feature.Category.Info,
280
+ )
281
+ )
282
+
283
+ if "rssi" in self._info:
284
+ self._add_feature(
285
+ Feature(
286
+ self,
287
+ id="rssi",
288
+ name="RSSI",
289
+ attribute_getter=lambda x: x._info["rssi"],
290
+ icon="mdi:signal",
291
+ category=Feature.Category.Debug,
292
+ )
293
+ )
294
+
295
+ if "ssid" in self._info:
296
+ self._add_feature(
297
+ Feature(
298
+ device=self,
299
+ id="ssid",
300
+ name="SSID",
301
+ attribute_getter="ssid",
302
+ icon="mdi:wifi",
303
+ category=Feature.Category.Debug,
304
+ )
305
+ )
306
+
307
+ if "overheated" in self._info:
308
+ self._add_feature(
309
+ Feature(
310
+ self,
311
+ id="overheated",
312
+ name="Overheated",
313
+ attribute_getter=lambda x: x._info["overheated"],
314
+ icon="mdi:heat-wave",
315
+ type=Feature.Type.BinarySensor,
316
+ category=Feature.Category.Info,
317
+ )
318
+ )
319
+
320
+ # We check for the key available, and not for the property truthiness,
321
+ # as the value is falsy when the device is off.
322
+ if "on_time" in self._info:
323
+ self._add_feature(
324
+ Feature(
325
+ device=self,
326
+ id="on_since",
327
+ name="On since",
328
+ attribute_getter="on_since",
329
+ icon="mdi:clock",
330
+ category=Feature.Category.Info,
331
+ )
332
+ )
333
+
334
+ for module in self.modules.values():
335
+ # Check if module features have already been initialized.
336
+ # i.e. when _exposes_child_modules is true
337
+ if not module._module_features:
338
+ module._initialize_features()
339
+ for feat in module._module_features.values():
340
+ self._add_feature(feat)
341
+ for child in self._children.values():
342
+ await child._initialize_features()
343
+
344
+ @property
345
+ def is_cloud_connected(self) -> bool:
346
+ """Returns if the device is connected to the cloud."""
347
+ if Module.Cloud not in self.modules:
348
+ return False
349
+ return self.modules[Module.Cloud].is_connected
350
+
351
+ @property
352
+ def sys_info(self) -> dict[str, Any]:
353
+ """Returns the device info."""
354
+ return self._info # type: ignore
355
+
356
+ @property
357
+ def model(self) -> str:
358
+ """Returns the device model."""
359
+ return str(self._info.get("model"))
360
+
361
+ @property
362
+ def alias(self) -> str | None:
363
+ """Returns the device alias or nickname."""
364
+ if self._info and (nickname := self._info.get("nickname")):
365
+ return base64.b64decode(nickname).decode()
366
+ else:
367
+ return None
368
+
369
+ @property
370
+ def time(self) -> datetime:
371
+ """Return the time."""
372
+ # TODO: Default to parent's time module for child devices
373
+ if self._parent and Module.Time in self.modules:
374
+ _timemod = self._parent.modules[Module.Time]
375
+ else:
376
+ _timemod = self.modules[Module.Time]
377
+
378
+ return _timemod.time
379
+
380
+ @property
381
+ def timezone(self) -> dict:
382
+ """Return the timezone and time_difference."""
383
+ ti = self.time
384
+ return {"timezone": ti.tzname()}
385
+
386
+ @property
387
+ def hw_info(self) -> dict:
388
+ """Return hardware info for the device."""
389
+ return {
390
+ "sw_ver": self._info.get("fw_ver"),
391
+ "hw_ver": self._info.get("hw_ver"),
392
+ "mac": self._info.get("mac"),
393
+ "type": self._info.get("type"),
394
+ "hwId": self._info.get("device_id"),
395
+ "dev_name": self.alias,
396
+ "oemId": self._info.get("oem_id"),
397
+ }
398
+
399
+ @property
400
+ def location(self) -> dict:
401
+ """Return the device location."""
402
+ loc = {
403
+ "latitude": cast(float, self._info.get("latitude", 0)) / 10_000,
404
+ "longitude": cast(float, self._info.get("longitude", 0)) / 10_000,
405
+ }
406
+ return loc
407
+
408
+ @property
409
+ def rssi(self) -> int | None:
410
+ """Return the rssi."""
411
+ rssi = self._info.get("rssi")
412
+ return int(rssi) if rssi else None
413
+
414
+ @property
415
+ def mac(self) -> str:
416
+ """Return the mac formatted with colons."""
417
+ return str(self._info.get("mac")).replace("-", ":")
418
+
419
+ @property
420
+ def device_id(self) -> str:
421
+ """Return the device id."""
422
+ return str(self._info.get("device_id"))
423
+
424
+ @property
425
+ def internal_state(self) -> Any:
426
+ """Return all the internal state data."""
427
+ return self._last_update
428
+
429
+ def _update_internal_state(self, info):
430
+ """Update the internal info state.
431
+
432
+ This is used by the parent to push updates to its children.
433
+ """
434
+ self._info = info
435
+
436
+ async def _query_helper(
437
+ self, method: str, params: dict | None = None, child_ids=None
438
+ ) -> Any:
439
+ res = await self.protocol.query({method: params})
440
+
441
+ return res
442
+
443
+ @property
444
+ def ssid(self) -> str:
445
+ """Return ssid of the connected wifi ap."""
446
+ ssid = self._info.get("ssid")
447
+ ssid = base64.b64decode(ssid).decode() if ssid else "No SSID"
448
+ return ssid
449
+
450
+ @property
451
+ def has_emeter(self) -> bool:
452
+ """Return if the device has emeter."""
453
+ return Module.Energy in self.modules
454
+
455
+ @property
456
+ def is_on(self) -> bool:
457
+ """Return true if the device is on."""
458
+ return bool(self._info.get("device_on"))
459
+
460
+ async def set_state(self, on: bool): # TODO: better name wanted.
461
+ """Set the device state.
462
+
463
+ See :meth:`is_on`.
464
+ """
465
+ return await self.protocol.query({"set_device_info": {"device_on": on}})
466
+
467
+ async def turn_on(self, **kwargs):
468
+ """Turn on the device."""
469
+ await self.set_state(True)
470
+
471
+ async def turn_off(self, **kwargs):
472
+ """Turn off the device."""
473
+ await self.set_state(False)
474
+
475
+ def update_from_discover_info(self, info):
476
+ """Update state from info from the discover call."""
477
+ self._discovery_info = info
478
+ self._info = info
479
+
480
+ async def get_emeter_realtime(self) -> EmeterStatus:
481
+ """Retrieve current energy readings."""
482
+ _LOGGER.warning("Deprecated, use `emeter_realtime`.")
483
+ if not self.has_emeter:
484
+ raise KasaException("Device has no emeter")
485
+ return self.emeter_realtime
486
+
487
+ @property
488
+ def emeter_realtime(self) -> EmeterStatus:
489
+ """Get the emeter status."""
490
+ energy = self.modules[Module.Energy]
491
+ return energy.emeter_realtime
492
+
493
+ @property
494
+ def emeter_this_month(self) -> float | None:
495
+ """Get the emeter value for this month."""
496
+ energy = self.modules[Module.Energy]
497
+ return energy.emeter_this_month
498
+
499
+ @property
500
+ def emeter_today(self) -> float | None:
501
+ """Get the emeter value for today."""
502
+ energy = self.modules[Module.Energy]
503
+ return energy.emeter_today
504
+
505
+ @property
506
+ def on_since(self) -> datetime | None:
507
+ """Return the time that the device was turned on or None if turned off."""
508
+ if (
509
+ not self._info.get("device_on")
510
+ or (on_time := self._info.get("on_time")) is None
511
+ ):
512
+ return None
513
+ on_time = cast(float, on_time)
514
+ if (timemod := self.modules.get(Module.Time)) is not None:
515
+ return timemod.time - timedelta(seconds=on_time)
516
+ else: # We have no device time, use current local time.
517
+ return datetime.now().replace(microsecond=0) - timedelta(seconds=on_time)
518
+
519
+ async def wifi_scan(self) -> list[WifiNetwork]:
520
+ """Scan for available wifi networks."""
521
+
522
+ def _net_for_scan_info(res):
523
+ return WifiNetwork(
524
+ ssid=base64.b64decode(res["ssid"]).decode(),
525
+ cipher_type=res["cipher_type"],
526
+ key_type=res["key_type"],
527
+ channel=res["channel"],
528
+ signal_level=res["signal_level"],
529
+ bssid=res["bssid"],
530
+ )
531
+
532
+ _LOGGER.debug("Querying networks")
533
+
534
+ resp = await self.protocol.query({"get_wireless_scan_info": {"start_index": 0}})
535
+ networks = [
536
+ _net_for_scan_info(net) for net in resp["get_wireless_scan_info"]["ap_list"]
537
+ ]
538
+ return networks
539
+
540
+ async def wifi_join(self, ssid: str, password: str, keytype: str = "wpa2_psk"):
541
+ """Join the given wifi network.
542
+
543
+ This method returns nothing as the device tries to activate the new
544
+ settings immediately instead of responding to the request.
545
+
546
+ If joining the network fails, the device will return to the previous state
547
+ after some delay.
548
+ """
549
+ if not self.credentials:
550
+ raise AuthenticationError("Device requires authentication.")
551
+
552
+ payload = {
553
+ "account": {
554
+ "username": base64.b64encode(
555
+ self.credentials.username.encode()
556
+ ).decode(),
557
+ "password": base64.b64encode(
558
+ self.credentials.password.encode()
559
+ ).decode(),
560
+ },
561
+ "wireless": {
562
+ "key_type": keytype,
563
+ "password": base64.b64encode(password.encode()).decode(),
564
+ "ssid": base64.b64encode(ssid.encode()).decode(),
565
+ },
566
+ "time": self.internal_state["get_device_time"],
567
+ }
568
+
569
+ # The device does not respond to the request but changes the settings
570
+ # immediately which causes us to timeout.
571
+ # Thus, We limit retries and suppress the raised exception as useless.
572
+ try:
573
+ return await self.protocol.query({"set_qs_info": payload}, retry_count=0)
574
+ except DeviceError:
575
+ raise # Re-raise on device-reported errors
576
+ except KasaException:
577
+ _LOGGER.debug("Received an expected for wifi join, but this is expected")
578
+
579
+ async def update_credentials(self, username: str, password: str):
580
+ """Update device credentials.
581
+
582
+ This will replace the existing authentication credentials on the device.
583
+ """
584
+ time_data = self.internal_state["get_device_time"]
585
+ payload = {
586
+ "account": {
587
+ "username": base64.b64encode(username.encode()).decode(),
588
+ "password": base64.b64encode(password.encode()).decode(),
589
+ },
590
+ "time": time_data,
591
+ }
592
+ return await self.protocol.query({"set_qs_info": payload})
593
+
594
+ async def set_alias(self, alias: str):
595
+ """Set the device name (alias)."""
596
+ return await self.protocol.query(
597
+ {"set_device_info": {"nickname": base64.b64encode(alias.encode()).decode()}}
598
+ )
599
+
600
+ async def reboot(self, delay: int = 1) -> None:
601
+ """Reboot the device.
602
+
603
+ Note that giving a delay of zero causes this to block,
604
+ as the device reboots immediately without responding to the call.
605
+ """
606
+ await self.protocol.query({"device_reboot": {"delay": delay}})
607
+
608
+ async def factory_reset(self) -> None:
609
+ """Reset device back to factory settings.
610
+
611
+ Note, this does not downgrade the firmware.
612
+ """
613
+ await self.protocol.query("device_reset")
614
+
615
+ @property
616
+ def device_type(self) -> DeviceType:
617
+ """Return the device type."""
618
+ if self._device_type is not DeviceType.Unknown:
619
+ return self._device_type
620
+
621
+ self._device_type = self._get_device_type_from_components(
622
+ list(self._components.keys()), self._info["type"]
623
+ )
624
+
625
+ return self._device_type
626
+
627
+ @staticmethod
628
+ def _get_device_type_from_components(
629
+ components: list[str], device_type: str
630
+ ) -> DeviceType:
631
+ """Find type to be displayed as a supported device category."""
632
+ if "HUB" in device_type:
633
+ return DeviceType.Hub
634
+ if "PLUG" in device_type:
635
+ if "child_device" in components:
636
+ return DeviceType.Strip
637
+ return DeviceType.Plug
638
+ if "light_strip" in components:
639
+ return DeviceType.LightStrip
640
+ if "SWITCH" in device_type and "child_device" in components:
641
+ return DeviceType.WallSwitch
642
+ if "dimmer_calibration" in components:
643
+ return DeviceType.Dimmer
644
+ if "brightness" in components:
645
+ return DeviceType.Bulb
646
+ if "SWITCH" in device_type:
647
+ return DeviceType.WallSwitch
648
+ if "SENSOR" in device_type:
649
+ return DeviceType.Sensor
650
+ if "ENERGY" in device_type:
651
+ return DeviceType.Thermostat
652
+ _LOGGER.warning("Unknown device type, falling back to plug")
653
+ return DeviceType.Plug