python-kasa 0.7.0.dev0__py3-none-any.whl → 0.7.0.dev2__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 (49) hide show
  1. kasa/__init__.py +19 -10
  2. kasa/aestransport.py +0 -3
  3. kasa/cli.py +12 -10
  4. kasa/device.py +34 -3
  5. kasa/deviceconfig.py +45 -20
  6. kasa/discover.py +106 -46
  7. kasa/feature.py +2 -1
  8. kasa/httpclient.py +24 -0
  9. kasa/interfaces/light.py +6 -1
  10. kasa/iot/iotbulb.py +3 -0
  11. kasa/iot/iotdevice.py +20 -1
  12. kasa/iot/iotdimmer.py +3 -0
  13. kasa/iot/iotlightstrip.py +3 -2
  14. kasa/iot/iotplug.py +1 -1
  15. kasa/iot/iotstrip.py +1 -1
  16. kasa/iot/modules/light.py +46 -4
  17. kasa/iot/modules/lightpreset.py +6 -1
  18. kasa/smart/modules/autooff.py +13 -8
  19. kasa/smart/modules/light.py +28 -1
  20. kasa/smartprotocol.py +3 -1
  21. kasa/tests/device_fixtures.py +10 -1
  22. kasa/tests/discovery_fixtures.py +82 -29
  23. kasa/tests/fakeprotocol_iot.py +30 -7
  24. kasa/tests/fixtures/HS110(EU)_1.0_1.2.5.json +1 -1
  25. kasa/tests/fixtures/HS110(US)_1.0_1.2.6.json +37 -0
  26. kasa/tests/fixtures/HS220(US)_1.0_1.5.7.json +1 -1
  27. kasa/tests/fixtures/HS220(US)_2.0_1.0.3.json +1 -1
  28. kasa/tests/fixtures/HS300(US)_1.0_1.0.21.json +89 -0
  29. kasa/tests/fixtures/KL120(US)_1.0_1.8.11.json +85 -0
  30. kasa/tests/fixtures/KL430(US)_1.0_1.0.10.json +51 -12
  31. kasa/tests/fixtures/KP303(UK)_1.0_1.0.3.json +1 -1
  32. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +1 -1
  33. kasa/tests/fixtures/smart/P115(EU)_1.0_1.2.3.json +386 -0
  34. kasa/tests/fixtures/smart/S505D(US)_1.0_1.1.0.json +262 -0
  35. kasa/tests/smart/modules/test_autooff.py +103 -0
  36. kasa/tests/test_aestransport.py +78 -2
  37. kasa/tests/test_bulb.py +10 -5
  38. kasa/tests/test_common_modules.py +28 -2
  39. kasa/tests/test_device.py +28 -6
  40. kasa/tests/test_device_factory.py +8 -8
  41. kasa/tests/test_dimmer.py +9 -9
  42. kasa/tests/test_discovery.py +61 -4
  43. kasa/tests/test_readme_examples.py +37 -22
  44. kasa/tests/test_smartprotocol.py +3 -2
  45. {python_kasa-0.7.0.dev0.dist-info → python_kasa-0.7.0.dev2.dist-info}/METADATA +4 -4
  46. {python_kasa-0.7.0.dev0.dist-info → python_kasa-0.7.0.dev2.dist-info}/RECORD +49 -43
  47. {python_kasa-0.7.0.dev0.dist-info → python_kasa-0.7.0.dev2.dist-info}/LICENSE +0 -0
  48. {python_kasa-0.7.0.dev0.dist-info → python_kasa-0.7.0.dev2.dist-info}/WHEEL +0 -0
  49. {python_kasa-0.7.0.dev0.dist-info → python_kasa-0.7.0.dev2.dist-info}/entry_points.txt +0 -0
kasa/iot/iotdevice.py CHANGED
@@ -105,7 +105,7 @@ class IotDevice(Device):
105
105
  All devices provide several informational properties:
106
106
 
107
107
  >>> dev.alias
108
- Kitchen
108
+ Bedroom Lamp Plug
109
109
  >>> dev.model
110
110
  HS110(EU)
111
111
  >>> dev.rssi
@@ -323,6 +323,18 @@ class IotDevice(Device):
323
323
  """Initialize modules not added in init."""
324
324
 
