python-kasa 0.6.2.1__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 (164) 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 +7 -5
  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 -562
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/fakeprotocol_iot.py +64 -6
  86. kasa/tests/fakeprotocol_smart.py +215 -22
  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/child/KE100(EU)_1.0_2.4.0.json +170 -0
  99. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  100. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  101. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  102. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  103. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  104. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  105. kasa/tests/smart/__init__.py +0 -0
  106. kasa/tests/smart/features/__init__.py +0 -0
  107. kasa/tests/smart/features/test_brightness.py +55 -0
  108. kasa/tests/smart/features/test_colortemp.py +30 -0
  109. kasa/tests/smart/modules/__init__.py +0 -0
  110. kasa/tests/smart/modules/test_contact.py +28 -0
  111. kasa/tests/smart/modules/test_fan.py +79 -0
  112. kasa/tests/smart/modules/test_firmware.py +108 -0
  113. kasa/tests/smart/modules/test_humidity.py +28 -0
  114. kasa/tests/smart/modules/test_light_effect.py +41 -0
  115. kasa/tests/smart/modules/test_temperature.py +47 -0
  116. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  117. kasa/tests/smart/modules/test_waterleak.py +42 -0
  118. kasa/tests/test_aestransport.py +115 -23
  119. kasa/tests/test_bulb.py +115 -85
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +216 -0
  123. kasa/tests/test_device.py +268 -0
  124. kasa/tests/test_device_factory.py +61 -35
  125. kasa/tests/test_device_type.py +1 -1
  126. kasa/tests/test_deviceconfig.py +2 -2
  127. kasa/tests/test_dimmer.py +33 -24
  128. kasa/tests/test_discovery.py +112 -63
  129. kasa/tests/test_emeter.py +14 -10
  130. kasa/tests/test_feature.py +205 -0
  131. kasa/tests/test_httpclient.py +9 -9
  132. kasa/tests/test_iotdevice.py +286 -0
  133. kasa/tests/test_klapprotocol.py +94 -37
  134. kasa/tests/test_lightstrip.py +24 -19
  135. kasa/tests/test_plug.py +46 -8
  136. kasa/tests/test_protocol.py +8 -10
  137. kasa/tests/test_readme_examples.py +87 -26
  138. kasa/tests/test_smartdevice.py +203 -311
  139. kasa/tests/test_smartprotocol.py +130 -25
  140. kasa/tests/test_strip.py +15 -6
  141. kasa/tests/test_usage.py +1 -1
  142. kasa/xortransport.py +15 -12
  143. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  145. kasa/modules/emeter.py +0 -111
  146. kasa/smartlightstrip.py +0 -143
  147. kasa/smartplug.py +0 -91
  148. kasa/tapo/__init__.py +0 -7
  149. kasa/tapo/childdevice.py +0 -41
  150. kasa/tapo/tapobulb.py +0 -262
  151. kasa/tapo/tapodevice.py +0 -409
  152. kasa/tapo/tapoplug.py +0 -45
  153. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  154. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  155. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  156. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  157. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  158. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  159. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  160. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  161. python_kasa-0.6.2.1.dist-info/RECORD +0 -167
  162. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -121,6 +121,61 @@ TIME_MODULE = {
121
121
  "set_timezone": None,
122
122
  }
123
123
 
124
+ CLOUD_MODULE = {
125
+ "get_info": {
126
+ "username": "",
127
+ "server": "devs.tplinkcloud.com",
128
+ "binded": 0,
129
+ "cld_connection": 0,
130
+ "illegalType": -1,
131
+ "stopConnect": -1,
132
+ "tcspStatus": -1,
133
+ "fwDlPage": "",
134
+ "tcspInfo": "",
135
+ "fwNotifyType": 0,
136
+ }
137
+ }
138
+
139
+
140
+ AMBIENT_MODULE = {
141
+ "get_current_brt": {"value": 26, "err_code": 0},
142
+ "get_config": {
143
+ "devs": [
144
+ {
145
+ "hw_id": 0,
146
+ "enable": 0,
147
+ "dark_index": 1,
148
+ "min_adc": 0,
149
+ "max_adc": 2450,
150
+ "level_array": [
151
+ {"name": "cloudy", "adc": 490, "value": 20},
152
+ {"name": "overcast", "adc": 294, "value": 12},
153
+ {"name": "dawn", "adc": 222, "value": 9},
154
+ {"name": "twilight", "adc": 222, "value": 9},
155
+ {"name": "total darkness", "adc": 111, "value": 4},
156
+ {"name": "custom", "adc": 2400, "value": 97},
157
+ ],
158
+ }
159
+ ],
160
+ "ver": "1.0",
161
+ "err_code": 0,
162
+ },
163
+ }
164
+
165
+
166
+ MOTION_MODULE = {
167
+ "get_config": {
168
+ "enable": 0,
169
+ "version": "1.0",
170
+ "trigger_index": 2,
171
+ "cold_time": 60000,
172
+ "min_adc": 0,
173
+ "max_adc": 4095,
174
+ "array": [80, 50, 20, 0],
175
+ "err_code": 0,
176
+ }
177
+ }
178
+
124
179
 
