python-kasa 0.7.0.dev2__py3-none-any.whl → 0.7.0.dev4__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.
kasa/aestransport.py CHANGED
@@ -28,6 +28,8 @@ from .exceptions import (
28
28
  DeviceError,
29
29
  KasaException,
30
30
  SmartErrorCode,
31
+ TimeoutError,
32
+ _ConnectionError,
31
33
  _RetryableError,
32
34
  )
33
35
  from .httpclient import HttpClient
@@ -220,7 +222,7 @@ class AesTransport(BaseTransport):
220
222
  "%s: logged in with default credentials",
221
223
  self._host,
222
224
  )
223
- except AuthenticationError:
225
+ except (AuthenticationError, _ConnectionError, TimeoutError):
224
226
  raise
225
227
  except Exception as ex:
226
228
  raise KasaException(
kasa/cli.py CHANGED
@@ -92,7 +92,7 @@ ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in DeviceEncryptionType]
92
92
  DEVICE_FAMILY_TYPES = [device_family_type.value for device_family_type in DeviceFamily]
93
93
 
94
94
  # Block list of commands which require no update
95
- SKIP_UPDATE_COMMANDS = ["wifi", "raw-command", "command"]
95
+ SKIP_UPDATE_COMMANDS = ["raw-command", "command"]
96
96
 
97
97
  click.anyio_backend = "asyncio"
98
98
 
kasa/iot/iotstrip.py CHANGED
@@ -10,6 +10,7 @@ from typing import Any
10
10
  from ..device_type import DeviceType
11
11
  from ..deviceconfig import DeviceConfig
12
12
  from ..exceptions import KasaException
13
+ from ..feature import Feature
13
14
  from ..module import Module
14
15
  from ..protocol import BaseProtocol
15
16
  from .iotdevice import (
@@ -125,6 +126,8 @@ class IotStrip(IotDevice):
125
126
  )
126
127
  for child in children
127
128
  }
129
+ for child in self._children.values():
130
+ await child._initialize_features()
128
131
 
129
132
  if update_children and self.has_emeter:
130
133
  for plug in self.children:
@@ -250,6 +253,32 @@ class IotStripPlug(IotPlug):
250
253
  await super()._initialize_modules()
251
254
  self.add_module("time", Time(self, "time"))
252
255
 
256
+ async def _initialize_features(self):
257
+ """Initialize common features."""
258
+ self._add_feature(
259
+ Feature(
260
+ self,
261
+ id="state",
262
+ name="State",
263
+ attribute_getter="is_on",
264
+ attribute_setter="set_state",
265
+ type=Feature.Type.Switch,
266
+ category=Feature.Category.Primary,
267
+ )
268
+ )
269
+ self._add_feature(
270
+ Feature(
271
+ device=self,
272
+ id="on_since",
273
+ name="On since",
274
+ attribute_getter="on_since",
275
+ icon="mdi:clock",
276
+ )
277
+ )
278
+ # If the strip plug has it's own modules we should call initialize
279
+ # features for the modules here. However the _initialize_modules function
280
+ # above does not seem to be called.
281
+
253
282
  async def update(self, update_children: bool = True):
254
283
  """Query the device to update the data.
255
284
 
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from ...interfaces.lighteffect import LightEffect as LightEffectInterface
6
+ from ...module import Module
6
7
  from ..effects import EFFECT_MAPPING_V1, EFFECT_NAMES_V1
7
8
  from ..iotmodule import IotModule
8
9
 
@@ -59,19 +60,24 @@ class LightEffect(IotModule, LightEffectInterface):
59
60
  :param int transition: The wanted transition time
60
61
  """
61
62
  if effect == self.LIGHT_EFFECTS_OFF:
62
- effect_dict = dict(self.data["lighting_effect_state"])
63
- effect_dict["enable"] = 0
63
+ light_module = self._device.modules[Module.Light]
64
+ effect_off_state = light_module.state
65
+ if brightness is not None:
66
+ effect_off_state.brightness = brightness
67
+ if transition is not None:
68
+ effect_off_state.transition = transition
69
+ await light_module.set_state(effect_off_state)
64
70
  elif effect not in EFFECT_MAPPING_V1:
65
71
  raise ValueError(f"The effect {effect} is not a built in effect.")
66
72
  else:
67
73
  effect_dict = EFFECT_MAPPING_V1[effect]
