python-kasa 0.7.0.dev3__py3-none-any.whl → 0.7.0.dev5__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 (38) hide show
  1. kasa/cli.py +58 -22
  2. kasa/device.py +21 -31
  3. kasa/feature.py +5 -4
  4. kasa/interfaces/__init__.py +2 -0
  5. kasa/interfaces/energy.py +181 -0
  6. kasa/iot/iotbulb.py +1 -1
  7. kasa/iot/iotdevice.py +26 -101
  8. kasa/iot/iotstrip.py +112 -60
  9. kasa/iot/modules/emeter.py +30 -89
  10. kasa/iot/modules/led.py +5 -0
  11. kasa/module.py +2 -3
  12. kasa/smart/modules/autooff.py +8 -0
  13. kasa/smart/modules/energy.py +58 -60
  14. kasa/smart/modules/lightpreset.py +10 -0
  15. kasa/smart/modules/lightstripeffect.py +14 -4
  16. kasa/smart/modules/lighttransition.py +10 -0
  17. kasa/smart/modules/time.py +7 -1
  18. kasa/smart/smartchilddevice.py +12 -1
  19. kasa/smart/smartdevice.py +34 -74
  20. kasa/tests/device_fixtures.py +31 -0
  21. kasa/tests/fakeprotocol_smart.py +19 -1
  22. kasa/tests/fixtures/smart/L920-5(EU)_1.0_1.0.7.json +350 -0
  23. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.15.json +966 -0
  24. kasa/tests/smart/features/test_brightness.py +3 -3
  25. kasa/tests/smart/modules/test_autooff.py +8 -8
  26. kasa/tests/smart/modules/test_fan.py +6 -7
  27. kasa/tests/test_childdevice.py +19 -1
  28. kasa/tests/test_cli.py +37 -5
  29. kasa/tests/test_common_modules.py +8 -7
  30. kasa/tests/test_device.py +14 -6
  31. kasa/tests/test_emeter.py +36 -8
  32. kasa/tests/test_iotdevice.py +9 -2
  33. kasa/tests/test_smartdevice.py +11 -7
  34. {python_kasa-0.7.0.dev3.dist-info → python_kasa-0.7.0.dev5.dist-info}/METADATA +1 -1
  35. {python_kasa-0.7.0.dev3.dist-info → python_kasa-0.7.0.dev5.dist-info}/RECORD +38 -35
  36. {python_kasa-0.7.0.dev3.dist-info → python_kasa-0.7.0.dev5.dist-info}/LICENSE +0 -0
  37. {python_kasa-0.7.0.dev3.dist-info → python_kasa-0.7.0.dev5.dist-info}/WHEEL +0 -0
  38. {python_kasa-0.7.0.dev3.dist-info → python_kasa-0.7.0.dev5.dist-info}/entry_points.txt +0 -0
kasa/iot/modules/led.py CHANGED
@@ -30,3 +30,8 @@ class Led(IotModule, LedInterface):
30
30
  async def set_led(self, state: bool):
31
31
  """Set the state of the led (night mode)."""
32
32
  return await self.call("set_led_off", {"off": int(not state)})