125
180
  class FakeIotProtocol(IotProtocol):
126
181
  def __init__(self, info):
@@ -129,6 +184,7 @@ class FakeIotProtocol(IotProtocol):
129
184
  config=DeviceConfig("127.0.0.123"),
130
185
  )
131
186
  )
187
+ info = copy.deepcopy(info)
132
188
  self.discovery_data = info
133
189
  self.writer = None
134
190
  self.reader = None
@@ -246,9 +302,9 @@ class FakeIotProtocol(IotProtocol):
246
302
 
247
303
  def set_preferred_state(self, new_state, *args):
248
304
  """Implement set_preferred_state."""
249
- self.proto["system"]["get_sysinfo"]["preferred_state"][
250
- new_state["index"]
251
- ] = new_state
305
+ self.proto["system"]["get_sysinfo"]["preferred_state"][new_state["index"]] = (
306
+ new_state
307
+ )
252
308
 
253
309
  def light_state(self, x, *args):
254
310
  light_state = self.proto["system"]["get_sysinfo"]["light_state"]
@@ -305,8 +361,10 @@ class FakeIotProtocol(IotProtocol):
305
361
  "set_brightness": set_hs220_brightness,
306
362
  "set_dimmer_transition": set_hs220_dimmer_transition,
307
363
  },
308
- "smartlife.iot.LAS": {},
309
- "smartlife.iot.PIR": {},
364
+ "smartlife.iot.LAS": AMBIENT_MODULE,
365
+ "smartlife.iot.PIR": MOTION_MODULE,
366
+ "cnCloud": CLOUD_MODULE,
367
+ "smartlife.iot.common.cloud": CLOUD_MODULE,
310
368
  }
311
369
 
312
370
  async def query(self, request, port=9999):
@@ -355,4 +413,4 @@ class FakeIotProtocol(IotProtocol):
355
413
  for target in request:
356
414
  response.update(get_response_for_module(target))
357
415
 
358
- return response
416
+ return copy.deepcopy(response)
@@ -1,14 +1,17 @@
1
- import warnings
1
+ import copy
2
2
  from json import loads as json_loads
3
3
 
4
- from kasa import Credentials, DeviceConfig, SmartDeviceException, SmartProtocol
4
+ import pytest
5
+
6
+ from kasa import Credentials, DeviceConfig, SmartProtocol
7
+ from kasa.exceptions import SmartErrorCode
5
8
  from kasa.protocol import BaseTransport
6
9
 
7
10
 
8
11
  class FakeSmartProtocol(SmartProtocol):
9
- def __init__(self, info):
12
+ def __init__(self, info, fixture_name):
10
13
  super().__init__(
11
- transport=FakeSmartTransport(info),
14
+ transport=FakeSmartTransport(info, fixture_name),
12
15
  )
13
16
 
14
17
  async def query(self, request, retry_count: int = 3):
@@ -18,7 +21,16 @@ class FakeSmartProtocol(SmartProtocol):
18
21
 
19
22
 
20
23
  class FakeSmartTransport(BaseTransport):
21
- def __init__(self, info):
24
+ def __init__(
25
+ self,
26
+ info,
27
+ fixture_name,
28
+ *,
29
+ list_return_size=10,
30
+ component_nego_not_included=False,
31
+ warn_fixture_missing_methods=True,
32
+ fix_incomplete_fixture_lists=True,
33
+ ):
22
34
  super().__init__(
23
35
  config=DeviceConfig(
24
36
  "127.0.0.123",
@@ -28,11 +40,16 @@ class FakeSmartTransport(BaseTransport):
28
40
  ),
29
41
  ),
30
42
  )