325
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
+ )
326
338
  self._add_feature(
327
339
  Feature(
328
340
  device=self,
@@ -634,6 +646,13 @@ class IotDevice(Device):
634
646
  """Return True if the device is on."""
635
647
  raise NotImplementedError("Device subclass needs to implement this.")
636
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
+
637
656
  @property # type: ignore
638
657
  @requires_update
639
658
  def on_since(self) -> datetime | None:
kasa/iot/iotdimmer.py CHANGED
@@ -168,6 +168,9 @@ class IotDimmer(IotPlug):
168
168
  if not 0 <= brightness <= 100:
169
169
  raise ValueError("Brightness value %s is not valid." % brightness)
170
170
 
171
+ # If zero set to 1 millisecond
172
+ if transition == 0:
173
+ transition = 1
171
174
  if not isinstance(transition, int):
172
175
  raise ValueError(
173
176
  "Transition must be integer, " "not of %s.", type(transition)
kasa/iot/iotlightstrip.py CHANGED
@@ -23,7 +23,7 @@ class IotLightStrip(IotBulb):
23
23
  >>> strip = IotLightStrip("127.0.0.1")
24
24
  >>> asyncio.run(strip.update())
25
25
  >>> print(strip.alias)
26
- KL430 pantry lightstrip
26
+ Bedroom Lightstrip
27
27
 
28
28
  Getting the length of the strip:
29
29
 
@@ -33,7 +33,8 @@ class IotLightStrip(IotBulb):
33
33
  Currently active effect:
34
34
 
35
35
  >>> strip.effect
36
- {'brightness': 50, 'custom': 0, 'enable': 0, 'id': '', 'name': ''}
36
+ {'brightness': 100, 'custom': 0, 'enable': 0,
37
+ 'id': 'bCTItKETDFfrKANolgldxfgOakaarARs', 'name': 'Flicker'}
37
38
 
38
39
  .. note::
39
40
  The device supports some features that are not currently implemented,
kasa/iot/iotplug.py CHANGED
@@ -32,7 +32,7 @@ class IotPlug(IotDevice):
32
32
  >>> plug = IotPlug("127.0.0.1")
33
33
  >>> asyncio.run(plug.update())
34
34
  >>> plug.alias
35
- Kitchen
35
+ Bedroom Lamp Plug
36
36
 
37
37
  Setting the LED state:
38
38
 
kasa/iot/iotstrip.py CHANGED
@@ -55,7 +55,7 @@ class IotStrip(IotDevice):
55
55
  >>> strip = IotStrip("127.0.0.1")
56
56
  >>> asyncio.run(strip.update())
57
57
  >>> strip.alias
58
- TP-LINK_Power Strip_CF69
58
+ Bedroom Power Strip
59
59
 
60
60
  All methods act on the whole strip:
61
61
 
kasa/iot/modules/light.py CHANGED
@@ -25,6 +25,7 @@ class Light(IotModule, LightInterface):
25
25
  """Implementation of brightness module."""
26
26
 
27
27
  _device: IotBulb | IotDimmer
28
+ _light_state: LightState
28
29
 
29
30
  def _initialize_features(self):
30
31
  """Initialize features."""
@@ -102,12 +103,14 @@ class Light(IotModule, LightInterface):
102
103
  async def set_brightness(
103
104
  self, brightness: int, *, transition: int | None = None
104
105
  ) -> dict:
105
- """Set the brightness in percentage.
106
+ """Set the brightness in percentage. A value of 0 will turn off the light.
106
107
 
107
108
  :param int brightness: brightness in percent
108
109
  :param int transition: transition in milliseconds.
109
110
  """
110
- return await self._device._set_brightness(brightness, transition=transition)
111
+ return await self.set_state(
112
+ LightState(brightness=brightness, transition=transition)
113
+ )
111
114
 
112
115
  @property
113
116
  def is_color(self) -> bool:
@@ -202,15 +205,54 @@ class Light(IotModule, LightInterface):
202
205
 
203
206
  async def set_state(self, state: LightState) -> dict:
204
207
  """Set the light state."""
205
- if (bulb := self._get_bulb_device()) is None:
206
- return await self.set_brightness(state.brightness or 0)
208
+ # iot protocol Dimmers and smart protocol devices do not support
209
+ # brightness of 0 so 0 will turn off all devices for consistency
210
+ if (bulb := self._get_bulb_device()) is None: # Dimmer
211
+ if state.brightness == 0 or state.light_on is False:
212
+ return await self._device.turn_off(transition=state.transition)
213
+ elif state.brightness:
214
+ # set_dimmer_transition will turn on the device
215
+ return await self._device.set_dimmer_transition(
216
+ state.brightness, state.transition or 0
217
+ )
218
+ return await self._device.turn_on(transition=state.transition)
207
219
  else:
208
220
  transition = state.transition
209
221
  state_dict = asdict(state)
210
222
  state_dict = {k: v for k, v in state_dict.items() if v is not None}
223
+ if "transition" in state_dict:
224
+ del state_dict["transition"]
211
225
  state_dict["on_off"] = 1 if state.light_on is None else int(state.light_on)
226
+ if state_dict.get("brightness") == 0:
227
+ state_dict["on_off"] = 0
228
+ del state_dict["brightness"]
229
+ # If light on state not set default to on.
230
+ elif state.light_on is None:
231
+ state_dict["on_off"] = 1
232
+ else:
233
+ state_dict["on_off"] = int(state.light_on)
212
234
  return await bulb._set_light_state(state_dict, transition=transition)
213
235
 
236
+ @property
237
+ def state(self) -> LightState:
238
+ """Return the current light state."""
239
+ return self._light_state
240
+
241
+ def _post_update_hook(self) -> None:
242
+ if self._device.is_on is False:
243
+ state = LightState(light_on=False)
244
+ else:
245
+ state = LightState(light_on=True)
246
+ if self.is_dimmable:
247
+ state.brightness = self.brightness
248
+ if self.is_color:
249
+ hsv = self.hsv
250
+ state.hue = hsv.hue
251
+ state.saturation = hsv.saturation
252
+ if self.is_variable_color_temp:
253
+ state.color_temp = self.color_temp
254
+ self._light_state = state
255
+
214
256
  async def _deprecated_set_light_state(
215
257
  self, state: dict, *, transition: int | None = None
216
258
  ) -> dict:
@@ -45,6 +45,9 @@ class LightPreset(IotModule, LightPresetInterface):
45
45
  self._presets = {
46
46
  f"Light preset {index+1}": IotLightPreset(**vals)
47
47
  for index, vals in enumerate(self.data["preferred_state"])
48
+ # Devices may list some light effects along with normal presets but these
49
+ # are handled by the LightEffect module so exclude preferred states with id
50
+ if "id" not in vals
48
51
  }
49
52
  self._preset_list = [self.PRESET_NOT_SET]
50
53
  self._preset_list.extend(self._presets.keys())
@@ -133,7 +136,9 @@ class LightPreset(IotModule, LightPresetInterface):
133
136
  def _deprecated_presets(self) -> list[IotLightPreset]:
134
137
  """Return a list of available bulb setting presets."""
135
138
  return [
136
- IotLightPreset(**vals) for vals in self._device.sys_info["preferred_state"]
139
+ IotLightPreset(**vals)
140
+ for vals in self._device.sys_info["preferred_state"]
141
+ if "id" not in vals
137
142
  ]
138
143
 
139
144
  async def _deprecated_save_preset(self, preset: IotLightPreset):
@@ -2,14 +2,13 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import logging
5
6
  from datetime import datetime, timedelta
6
- from typing import TYPE_CHECKING
7
7
 
8
8
  from ...feature import Feature
9
9
  from ..smartmodule import SmartModule
10
10
 
11
- if TYPE_CHECKING:
12
- from ..smartdevice import SmartDevice
11
+ _LOGGER = logging.getLogger(__name__)
13
12
 
14
13
 
15
14
  class AutoOff(SmartModule):
@@ -18,11 +17,17 @@ class AutoOff(SmartModule):
18
17
  REQUIRED_COMPONENT = "auto_off"
19
18
  QUERY_GETTER_NAME = "get_auto_off_config"
20
19
 
21
- def __init__(self, device: SmartDevice, module: str):
22
- super().__init__(device, module)
20
+ def _initialize_features(self):
21
+ """Initialize features after the initial update."""
22
+ if not isinstance(self.data, dict):
23
+ _LOGGER.warning(
24
+ "No data available for module, skipping %s: %s", self, self.data
25
+ )
26
+ return
27
+
23
28
  self._add_feature(
24
29
  Feature(
25
- device,
30
+ self._device,
26
31
  id="auto_off_enabled",
27
32
  name="Auto off enabled",
28
33
  container=self,
@@ -33,7 +38,7 @@ class AutoOff(SmartModule):
33
38
  )
34
39
  self._add_feature(
35
40
  Feature(
36
- device,
41
+ self._device,
37
42
  id="auto_off_minutes",
38
43
  name="Auto off minutes",
39
44
  container=self,
@@ -44,7 +49,7 @@ class AutoOff(SmartModule):
44
49
  )
45
50
  self._add_feature(
46
51
  Feature(
47
- device,
52
+ self._device,
48
53
  id="auto_off_at",
49
54
  name="Auto off at",
50
55
  container=self,
@@ -14,6 +14,8 @@ from ..smartmodule import SmartModule
14
14
  class Light(SmartModule, LightInterface):
15
15
  """Implementation of a light."""
16
16
 
17
+ _light_state: LightState
18
+
17
19
  def query(self) -> dict:
18
20
  """Query to execute during the update cycle."""
19
21
  return {}
@@ -131,9 +133,34 @@ class Light(SmartModule, LightInterface):
131
133
  """Set the light state."""
132
134
  state_dict = asdict(state)
133
135
  # brightness of 0 turns off the light, it's not a valid brightness
134
- if state.brightness and state.brightness == 0:
136
+ if state.brightness == 0:
135
137
  state_dict["device_on"] = False
136
138
  del state_dict["brightness"]
139
+ elif state.light_on is not None:
140
+ state_dict["device_on"] = state.light_on
141
+ del state_dict["light_on"]
142
+ else:
143
+ state_dict["device_on"] = True
137
144
 
138
145
  params = {k: v for k, v in state_dict.items() if v is not None}
139
146
  return await self.call("set_device_info", params)
147
+
148
+ @property
149
+ def state(self) -> LightState:
150
+ """Return the current light state."""
151
+ return self._light_state
152
+
153
+ def _post_update_hook(self) -> None:
154
+ if self._device.is_on is False:
155
+ state = LightState(light_on=False)
156
+ else:
157
+ state = LightState(light_on=True)
158
+ if self.is_dimmable:
159
+ state.brightness = self.brightness
160
+ if self.is_color:
161
+ hsv = self.hsv
162
+ state.hue = hsv.hue
163
+ state.saturation = hsv.saturation
164
+ if self.is_variable_color_temp:
165
+ state.color_temp = self.color_temp
166
+ self._light_state = state
kasa/smartprotocol.py CHANGED
@@ -402,7 +402,9 @@ class _ChildProtocolWrapper(SmartProtocol):
402
402
  ret_val = {}
403
403
  for multi_response in multi_responses:
404
404
  method = multi_response["method"]
405
- self._handle_response_error_code(multi_response, method)
405
+ self._handle_response_error_code(
406
+ multi_response, method, raise_on_error=False
407
+ )
406
408
  ret_val[method] = multi_response.get("result")
407
409
  return ret_val
408
410
 
@@ -75,6 +75,7 @@ PLUGS_IOT = {
75
75
  PLUGS_SMART = {
76
76
  "P100",
77
77
  "P110",
78
+ "P115",
78
79
  "KP125M",
79
80
  "EP25",
80
81
  "P125M",
@@ -95,6 +96,7 @@ SWITCHES_SMART = {
95
96
  "KS240",
96
97
  "S500D",
97
98
  "S505",
99
+ "S505D",
98
100
  }
99
101
  SWITCHES = {*SWITCHES_IOT, *SWITCHES_SMART}
100
102
  STRIPS_IOT = {"HS107", "HS300", "KP303", "KP200", "KP400", "EP40"}
@@ -113,7 +115,7 @@ SENSORS_SMART = {"T310", "T315", "T300", "T110"}
113
115
  THERMOSTATS_SMART = {"KE100"}
114
116
 
115
117
  WITH_EMETER_IOT = {"HS110", "HS300", "KP115", "KP125", *BULBS_IOT}
116
- WITH_EMETER_SMART = {"P110", "KP125M", "EP25"}
118
+ WITH_EMETER_SMART = {"P110", "P115", "KP125M", "EP25"}
117
119
  WITH_EMETER = {*WITH_EMETER_IOT, *WITH_EMETER_SMART}
118
120
 
119
121
  DIMMABLE = {*BULBS, *DIMMERS}
@@ -396,6 +398,13 @@ async def get_device_for_fixture_protocol(fixture, protocol):
396
398
  return await get_device_for_fixture(fixture_info)
397
399
 
398
400
 
401
+ def get_fixture_info(fixture, protocol):
402
+ finfo = FixtureInfo(name=fixture, protocol=protocol, data={})
403
+ for fixture_info in FIXTURE_DATA:
404
+ if finfo == fixture_info:
405
+ return fixture_info
406
+
407
+
399
408
  @pytest.fixture(params=filter_fixtures("main devices"), ids=idgenerator)
400
409
  async def dev(request) -> AsyncGenerator[Device, None]:
401
410
  """Device fixture.
@@ -44,9 +44,14 @@ UNSUPPORTED_DEVICES = {
44
44
  }
45
45
 
46
46
 
47
- def parametrize_discovery(desc, *, data_root_filter, protocol_filter=None):
47
+ def parametrize_discovery(
48
+ desc, *, data_root_filter=None, protocol_filter=None, model_filter=None
49
+ ):
48
50
  filtered_fixtures = filter_fixtures(
49
- desc, data_root_filter=data_root_filter, protocol_filter=protocol_filter
51
+ desc,
52
+ data_root_filter=data_root_filter,
53
+ protocol_filter=protocol_filter,
54
+ model_filter=model_filter,
50
55
  )
51
56
  return pytest.mark.parametrize(
52
57
  "discovery_mock",
@@ -65,10 +70,14 @@ new_discovery = parametrize_discovery(
65
70
  params=filter_fixtures("discoverable", protocol_filter={"SMART", "IOT"}),
66
71
  ids=idgenerator,
67
72
  )
68
- def discovery_mock(request, mocker):
73
+ async def discovery_mock(request, mocker):
69
74
  """Mock discovery and patch protocol queries to use Fake protocols."""
70
75
  fixture_info: FixtureInfo = request.param
71
- fixture_data = fixture_info.data
76
+ yield patch_discovery({"127.0.0.123": fixture_info}, mocker)
77
+
78
+
79
+ def create_discovery_mock(ip: str, fixture_data: dict):
80
+ """Mock discovery and patch protocol queries to use Fake protocols."""
72
81
 
73
82
  @dataclass
74
83
  class _DiscoveryMock:
@@ -79,6 +88,7 @@ def discovery_mock(request, mocker):
79
88
  query_data: dict
80
89
  device_type: str
81
90
  encrypt_type: str
91
+ _datagram: bytes
82
92
  login_version: int | None = None
83
93
  port_override: int | None = None
84
94
 
@@ -94,13 +104,14 @@ def discovery_mock(request, mocker):
94
104
  + json_dumps(discovery_data).encode()
95
105
  )
96
106
  dm = _DiscoveryMock(
97
- "127.0.0.123",
107
+ ip,
98
108
  80,
99
109
  20002,
100
110
  discovery_data,
101
111
  fixture_data,
102
112
  device_type,
103
113
  encrypt_type,
114
+ datagram,
104
115
  login_version,
105
116
  )
106
117
  else:
@@ -111,45 +122,87 @@ def discovery_mock(request, mocker):
111
122
  login_version = None
112
123
  datagram = XorEncryption.encrypt(json_dumps(discovery_data))[4:]
113
124
  dm = _DiscoveryMock(
114
- "127.0.0.123",
125
+ ip,
115
126
  9999,
116
127
  9999,
117
128
  discovery_data,
118
129
  fixture_data,
119
130
  device_type,
120
131
  encrypt_type,
132
+ datagram,
121
133
  login_version,
122
134
  )
123
135
 
136
+ return dm
137
+
138
+
139
+ def patch_discovery(fixture_infos: dict[str, FixtureInfo], mocker):
140
+ """Mock discovery and patch protocol queries to use Fake protocols."""
141
+ discovery_mocks = {
142
+ ip: create_discovery_mock(ip, fixture_info.data)
143
+ for ip, fixture_info in fixture_infos.items()
144
+ }
145
+ protos = {
146
+ ip: FakeSmartProtocol(fixture_info.data, fixture_info.name)
147
+ if "SMART" in fixture_info.protocol
148
+ else FakeIotProtocol(fixture_info.data, fixture_info.name)
149
+ for ip, fixture_info in fixture_infos.items()
150
+ }
151
+ first_ip = list(fixture_infos.keys())[0]
152
+ first_host = None
153
+
124
154
  async def mock_discover(self):
125
- port = (
126
- dm.port_override
127
- if dm.port_override and dm.discovery_port != 20002
128
- else dm.discovery_port
129
- )
130
- self.datagram_received(
131
- datagram,
132
- (dm.ip, port),
133
- )
155
+ """Call datagram_received for all mock fixtures.
156
+
157
+ Handles test cases modifying the ip and hostname of the first fixture
158
+ for discover_single testing.
159
+ """
160
+ for ip, dm in discovery_mocks.items():
161
+ first_ip = list(discovery_mocks.values())[0].ip
162
+ fixture_info = fixture_infos[ip]
163
+ # Ip of first fixture could have been modified by a test
164
+ if dm.ip == first_ip:
165
+ # hostname could have been used
166
+ host = first_host if first_host else first_ip
167
+ else:
168
+ host = dm.ip
169
+ # update the protos for any host testing or the test overriding the first ip
170
+ protos[host] = (
171
+ FakeSmartProtocol(fixture_info.data, fixture_info.name)
172
+ if "SMART" in fixture_info.protocol
173
+ else FakeIotProtocol(fixture_info.data, fixture_info.name)
174
+ )
175
+ port = (
176
+ dm.port_override
177
+ if dm.port_override and dm.discovery_port != 20002
178
+ else dm.discovery_port
179
+ )
180
+ self.datagram_received(
181
+ dm._datagram,
182
+ (dm.ip, port),
183
+ )
184
+
185
+ async def _query(self, request, retry_count: int = 3):
186
+ return await protos[self._host].query(request)
134
187
 
188
+ def _getaddrinfo(host, *_, **__):
189
+ nonlocal first_host, first_ip
190
+ first_host = host # Store the hostname used by discover single
191
+ first_ip = list(discovery_mocks.values())[
192
+ 0
193
+ ].ip # ip could have been overridden in test
194
+ return [(None, None, None, None, (first_ip, 0))]
195
+
196
+ mocker.patch("kasa.IotProtocol.query", _query)
197
+ mocker.patch("kasa.SmartProtocol.query", _query)
135
198
  mocker.patch("kasa.discover._DiscoverProtocol.do_discover", mock_discover)
136
199
  mocker.patch(
137
200
  "socket.getaddrinfo",
138
- side_effect=lambda *_, **__: [(None, None, None, None, (dm.ip, 0))],
201
+ # side_effect=lambda *_, **__: [(None, None, None, None, (first_ip, 0))],
202
+ side_effect=_getaddrinfo,
139
203
  )
140
-
141
- if "SMART" in fixture_info.protocol:
142
- proto = FakeSmartProtocol(fixture_data, fixture_info.name)
143
- else:
144
- proto = FakeIotProtocol(fixture_data)
145
-
146
- async def _query(request, retry_count: int = 3):
147
- return await proto.query(request)
148
-
149
- mocker.patch("kasa.IotProtocol.query", side_effect=_query)
150
- mocker.patch("kasa.SmartProtocol.query", side_effect=_query)
151
-
152
- yield dm
204
+ # Only return the first discovery mock to be used for testing discover single
205
+ return discovery_mocks[first_ip]
153
206
 
154
207
 
155
208
  @pytest.fixture(
@@ -3,7 +3,7 @@ import logging
3
3
 
4
4
  from ..deviceconfig import DeviceConfig
5
5
  from ..iotprotocol import IotProtocol
6
- from ..xortransport import XorTransport
6
+ from ..protocol import BaseTransport
7
7
 
8
8
  _LOGGER = logging.getLogger(__name__)
9
9
 
@@ -178,17 +178,26 @@ MOTION_MODULE = {
178
178
 
179
179
 
180
180
  class FakeIotProtocol(IotProtocol):
181
- def __init__(self, info):
181
+ def __init__(self, info, fixture_name=None):
182
182
  super().__init__(
183
- transport=XorTransport(
184
- config=DeviceConfig("127.0.0.123"),
185
- )
183
+ transport=FakeIotTransport(info, fixture_name),
186
184
  )
185
+
186
+ async def query(self, request, retry_count: int = 3):
187
+ """Implement query here so tests can still patch IotProtocol.query."""
188
+ resp_dict = await self._query(request, retry_count)
189
+ return resp_dict
190
+
191
+
192
+ class FakeIotTransport(BaseTransport):
193
+ def __init__(self, info, fixture_name=None):
194
+ super().__init__(config=DeviceConfig("127.0.0.123"))
187
195
  info = copy.deepcopy(info)
188
196
  self.discovery_data = info
197
+ self.fixture_name = fixture_name
189
198
  self.writer = None
190
199
  self.reader = None
191
- proto = copy.deepcopy(FakeIotProtocol.baseproto)
200
+ proto = copy.deepcopy(FakeIotTransport.baseproto)
192
201
 
193
202
  for target in info:
194
203
  # print("target %s" % target)
@@ -220,6 +229,14 @@ class FakeIotProtocol(IotProtocol):
220
229
 
221
230
  self.proto = proto
222
231
 
232
+ @property
233
+ def default_port(self) -> int:
234
+ return 9999
235
+
236
+ @property
237
+ def credentials_hash(self) -> str:
238
+ return ""
239
+
223
240
  def set_alias(self, x, child_ids=None):
224
241
  if child_ids is None:
225
242
  child_ids = []
@@ -367,7 +384,7 @@ class FakeIotProtocol(IotProtocol):
367
384
  "smartlife.iot.common.cloud": CLOUD_MODULE,
368
385
  }
369
386
 
370
- async def query(self, request, port=9999):
387
+ async def send(self, request, port=9999):
371
388
  proto = self.proto
372
389
 
373
390
  # collect child ids from context
@@ -414,3 +431,9 @@ class FakeIotProtocol(IotProtocol):
414
431
  response.update(get_response_for_module(target))
415
432
 
416
433
  return copy.deepcopy(response)
434
+
435
+ async def close(self) -> None:
436
+ pass
437
+
438
+ async def reset(self) -> None:
439
+ pass
@@ -11,7 +11,7 @@
11
11
  "system": {
12
12
  "get_sysinfo": {
13
13
  "active_mode": "schedule",
14
- "alias": "Kitchen",
14
+ "alias": "Bedroom Lamp Plug",
15
15
  "dev_name": "Wi-Fi Smart Plug With Energy Monitoring",
16
16
  "deviceId": "0000000000000000000000000000000000000000",
17
17
  "err_code": 0,
@@ -0,0 +1,37 @@
1
+ {
2
+ "emeter": {
3
+ "get_realtime": {
4
+ "current": 0.128037,
5
+ "err_code": 0,
6
+ "power": 7.677094,
7
+ "total": 30.404,
8
+ "voltage": 118.917389
9
+ }
10
+ },
11
+ "system": {
12
+ "get_sysinfo": {
13
+ "active_mode": "schedule",
14
+ "alias": "Home Google WiFi HS110",
15
+ "dev_name": "Wi-Fi Smart Plug With Energy Monitoring",
16
+ "deviceId": "0000000000000000000000000000000000000000",
17
+ "err_code": 0,
18
+ "feature": "TIM:ENE",
19
+ "fwId": "00000000000000000000000000000000",
20
+ "hwId": "00000000000000000000000000000000",
21
+ "hw_ver": "1.0",
22
+ "icon_hash": "",
23
+ "latitude": 0,
24
+ "led_off": 0,
25
+ "longitude": 0,
26
+ "mac": "00:00:00:00:00:00",
27
+ "model": "HS110(US)",
28
+ "oemId": "00000000000000000000000000000000",
29
+ "on_time": 14048150,
30
+ "relay_state": 1,
31
+ "rssi": -38,
32
+ "sw_ver": "1.2.6 Build 200727 Rel.121701",
33
+ "type": "IOT.SMARTPLUGSWITCH",
34
+ "updating": 0
35
+ }
36
+ }
37
+ }
@@ -28,7 +28,7 @@
28
28
  "system": {
29
29
  "get_sysinfo": {
30
30
  "active_mode": "none",
31
- "alias": "Living room left dimmer",
31
+ "alias": "Living Room Dimmer Switch",
32
32
  "brightness": 25,
33
33
  "dev_name": "Smart Wi-Fi Dimmer",
34
34
  "deviceId": "000000000000000000000000000000000000000",
@@ -17,7 +17,7 @@
17
17
  "system": {
18
18
  "get_sysinfo": {
19
19
  "active_mode": "none",
20
- "alias": "Living Room Lights",
20
+ "alias": "Living Room Dimmer Switch",
21
21
  "brightness": 100,
22
22
  "dev_name": "Wi-Fi Smart Dimmer",
23
23
  "deviceId": "0000000000000000000000000000000000000000",