33
+
34
+ @property
35
+ def is_supported(self) -> bool:
36
+ """Return whether the module is supported by the device."""
37
+ return "led_off" in self.data
kasa/module.py CHANGED
@@ -33,6 +33,8 @@ class Module(ABC):
33
33
  """
34
34
 
35
35
  # Common Modules
36
+ Energy: Final[ModuleName[interfaces.Energy]] = ModuleName("Energy")
37
+ Fan: Final[ModuleName[interfaces.Fan]] = ModuleName("Fan")
36
38
  LightEffect: Final[ModuleName[interfaces.LightEffect]] = ModuleName("LightEffect")
37
39
  Led: Final[ModuleName[interfaces.Led]] = ModuleName("Led")
38
40
  Light: Final[ModuleName[interfaces.Light]] = ModuleName("Light")
@@ -42,7 +44,6 @@ class Module(ABC):
42
44
  IotAmbientLight: Final[ModuleName[iot.AmbientLight]] = ModuleName("ambient")
43
45
  IotAntitheft: Final[ModuleName[iot.Antitheft]] = ModuleName("anti_theft")
44
46
  IotCountdown: Final[ModuleName[iot.Countdown]] = ModuleName("countdown")
45
- IotEmeter: Final[ModuleName[iot.Emeter]] = ModuleName("emeter")
46
47
  IotMotion: Final[ModuleName[iot.Motion]] = ModuleName("motion")
47
48
  IotSchedule: Final[ModuleName[iot.Schedule]] = ModuleName("schedule")
48
49
  IotUsage: Final[ModuleName[iot.Usage]] = ModuleName("usage")
@@ -62,8 +63,6 @@ class Module(ABC):
62
63
  )
63
64
  ContactSensor: Final[ModuleName[smart.ContactSensor]] = ModuleName("ContactSensor")
64
65
  DeviceModule: Final[ModuleName[smart.DeviceModule]] = ModuleName("DeviceModule")
65
- Energy: Final[ModuleName[smart.Energy]] = ModuleName("Energy")
66
- Fan: Final[ModuleName[smart.Fan]] = ModuleName("Fan")
67
66
  Firmware: Final[ModuleName[smart.Firmware]] = ModuleName("Firmware")
68
67
  FrostProtection: Final[ModuleName[smart.FrostProtection]] = ModuleName(
69
68
  "FrostProtection"
@@ -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
@@ -2,60 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING
6
-
7
5
  from ...emeterstatus import EmeterStatus
8
- from ...feature import Feature
6
+ from ...exceptions import KasaException
7
+ from ...interfaces.energy import Energy as EnergyInterface
9
8
  from ..smartmodule import SmartModule
10
9
 
11
- if TYPE_CHECKING:
12
- from ..smartdevice import SmartDevice
13
-
14
10
 
15
- class Energy(SmartModule):
11
+ class Energy(SmartModule, EnergyInterface):
16
12
  """Implementation of energy monitoring module."""
17
13
 
18
14
  REQUIRED_COMPONENT = "energy_monitoring"
19
15
 
20
- def __init__(self, device: SmartDevice, module: str):
21
- super().__init__(device, module)
22
- self._add_feature(
23
- Feature(
24
- device,
25
- "consumption_current",
26
- name="Current consumption",
27
- attribute_getter="current_power",
28
- container=self,
29
- unit="W",
30
- precision_hint=1,
31
- category=Feature.Category.Primary,
32
- )
33
- )
34
- self._add_feature(
35
- Feature(
36
- device,
37
- "consumption_today",
38
- name="Today's consumption",
39
- attribute_getter="emeter_today",
40
- container=self,
41
- unit="Wh",
42
- precision_hint=2,
43
- category=Feature.Category.Info,
44
- )
45
- )
46
- self._add_feature(
47
- Feature(
48
- device,
49
- "consumption_this_month",
50
- name="This month's consumption",
51
- attribute_getter="emeter_this_month",
52
- container=self,
53
- unit="Wh",
54
- precision_hint=2,
55
- category=Feature.Category.Info,
56
- )
57
- )
58
-
59
16
  def query(self) -> dict:
60
17
  """Query to execute during the update cycle."""
61
18
  req = {
@@ -66,9 +23,9 @@ class Energy(SmartModule):
66
23
  return req
67
24
 
68
25
  @property
69
- def current_power(self) -> float | None:
26
+ def current_consumption(self) -> float | None:
70
27
  """Current power in watts."""
71
- if power := self.energy.get("current_power"):
28
+ if (power := self.energy.get("current_power")) is not None:
72
29
  return power / 1_000
73
30
  return None
74
31
 
@@ -79,23 +36,64 @@ class Energy(SmartModule):
79
36
  return en
80
37
  return self.data
81
38
 
82
- @property
83
- def emeter_realtime(self):
84
- """Get the emeter status."""
85
- # TODO: Perhaps we should get rid of emeterstatus altogether for smartdevices
39
+ def _get_status_from_energy(self, energy) -> EmeterStatus:
86
40
  return EmeterStatus(
87
41
  {
88
- "power_mw": self.energy.get("current_power"),
89
- "total": self.energy.get("today_energy") / 1_000,
42
+ "power_mw": energy.get("current_power"),
43
+ "total": energy.get("today_energy") / 1_000,
90
44
  }
91
45
  )
92
46
 
93
47
  @property
94
- def emeter_this_month(self) -> float | None:
95
- """Get the emeter value for this month."""
96
- return self.energy.get("month_energy")
48
+ def status(self):
49
+ """Get the emeter status."""
50
+ return self._get_status_from_energy(self.energy)
51
+
52
+ async def get_status(self):
53
+ """Return real-time statistics."""
54
+ res = await self.call("get_energy_usage")
55
+ return self._get_status_from_energy(res["get_energy_usage"])
56
+
57
+ @property
58
+ def consumption_this_month(self) -> float | None:
59
+ """Get the emeter value for this month in kWh."""
60
+ return self.energy.get("month_energy") / 1_000
61
+
62
+ @property
63
+ def consumption_today(self) -> float | None:
64
+ """Get the emeter value for today in kWh."""
65
+ return self.energy.get("today_energy") / 1_000
66
+
67
+ @property
68
+ def consumption_total(self) -> float | None:
69
+ """Return total consumption since last reboot in kWh."""
70
+ return None
71
+
72
+ @property
73
+ def current(self) -> float | None:
74
+ """Return the current in A."""
75
+ return None
97
76
 
98
77
  @property
99
- def emeter_today(self) -> float | None:
100
- """Get the emeter value for today."""
101
- return self.energy.get("today_energy")
78
+ def voltage(self) -> float | None:
79
+ """Get the current voltage in V."""
80
+ return None
81
+
82
+ async def _deprecated_get_realtime(self) -> EmeterStatus:
83
+ """Retrieve current energy readings."""
84
+ return self.status
85
+
86
+ async def erase_stats(self):
87
+ """Erase all stats."""
88
+ raise KasaException("Device does not support periodic statistics")
89
+
90
+ async def get_daily_stats(self, *, year=None, month=None, kwh=True) -> dict:
91
+ """Return daily stats for the given year & month.
92
+
93
+ The return value is a dictionary of {day: energy, ...}.
94
+ """
95
+ raise KasaException("Device does not support periodic statistics")
96
+
97
+ async def get_monthly_stats(self, *, year=None, kwh=True) -> dict:
98
+ """Return monthly stats for the given year."""
99
+ raise KasaException("Device does not support periodic statistics")
@@ -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
@@ -2,16 +2,27 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from typing import TYPE_CHECKING
6
+
5
7
  from ...interfaces.lighteffect import LightEffect as LightEffectInterface
6
8
  from ..effects import EFFECT_MAPPING, EFFECT_NAMES
7
9
  from ..smartmodule import SmartModule
8
10
 
11
+ if TYPE_CHECKING:
12
+ from ..smartdevice import SmartDevice
13
+
9
14
 
10
15
  class LightStripEffect(SmartModule, LightEffectInterface):
11
16
  """Implementation of dynamic light effects."""
12
17
 
13
18
  REQUIRED_COMPONENT = "light_strip_lighting_effect"
14
19
 
20
+ def __init__(self, device: SmartDevice, module: str):
21
+ super().__init__(device, module)
22
+ effect_list = [self.LIGHT_EFFECTS_OFF]
23
+ effect_list.extend(EFFECT_NAMES)
24
+ self._effect_list = effect_list
25
+
15
26
  @property
16
27
  def name(self) -> str:
17
28
  """Name of the module.