31
- self.info = info
32
- self.components = {
33
- comp["id"]: comp["ver_code"]
34
- for comp in self.info["component_nego"]["component_list"]
35
- }
43
+ self.fixture_name = fixture_name
44
+ self.info = copy.deepcopy(info)
45
+ if not component_nego_not_included:
46
+ self.components = {
47
+ comp["id"]: comp["ver_code"]
48
+ for comp in self.info["component_nego"]["component_list"]
49
+ }
50
+ self.list_return_size = list_return_size
51
+ self.warn_fixture_missing_methods = warn_fixture_missing_methods
52
+ self.fix_incomplete_fixture_lists = fix_incomplete_fixture_lists
36
53
 
37
54
  @property
38
55
  def default_port(self):
@@ -46,6 +63,58 @@ class FakeSmartTransport(BaseTransport):
46
63
 
47
64
  FIXTURE_MISSING_MAP = {
48
65
  "get_wireless_scan_info": ("wireless", {"ap_list": [], "wep_supported": False}),
66
+ "get_auto_off_config": ("auto_off", {"delay_min": 10, "enable": False}),
67
+ "get_led_info": (
68
+ "led",
69
+ {
70
+ "led_rule": "never",
71
+ "led_status": False,
72
+ "night_mode": {
73
+ "end_time": 420,
74
+ "night_mode_type": "sunrise_sunset",
75
+ "start_time": 1140,
76
+ "sunrise_offset": 0,
77
+ "sunset_offset": 0,
78
+ },
79
+ },
80
+ ),
81
+ "get_on_off_gradually_info": ("on_off_gradually", {"enable": True}),
82
+ "get_latest_fw": (
83
+ "firmware",
84
+ {
85
+ "fw_size": 0,
86
+ "fw_ver": "1.0.5 Build 230801 Rel.095702",
87
+ "hw_id": "",
88
+ "need_to_upgrade": False,
89
+ "oem_id": "",
90
+ "release_date": "",
91
+ "release_note": "",
92
+ "type": 0,
93
+ },
94
+ ),
95
+ "get_auto_update_info": (
96
+ "firmware",
97
+ {"enable": True, "random_range": 120, "time": 180},
98
+ ),
99
+ "get_alarm_configure": (
100
+ "alarm",
101
+ {
102
+ "get_alarm_configure": {
103
+ "duration": 10,
104
+ "type": "Doorbell Ring 2",
105
+ "volume": "low",
106
+ }
107
+ },
108
+ ),
109
+ "get_support_alarm_type_list": (
110
+ "alarm",
111
+ {
112
+ "alarm_type_list": [
113
+ "Doorbell Ring 1",
114
+ ]
115
+ },
116
+ ),
117
+ "get_device_usage": ("device", {}),
49
118
  }
50
119
 
51
120
  async def send(self, request: str):
@@ -56,6 +125,9 @@ class FakeSmartTransport(BaseTransport):
56
125
  responses = []
57
126
  for request in params["requests"]:
58
127
  response = self._send_request(request) # type: ignore[arg-type]
128
+ # Devices do not continue after error
129
+ if response["error_code"] != 0:
130
+ break
59
131
  response["method"] = request["method"] # type: ignore[index]
60
132
  responses.append(response)
61
133
  return {"result": {"responses": responses}, "error_code": 0}
@@ -80,15 +152,85 @@ class FakeSmartTransport(BaseTransport):
80
152
 
81
153
  # We only support get & set device info for now.
82
154
  if child_method == "get_device_info":
83
- return {"result": info, "error_code": 0}
155
+ result = copy.deepcopy(info)
156
+ return {"result": result, "error_code": 0}
84
157
  elif child_method == "set_device_info":
85
158
  info.update(child_params)
86
159
  return {"error_code": 0}
160
+ elif child_method == "set_preset_rules":
161
+ return self._set_child_preset_rules(info, child_params)
162
+ elif (
163
+ # FIXTURE_MISSING is for service calls not in place when
164
+ # SMART fixtures started to be generated
165
+ missing_result := self.FIXTURE_MISSING_MAP.get(child_method)
166
+ ) and missing_result[0] in self.components:
167
+ result = copy.deepcopy(missing_result[1])
168
+ retval = {"result": result, "error_code": 0}
169
+ return retval
170
+ else:
171
+ # PARAMS error returned for KS240 when get_device_usage called
172
+ # on parent device. Could be any error code though.
173
+ # TODO: Try to figure out if there's a way to prevent the KS240 smartdevice
174
+ # calling the unsupported device in the first place.
175
+ retval = {
176
+ "error_code": SmartErrorCode.PARAMS_ERROR.value,
177
+ "method": child_method,
178
+ }
179
+ return retval
87
180
 
