python-kasa 0.7.0.dev3__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.
@@ -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
@@ -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]
@@ -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.