@@ -37,7 +48,8 @@ class LightStripEffect(SmartModule, LightEffectInterface):
37
48
  """
38
49
  eff = self.data["lighting_effect"]
39
50
  name = eff["name"]
40
- if eff["enable"]:
51
+ # When devices are unpaired effect name is softAP which is not in our list
52
+ if eff["enable"] and name in self._effect_list:
41
53
  return name
42
54
  return self.LIGHT_EFFECTS_OFF
43
55
 
@@ -48,9 +60,7 @@ class LightStripEffect(SmartModule, LightEffectInterface):
48
60
  Example:
49
61
  ['Aurora', 'Bubbling Cauldron', ...]
50
62
  """
51
- effect_list = [self.LIGHT_EFFECTS_OFF]
52
- effect_list.extend(EFFECT_NAMES)
53
- return effect_list
63
+ return self._effect_list
54
64
 
55
65
  async def set_effect(
56
66
  self,
@@ -181,3 +181,13 @@ class LightTransition(SmartModule):
181
181
  return {}
182
182
  else:
183
183
  return {self.QUERY_GETTER_NAME: None}
184
+
185
+ async def _check_supported(self):
186
+ """Additional check to see if the module is supported by the device.
187
+
188
+ Parent devices that report components of children such as ks240 will not have
189
+ the brightness value is sysinfo.
190
+ """
191
+ # Look in _device.sys_info here because self.data is either sys_info or
192
+ # get_preset_rules depending on whether it's a child device or not.
193
+ return "brightness" in self._device.sys_info
@@ -51,7 +51,13 @@ class Time(SmartModule):
51
51
  async def set_time(self, dt: datetime):
52
52
  """Set device time."""
53
53
  unixtime = mktime(dt.timetuple())
54
+ offset = cast(timedelta, dt.utcoffset())
55
+ diff = offset / timedelta(minutes=1)
54
56
  return await self.call(
55
57
  "set_device_time",
56
- {"timestamp": unixtime, "time_diff": dt.utcoffset(), "region": dt.tzname()},
58
+ {
59
+ "timestamp": int(unixtime),
60
+ "time_diff": int(diff),
61
+ "region": dt.tzname(),
62
+ },
57
63
  )
@@ -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
@@ -4,14 +4,13 @@ from __future__ import annotations
4
4
 
5
5
  import base64
6
6
  import logging
7
- from datetime import datetime, timedelta
7
+ from datetime import datetime, timedelta, timezone
8
8
  from typing import TYPE_CHECKING, Any, Mapping, Sequence, cast
9
9
 
10
10
  from ..aestransport import AesTransport
11
11
  from ..device import Device, WifiNetwork
12
12
  from ..device_type import DeviceType
13
13
  from ..deviceconfig import DeviceConfig
14
- from ..emeterstatus import EmeterStatus
15
14
  from ..exceptions import AuthenticationError, DeviceError, KasaException, SmartErrorCode
16
15
  from ..feature import Feature
17
16
  from ..module import Module
@@ -29,11 +28,11 @@ from .smartmodule import SmartModule
29
28
  _LOGGER = logging.getLogger(__name__)
30
29
 
31
30
 
32
- # List of modules that wall switches with children, i.e. ks240 report on
31
+ # List of modules that non hub devices with children, i.e. ks240/P300, report on
33
32
  # the child but only work on the parent. See longer note below in _initialize_modules.
34
33
  # This list should be updated when creating new modules that could have the
35
34
  # same issue, homekit perhaps?
36
- WALL_SWITCH_PARENT_ONLY_MODULES = [DeviceModule, Time, Firmware, Cloud]
35
+ NON_HUB_PARENT_ONLY_MODULES = [DeviceModule, Time, Firmware, Cloud]
37
36
 
38
37
 
39
38
  # Device must go last as the other interfaces also inherit Device
@@ -57,7 +56,6 @@ class SmartDevice(Device):
57
56
  self._components: dict[str, int] = {}
58
57
  self._state_information: dict[str, Any] = {}
59
58
  self._modules: dict[str | ModuleName[Module], SmartModule] = {}
60
- self._exposes_child_modules = False
61
59
  self._parent: SmartDevice | None = None
62
60
  self._children: Mapping[str, SmartDevice] = {}
63
61
  self._last_update = {}
@@ -99,16 +97,6 @@ class SmartDevice(Device):
99
97
  @property
100
98
  def modules(self) -> ModuleMapping[SmartModule]:
101
99
  """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
100
  if TYPE_CHECKING: # Needed for python 3.8
113
101
  return cast(ModuleMapping[SmartModule], self._modules)
114
102
  return self._modules
@@ -160,7 +148,7 @@ class SmartDevice(Device):
160
148
  if "child_device" in self._components and not self.children:
161
149
  await self._initialize_children()
162
150
 
163
- async def update(self, update_children: bool = True):
151
+ async def update(self, update_children: bool = False):
164
152
  """Update the device."""
165
153
  if self.credentials is None and self.credentials_hash is None:
166
154
  raise AuthenticationError("Tapo plug requires authentication.")
@@ -178,9 +166,14 @@ class SmartDevice(Device):
178
166
  self._last_update = resp = await self.protocol.query(req)
179
167
 
180
168
  self._info = self._try_get_response(resp, "get_device_info")
169
+
170
+ # Call child update which will only update module calls, info is updated
171
+ # from get_child_device_list. update_children only affects hub devices, other
172
+ # devices will always update children to prevent errors on module access.
173
+ if update_children or self.device_type != DeviceType.Hub:
174
+ for child in self._children.values():
175
+ await child.update()
181
176
  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
177
  for info in child_info["child_device_list"]:
185
178
  self._children[info["device_id"]]._update_internal_state(info)
186
179
 
@@ -207,21 +200,18 @@ class SmartDevice(Device):
207
200
  # when they need to be accessed through the children.
208
201
  # The logic below ensures that such devices add all but whitelisted, only on
209
202
  # the child device.
203
+ # It also ensures that devices like power strips do not add modules such as
204
+ # firmware to the child devices.
210
205
  skip_parent_only_modules = False
211
206
  child_modules_to_skip = {}
212
- if self._parent and self._parent.device_type == DeviceType.WallSwitch:
207
+ if self._parent and self._parent.device_type != DeviceType.Hub:
213
208
  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
209
 
220
210
  for mod in SmartModule.REGISTERED_MODULES.values():
221
211
  _LOGGER.debug("%s requires %s", mod, mod.REQUIRED_COMPONENT)
222
212
 
223
213
  if (
224
- skip_parent_only_modules and mod in WALL_SWITCH_PARENT_ONLY_MODULES
214
+ skip_parent_only_modules and mod in NON_HUB_PARENT_ONLY_MODULES
225
215
  ) or mod.__name__ in child_modules_to_skip:
226
216
  continue
227
217
  if (
@@ -332,10 +322,7 @@ class SmartDevice(Device):
332
322
  )
333
323
 
334
324
  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()
325
+ module._initialize_features()
339
326
  for feat in module._module_features.values():
340
327
  self._add_feature(feat)
341
328
  for child in self._children.values():
@@ -369,13 +356,25 @@ class SmartDevice(Device):
369
356
  @property
370
357
  def time(self) -> datetime:
371
358
  """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]
359
+ if (self._parent and (time_mod := self._parent.modules.get(Module.Time))) or (
360
+ time_mod := self.modules.get(Module.Time)
361
+ ):
362
+ return time_mod.time
363
+
364
+ # We have no device time, use current local time.
365
+ return datetime.now(timezone.utc).astimezone().replace(microsecond=0)
366
+
367
+ @property
368
+ def on_since(self) -> datetime | None:
369
+ """Return the time that the device was turned on or None if turned off."""
370
+ if (
371
+ not self._info.get("device_on")
372
+ or (on_time := self._info.get("on_time")) is None
373
+ ):
374
+ return None
377
375
 
378
- return _timemod.time
376
+ on_time = cast(float, on_time)
377
+ return self.time - timedelta(seconds=on_time)
379
378
 
380
379
  @property
381
380
  def timezone(self) -> dict:
@@ -477,45 +476,6 @@ class SmartDevice(Device):
477
476
  self._discovery_info = info
478
477
  self._info = info
479
478
 
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
479
  async def wifi_scan(self) -> list[WifiNetwork]:
520
480
  """Scan for available wifi networks."""
521
481
 
@@ -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.