88
181
  raise NotImplementedError(
89
182
  "Method %s not implemented for children" % child_method
90
183
  )
91
184
 
185
+ def _set_dynamic_light_effect(self, info, params):
186
+ """Set or remove values as per the device behaviour."""
187
+ info["get_device_info"]["dynamic_light_effect_enable"] = params["enable"]
188
+ info["get_dynamic_light_effect_rules"]["enable"] = params["enable"]
189
+ if params["enable"]:
190
+ info["get_device_info"]["dynamic_light_effect_id"] = params["id"]
191
+ info["get_dynamic_light_effect_rules"]["current_rule_id"] = params["enable"]
192
+ else:
193
+ if "dynamic_light_effect_id" in info["get_device_info"]:
194
+ del info["get_device_info"]["dynamic_light_effect_id"]
195
+ if "current_rule_id" in info["get_dynamic_light_effect_rules"]:
196
+ del info["get_dynamic_light_effect_rules"]["current_rule_id"]
197
+
198
+ def _set_light_strip_effect(self, info, params):
199
+ """Set or remove values as per the device behaviour."""
200
+ info["get_device_info"]["lighting_effect"]["enable"] = params["enable"]
201
+ info["get_device_info"]["lighting_effect"]["name"] = params["name"]
202
+ info["get_device_info"]["lighting_effect"]["id"] = params["id"]
203
+ info["get_lighting_effect"] = copy.deepcopy(params)
204
+
205
+ def _set_led_info(self, info, params):
206
+ """Set or remove values as per the device behaviour."""
207
+ info["get_led_info"]["led_status"] = params["led_rule"] != "never"
208
+ info["get_led_info"]["led_rule"] = params["led_rule"]
209
+
210
+ def _set_preset_rules(self, info, params):
211
+ """Set or remove values as per the device behaviour."""
212
+ if "brightness" not in info["get_preset_rules"]:
213
+ return {"error_code": SmartErrorCode.PARAMS_ERROR}
214
+ info["get_preset_rules"]["brightness"] = params["brightness"]
215
+ return {"error_code": 0}
216
+
217
+ def _set_child_preset_rules(self, info, params):
218
+ """Set or remove values as per the device behaviour."""
219
+ # So far the only child device with light preset (KS240) has the
220
+ # data available to read in the device_info. If a child device
221
+ # appears that doesn't have this this will need to be extended.
222
+ if "preset_state" not in info:
223
+ return {"error_code": SmartErrorCode.PARAMS_ERROR}
224
+ info["preset_state"] = [{"brightness": b} for b in params["brightness"]]
225
+ return {"error_code": 0}
226
+
227
+ def _edit_preset_rules(self, info, params):
228
+ """Set or remove values as per the device behaviour."""
229
+ if "states" not in info["get_preset_rules"] is None:
230
+ return {"error_code": SmartErrorCode.PARAMS_ERROR}
231
+ info["get_preset_rules"]["states"][params["index"]] = params["state"]
232
+ return {"error_code": 0}
233
+
92
234
  def _send_request(self, request_dict: dict):
93
235
  method = request_dict["method"]
94
236
  params = request_dict["params"]
@@ -98,21 +240,72 @@ class FakeSmartTransport(BaseTransport):
98
240
  return self._handle_control_child(params)
99
241
  elif method == "component_nego" or method[:4] == "get_":
100
242
  if method in info:
101
- return {"result": info[method], "error_code": 0}
102
- elif (
243
+ result = copy.deepcopy(info[method])
244
+ if "start_index" in result and "sum" in result:
245
+ list_key = next(
246
+ iter([key for key in result if isinstance(result[key], list)])
247
+ )
248
+ start_index = (
249
+ start_index
250
+ if (params and (start_index := params.get("start_index")))
251
+ else 0
252
+ )
253
+ # Fixtures generated before _handle_response_lists was implemented
254
+ # could have incomplete lists.
255
+ if (
256
+ len(result[list_key]) < result["sum"]
257
+ and self.fix_incomplete_fixture_lists
258
+ ):
259
+ result["sum"] = len(result[list_key])
260
+ if self.warn_fixture_missing_methods:
261
+ pytest.fixtures_missing_methods.setdefault(
262
+ self.fixture_name, set()
263
+ ).add(f"{method} (incomplete '{list_key}' list)")
264
+
265
+ result[list_key] = result[list_key][
266
+ start_index : start_index + self.list_return_size
267
+ ]
268
+ return {"result": result, "error_code": 0}
269
+
270
+ if (
271
+ # FIXTURE_MISSING is for service calls not in place when
272
+ # SMART fixtures started to be generated
103
273
  missing_result := self.FIXTURE_MISSING_MAP.get(method)
104
274
  ) and missing_result[0] in self.components:
105
- warnings.warn(
106
- UserWarning(
107
- f"Fixture missing expected method {method}, try to regenerate"
108
- ),
109
- stacklevel=1,
110
- )
111
- return {"result": missing_result[1], "error_code": 0}
275
+ # Copy to info so it will work with update methods
276
+ info[method] = copy.deepcopy(missing_result[1])
277
+ result = copy.deepcopy(info[method])
278
+ retval = {"result": result, "error_code": 0}
112
279
  else:
113
- raise SmartDeviceException(f"Fixture doesn't support {method}")
114
- elif method == "set_qs_info":
280
+ # PARAMS error returned for KS240 when get_device_usage called
281
+ # on parent device. Could be any error code though.
282
+ # TODO: Try to figure out if there's a way to prevent the KS240 smartdevice
283
+ # calling the unsupported device in the first place.
284
+ retval = {
285
+ "error_code": SmartErrorCode.PARAMS_ERROR.value,
286
+ "method": method,
287
+ }
288
+ # Reduce warning spam by consolidating and reporting at the end of the run
289
+ if self.warn_fixture_missing_methods:
290
+ pytest.fixtures_missing_methods.setdefault(
291
+ self.fixture_name, set()
292
+ ).add(method)
293
+ return retval
294
+ elif method in ["set_qs_info", "fw_download"]:
295
+ return {"error_code": 0}
296
+ elif method == "set_dynamic_light_effect_rule_enable":
297
+ self._set_dynamic_light_effect(info, params)
298
+ return {"error_code": 0}
299
+ elif method == "set_lighting_effect":
300
+ self._set_light_strip_effect(info, params)
301
+ return {"error_code": 0}
302
+ elif method == "set_led_info":
303
+ self._set_led_info(info, params)
115
304
  return {"error_code": 0}
305
+ elif method == "set_preset_rules":
306
+ return self._set_preset_rules(info, params)
307
+ elif method == "edit_preset_rules":
308
+ return self._edit_preset_rules(info, params)
116
309
  elif method[:4] == "set_":
117
310
  target_method = f"get_{method[4:]}"
118
311
  info[target_method].update(params)
@@ -0,0 +1,154 @@
1
+ from __future__ import annotations
2
+
3
+ import glob
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ from typing import NamedTuple
8
+
9
+ from kasa.device_factory import _get_device_type_from_sys_info
10
+ from kasa.device_type import DeviceType
11
+ from kasa.smart.smartdevice import SmartDevice
12
+
13
+
14
+ class FixtureInfo(NamedTuple):
15
+ name: str
16
+ protocol: str
17
+ data: dict
18
+
19
+
20
+ FixtureInfo.__hash__ = lambda self: hash((self.name, self.protocol)) # type: ignore[attr-defined, method-assign]
21
+ FixtureInfo.__eq__ = lambda x, y: hash(x) == hash(y) # type: ignore[method-assign]
22
+
23
+
24
+ SUPPORTED_IOT_DEVICES = [
25
+ (device, "IOT")
26
+ for device in glob.glob(
27
+ os.path.dirname(os.path.abspath(__file__)) + "/fixtures/*.json"
28
+ )
29
+ ]
30
+
31
+ SUPPORTED_SMART_DEVICES = [
32
+ (device, "SMART")
33
+ for device in glob.glob(
34
+ os.path.dirname(os.path.abspath(__file__)) + "/fixtures/smart/*.json"
35
+ )
36
+ ]
37
+
38
+ SUPPORTED_SMART_CHILD_DEVICES = [
39
+ (device, "SMART.CHILD")
40
+ for device in glob.glob(
41
+ os.path.dirname(os.path.abspath(__file__)) + "/fixtures/smart/child/*.json"
42
+ )
43
+ ]
44
+
45
+
46
+ SUPPORTED_DEVICES = (
47
+ SUPPORTED_IOT_DEVICES + SUPPORTED_SMART_DEVICES + SUPPORTED_SMART_CHILD_DEVICES
48
+ )
49
+
50
+
51
+ def idgenerator(paramtuple: FixtureInfo):
52
+ try:
53
+ return paramtuple.name + (
54
+ "" if paramtuple.protocol == "IOT" else "-" + paramtuple.protocol
55
+ )
56
+ except: # TODO: HACK as idgenerator is now used by default # noqa: E722
57
+ return None
58
+
59
+
60
+ def get_fixture_info() -> list[FixtureInfo]:
61
+ """Return raw discovery file contents as JSON. Used for discovery tests."""
62
+ fixture_data = []
63
+ for file, protocol in SUPPORTED_DEVICES:
64
+ p = Path(file)
65
+ folder = Path(__file__).parent / "fixtures"
66
+ if protocol == "SMART":
67
+ folder = folder / "smart"
68
+ if protocol == "SMART.CHILD":
69
+ folder = folder / "smart/child"
70
+ p = folder / file
71
+
72
+ with open(p) as f:
73
+ data = json.load(f)
74
+
75
+ fixture_name = p.name
76
+ fixture_data.append(
77
+ FixtureInfo(data=data, protocol=protocol, name=fixture_name)
78
+ )
79
+ return fixture_data
80
+
81
+
82
+ FIXTURE_DATA: list[FixtureInfo] = get_fixture_info()
83
+
84
+
85
+ def filter_fixtures(
86
+ desc,
87
+ *,
88
+ data_root_filter: str | None = None,
89
+ protocol_filter: set[str] | None = None,
90
+ model_filter: set[str] | None = None,
91
+ component_filter: str | None = None,
92
+ device_type_filter: list[DeviceType] | None = None,
93
+ ):
94
+ """Filter the fixtures based on supplied parameters.
95
+
96
+ data_root_filter: return fixtures containing the supplied top
97
+ level key, i.e. discovery_result
98
+ protocol_filter: set of protocols to match, IOT, SMART, SMART.CHILD
99
+ model_filter: set of device models to match
100
+ component_filter: filter SMART fixtures that have the provided
101
+ component in component_nego details.
102
+ """
103
+
104
+ def _model_match(fixture_data: FixtureInfo, model_filter):
105
+ file_model_region = fixture_data.name.split("_")[0]
106
+ file_model = file_model_region.split("(")[0]
107
+ return file_model in model_filter
108
+
109
+ def _component_match(fixture_data: FixtureInfo, component_filter):
110
+ if (component_nego := fixture_data.data.get("component_nego")) is None:
111
+ return False
112
+ components = {
113
+ component["id"]: component["ver_code"]
114
+ for component in component_nego["component_list"]
115
+ }
116
+ return component_filter in components
117
+
118
+ def _device_type_match(fixture_data: FixtureInfo, device_type):
119
+ if (component_nego := fixture_data.data.get("component_nego")) is None:
120
+ return _get_device_type_from_sys_info(fixture_data.data) in device_type
121
+ components = [component["id"] for component in component_nego["component_list"]]
122
+ if (info := fixture_data.data.get("get_device_info")) and (
123
+ type_ := info.get("type")
124
+ ):
125
+ return (
126
+ SmartDevice._get_device_type_from_components(components, type_)
127
+ in device_type
128
+ )
129
+ return False
130
+
131
+ filtered = []
132
+ if protocol_filter is None:
133
+ protocol_filter = {"IOT", "SMART"}
134
+ for fixture_data in FIXTURE_DATA:
135
+ if data_root_filter and data_root_filter not in fixture_data.data:
136
+ continue
137
+ if fixture_data.protocol not in protocol_filter:
138
+ continue
139
+ if model_filter is not None and not _model_match(fixture_data, model_filter):
140
+ continue
141
+ if component_filter and not _component_match(fixture_data, component_filter):
142
+ continue
143
+ if device_type_filter and not _device_type_match(
144
+ fixture_data, device_type_filter
145
+ ):
146
+ continue
147
+
148
+ filtered.append(fixture_data)
149
+
150
+ print(f"# {desc}")
151
+ for value in filtered:
152
+ print(f"\t{value.name}")
153
+ filtered.sort()
154
+ return filtered