68
74
 
69
- if brightness is not None:
70
- effect_dict["brightness"] = brightness
71
- if transition is not None:
72
- effect_dict["transition"] = transition
75
+ if brightness is not None:
76
+ effect_dict["brightness"] = brightness
77
+ if transition is not None:
78
+ effect_dict["transition"] = transition
73
79
 
74
- await self.set_custom_effect(effect_dict)
80
+ await self.set_custom_effect(effect_dict)
75
81
 
76
82
  async def set_custom_effect(
77
83
  self,
@@ -99,3 +99,11 @@ class AutoOff(SmartModule):
99
99
  sysinfo = self._device.sys_info
100
100
 
101
101
  return self._device.time + timedelta(seconds=sysinfo["auto_off_remain_time"])
102
+
103
+ async def _check_supported(self):
104
+ """Additional check to see if the module is supported by the device.
105
+
106
+ Parent devices that report components of children such as P300 will not have
107
+ the auto_off_status is sysinfo.
108
+ """
109
+ return "auto_off_status" in self._device.sys_info
kasa/smart/modules/fan.py CHANGED
@@ -5,13 +5,14 @@ from __future__ import annotations
5
5
  from typing import TYPE_CHECKING
6
6
 
7
7
  from ...feature import Feature
8
+ from ...interfaces.fan import Fan as FanInterface
8
9
  from ..smartmodule import SmartModule
9
10
 
10
11
  if TYPE_CHECKING:
11
12
  from ..smartdevice import SmartDevice
12
13
 
13
14
 
14
- class Fan(SmartModule):
15
+ class Fan(SmartModule, FanInterface):
15
16
  """Implementation of fan_control module."""
16
17
 
17
18
  REQUIRED_COMPONENT = "fan_control"
@@ -54,7 +55,7 @@ class Fan(SmartModule):
54
55
  @property
55
56
  def fan_speed_level(self) -> int:
56
57
  """Return fan speed level."""
57
- return self.data["fan_speed_level"]
58
+ return 0 if self.data["device_on"] is False else self.data["fan_speed_level"]
58
59
 
59
60
  async def set_fan_speed_level(self, level: int):
60
61
  """Set fan speed level, 0 for off, 1-4 for on."""
@@ -140,3 +140,13 @@ class LightPreset(SmartModule, LightPresetInterface):
140
140
  if self._state_in_sysinfo: # Child lights can have states in the child info
141
141
  return {}
142
142
  return {self.QUERY_GETTER_NAME: None}
143
+
144
+ async def _check_supported(self):
145
+ """Additional check to see if the module is supported by the device.
146
+
147
+ Parent devices that report components of children such as ks240 will not have
148
+ the brightness value is sysinfo.
149
+ """
150
+ # Look in _device.sys_info here because self.data is either sys_info or
151
+ # get_preset_rules depending on whether it's a child device or not.
152
+ return "brightness" in self._device.sys_info
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import logging
6
+ from typing import Any
6
7
 
7
8
  from ..device_type import DeviceType
8
9
  from ..deviceconfig import DeviceConfig
@@ -34,7 +35,17 @@ class SmartChildDevice(SmartDevice):
34
35
  self.protocol = _ChildProtocolWrapper(self._id, parent.protocol)
35
36
 
36
37
  async def update(self, update_children: bool = True):
37
- """Noop update. The parent updates our internals."""
38
+ """Update child module info.
39
+
40
+ The parent updates our internal info so just update modules with
41
+ their own queries.
42
+ """
43
+ req: dict[str, Any] = {}
44
+ for module in self.modules.values():
45
+ if mod_query := module.query():
46
+ req.update(mod_query)
47
+ if req:
48
+ self._last_update = await self.protocol.query(req)
38
49
 
39
50
  @classmethod
40
51
  async def create(cls, parent: SmartDevice, child_info, child_components):
kasa/smart/smartdevice.py CHANGED
@@ -29,11 +29,11 @@ from .smartmodule import SmartModule
29
29
  _LOGGER = logging.getLogger(__name__)
30
30
 
31
31
 
32
- # List of modules that wall switches with children, i.e. ks240 report on
32
+ # List of modules that non hub devices with children, i.e. ks240/P300, report on
33
33
  # the child but only work on the parent. See longer note below in _initialize_modules.
34
34
  # This list should be updated when creating new modules that could have the
35
35
  # same issue, homekit perhaps?
36
- WALL_SWITCH_PARENT_ONLY_MODULES = [DeviceModule, Time, Firmware, Cloud]
36
+ NON_HUB_PARENT_ONLY_MODULES = [DeviceModule, Time, Firmware, Cloud]
37
37
 
38
38
 
39
39
  # Device must go last as the other interfaces also inherit Device
@@ -57,7 +57,6 @@ class SmartDevice(Device):
57
57
  self._components: dict[str, int] = {}
58
58
  self._state_information: dict[str, Any] = {}
59
59
  self._modules: dict[str | ModuleName[Module], SmartModule] = {}
60
- self._exposes_child_modules = False
61
60
  self._parent: SmartDevice | None = None
62
61
  self._children: Mapping[str, SmartDevice] = {}
63
62
  self._last_update = {}
@@ -99,16 +98,6 @@ class SmartDevice(Device):
99
98
  @property
100
99
  def modules(self) -> ModuleMapping[SmartModule]:
101
100
  """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
101
  if TYPE_CHECKING: # Needed for python 3.8
113
102
  return cast(ModuleMapping[SmartModule], self._modules)
114
103
  return self._modules
@@ -160,7 +149,7 @@ class SmartDevice(Device):
160
149
  if "child_device" in self._components and not self.children:
161
150
  await self._initialize_children()
162
151
 
163
- async def update(self, update_children: bool = True):
152
+ async def update(self, update_children: bool = False):
164
153
  """Update the device."""
165
154
  if self.credentials is None and self.credentials_hash is None:
166
155
  raise AuthenticationError("Tapo plug requires authentication.")
@@ -178,9 +167,14 @@ class SmartDevice(Device):
178
167
  self._last_update = resp = await self.protocol.query(req)
179
168
 
180
169
  self._info = self._try_get_response(resp, "get_device_info")
170
+
171
+ # Call child update which will only update module calls, info is updated
172
+ # from get_child_device_list. update_children only affects hub devices, other
173
+ # devices will always update children to prevent errors on module access.
174
+ if update_children or self.device_type != DeviceType.Hub:
175
+ for child in self._children.values():
176
+ await child.update()
181
177
  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
178
  for info in child_info["child_device_list"]:
185
179
  self._children[info["device_id"]]._update_internal_state(info)
186
180
 
@@ -207,21 +201,18 @@ class SmartDevice(Device):
207
201
  # when they need to be accessed through the children.
208
202
  # The logic below ensures that such devices add all but whitelisted, only on
209
203
  # the child device.
204
+ # It also ensures that devices like power strips do not add modules such as
205
+ # firmware to the child devices.
210
206
  skip_parent_only_modules = False
211
207
  child_modules_to_skip = {}
212
- if self._parent and self._parent.device_type == DeviceType.WallSwitch:
208
+ if self._parent and self._parent.device_type != DeviceType.Hub:
213
209
  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
210
 
220
211
  for mod in SmartModule.REGISTERED_MODULES.values():
221
212
  _LOGGER.debug("%s requires %s", mod, mod.REQUIRED_COMPONENT)
222
213
 
223
214
  if (
224
- skip_parent_only_modules and mod in WALL_SWITCH_PARENT_ONLY_MODULES
215
+ skip_parent_only_modules and mod in NON_HUB_PARENT_ONLY_MODULES
225
216
  ) or mod.__name__ in child_modules_to_skip:
226
217
  continue
227
218
  if (
@@ -332,10 +323,7 @@ class SmartDevice(Device):
332
323
  )
333
324
 
334
325
  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()
326
+ module._initialize_features()
339
327
  for feat in module._module_features.values():
340
328
  self._add_feature(feat)
341
329
  for child in self._children.values():
@@ -369,8 +357,7 @@ class SmartDevice(Device):
369
357
  @property
370
358
  def time(self) -> datetime:
371
359
  """Return the time."""
372
- # TODO: Default to parent's time module for child devices
373
- if self._parent and Module.Time in self.modules:
360
+ if self._parent and Module.Time in self._parent.modules:
374
361
  _timemod = self._parent.modules[Module.Time]
375
362
  else:
376
363
  _timemod = self.modules[Module.Time]
@@ -152,6 +152,24 @@ def parametrize_combine(parametrized: list[pytest.MarkDecorator]):
152
152
  )
153
153
 
154
154
 
155
+ def parametrize_subtract(params: pytest.MarkDecorator, subtract: pytest.MarkDecorator):
156
+ """Combine multiple pytest parametrize dev marks into one set of fixtures."""
157
+ if params.args[0] != "dev" or subtract.args[0] != "dev":
158
+ raise Exception(
159
+ f"Supplied mark is not for dev fixture: {params.args[0]} {subtract.args[0]}"
160
+ )
161
+ fixtures = []
162
+ for param in params.args[1]:
163
+ if param not in subtract.args[1]:
164
+ fixtures.append(param)
165
+ return pytest.mark.parametrize(
166
+ "dev",
167
+ sorted(fixtures),
168
+ indirect=True,
169
+ ids=idgenerator,
170
+ )
171
+
172
+
155
173
  def parametrize(
156
174
  desc,
157
175
  *,
@@ -434,3 +452,16 @@ async def dev(request) -> AsyncGenerator[Device, None]:
434
452
  yield dev
435
453
 
436
454
  await dev.disconnect()
455
+
456
+
457
+ def get_parent_and_child_modules(device: Device, module_name):
458
+ """Return iterator of module if exists on parent and children.
459
+
460
+ Useful for testing devices that have components listed on the parent that are only
461
+ supported on the children, i.e. ks240.
462
+ """
463
+ if module_name in device.modules:
464
+ yield device.modules[module_name]
465
+ for child in device.children:
466
+ if module_name in child.modules:
467
+ yield child.modules[module_name]
@@ -317,6 +317,12 @@ class FakeIotTransport(BaseTransport):
317
317
  _LOGGER.debug("New light state: %s", new_state)
318
318
  self.proto["system"]["get_sysinfo"]["light_state"] = new_state
319
319
 
320
+ # Setting the light state on a device will turn off any active lighting effects.
321
+ if lighting_effect_state := self.proto["system"]["get_sysinfo"].get(
322
+ "lighting_effect_state"
323
+ ):
324
+ lighting_effect_state["enable"] = 0
325
+
320
326
  def set_preferred_state(self, new_state, *args):
321
327
  """Implement set_preferred_state."""
322
328
  self.proto["system"]["get_sysinfo"]["preferred_state"][new_state["index"]] = (
@@ -149,6 +149,11 @@ class FakeSmartTransport(BaseTransport):
149
149
  if child["device_id"] == device_id:
150
150
  info = child
151
151
  break
152
+ # Create the child_devices fixture section for fixtures generated before it was added
153
+ if "child_devices" not in self.info:
154
+ self.info["child_devices"] = {}
155
+ # Get the method calls made directly on the child devices
156
+ child_device_calls = self.info["child_devices"].setdefault(device_id, {})
152
157
 
153
158
  # We only support get & set device info for now.
154
159
  if child_method == "get_device_info":
@@ -159,14 +164,27 @@ class FakeSmartTransport(BaseTransport):
159
164
  return {"error_code": 0}
160
165
  elif child_method == "set_preset_rules":
161
166
  return self._set_child_preset_rules(info, child_params)
167
+ elif child_method in child_device_calls:
168
+ result = copy.deepcopy(child_device_calls[child_method])
169
+ return {"result": result, "error_code": 0}
162
170
  elif (
163
171
  # FIXTURE_MISSING is for service calls not in place when
164
172
  # SMART fixtures started to be generated
165
173
  missing_result := self.FIXTURE_MISSING_MAP.get(child_method)
166
174
  ) and missing_result[0] in self.components:
167
- result = copy.deepcopy(missing_result[1])
175
+ # Copy to info so it will work with update methods
176
+ child_device_calls[child_method] = copy.deepcopy(missing_result[1])
177
+ result = copy.deepcopy(info[child_method])
168
178
  retval = {"result": result, "error_code": 0}
169
179
  return retval
180
+ elif child_method[:4] == "set_":
181
+ target_method = f"get_{child_method[4:]}"
182
+ if target_method not in child_device_calls:
183
+ raise RuntimeError(
184
+ f"No {target_method} in child info, calling set before get not supported."
185
+ )
186
+ child_device_calls[target_method].update(child_params)
187
+ return {"error_code": 0}
170
188
  else:
171
189
  # PARAMS error returned for KS240 when get_device_usage called
172
190
  # on parent device. Could be any error code though.