python-kasa 0.6.2__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 (168) 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 +12 -7
  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 -551
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/{newfakes.py → fakeprotocol_iot.py} +61 -291
  86. kasa/tests/fakeprotocol_smart.py +318 -0
  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/P300(EU)_1.0_1.0.13.json +13 -23
  99. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +6 -6
  100. kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +295 -0
  101. kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +423 -0
  102. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  103. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  104. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  105. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  106. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  107. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  108. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  109. kasa/tests/smart/__init__.py +0 -0
  110. kasa/tests/smart/features/__init__.py +0 -0
  111. kasa/tests/smart/features/test_brightness.py +55 -0
  112. kasa/tests/smart/features/test_colortemp.py +30 -0
  113. kasa/tests/smart/modules/__init__.py +0 -0
  114. kasa/tests/smart/modules/test_contact.py +28 -0
  115. kasa/tests/smart/modules/test_fan.py +79 -0
  116. kasa/tests/smart/modules/test_firmware.py +108 -0
  117. kasa/tests/smart/modules/test_humidity.py +28 -0
  118. kasa/tests/smart/modules/test_light_effect.py +41 -0
  119. kasa/tests/smart/modules/test_temperature.py +47 -0
  120. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  121. kasa/tests/smart/modules/test_waterleak.py +42 -0
  122. kasa/tests/test_aestransport.py +115 -25
  123. kasa/tests/test_bulb.py +169 -86
  124. kasa/tests/test_childdevice.py +84 -0
  125. kasa/tests/test_cli.py +452 -100
  126. kasa/tests/test_common_modules.py +216 -0
  127. kasa/tests/test_device.py +268 -0
  128. kasa/tests/test_device_factory.py +61 -41
  129. kasa/tests/test_device_type.py +1 -1
  130. kasa/tests/test_deviceconfig.py +2 -5
  131. kasa/tests/test_dimmer.py +33 -24
  132. kasa/tests/test_discovery.py +112 -69
  133. kasa/tests/test_emeter.py +39 -12
  134. kasa/tests/test_feature.py +205 -0
  135. kasa/tests/test_httpclient.py +9 -9
  136. kasa/tests/test_iotdevice.py +286 -0
  137. kasa/tests/test_klapprotocol.py +94 -41
  138. kasa/tests/test_lightstrip.py +24 -19
  139. kasa/tests/test_plug.py +51 -9
  140. kasa/tests/test_protocol.py +8 -12
  141. kasa/tests/test_readme_examples.py +86 -27
  142. kasa/tests/test_smartdevice.py +211 -247
  143. kasa/tests/test_smartprotocol.py +129 -26
  144. kasa/tests/test_strip.py +15 -6
  145. kasa/tests/test_usage.py +1 -3
  146. kasa/xortransport.py +15 -12
  147. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -141
  148. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  149. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +1 -1
  150. kasa/modules/emeter.py +0 -111
  151. kasa/smartlightstrip.py +0 -143
  152. kasa/smartplug.py +0 -91
  153. kasa/tapo/__init__.py +0 -7
  154. kasa/tapo/childdevice.py +0 -44
  155. kasa/tapo/tapobulb.py +0 -262
  156. kasa/tapo/tapodevice.py +0 -383
  157. kasa/tapo/tapoplug.py +0 -45
  158. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  159. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  160. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  161. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  162. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  163. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  164. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  165. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  166. python_kasa-0.6.2.dist-info/RECORD +0 -163
  167. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  168. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -1,12 +1,15 @@
1
+ from __future__ import annotations
2
+
1
3
  import base64
2
4
  import json
5
+ import logging
3
6
  import random
4
7
  import string
5
8
  import time
6
9
  from contextlib import nullcontext as does_not_raise
7
10
  from json import dumps as json_dumps
8
11
  from json import loads as json_loads
9
- from typing import Any, Dict, Optional
12
+ from typing import Any
10
13
 
11
14
  import aiohttp
12
15
  import pytest
@@ -18,10 +21,8 @@ from ..aestransport import AesEncyptionSession, AesTransport, TransportState
18
21
  from ..credentials import Credentials
19
22
  from ..deviceconfig import DeviceConfig
20
23
  from ..exceptions import (
21
- SMART_RETRYABLE_ERRORS,
22
- SMART_TIMEOUT_ERRORS,
23
- AuthenticationException,
24
- SmartDeviceException,
24
+ AuthenticationError,
25
+ KasaException,
25
26
  SmartErrorCode,
26
27
  )
27
28
  from ..httpclient import HttpClient
@@ -50,8 +51,8 @@ status_parameters = pytest.mark.parametrize(
50
51
  "status_code, error_code, inner_error_code, expectation",
51
52
  [
52
53
  (200, 0, 0, does_not_raise()),
53
- (400, 0, 0, pytest.raises(SmartDeviceException)),
54
- (200, -1, 0, pytest.raises(SmartDeviceException)),
54
+ (400, 0, 0, pytest.raises(KasaException)),
55
+ (200, -1, 0, pytest.raises(KasaException)),
55
56
  ],
56
57
  ids=("success", "status_code", "error_code"),
57
58
  )
@@ -102,17 +103,17 @@ async def test_login(mocker, status_code, error_code, inner_error_code, expectat
102
103
  ([SmartErrorCode.LOGIN_ERROR, 0, 0, 0], does_not_raise(), 4),
103
104
  (
104
105
  [SmartErrorCode.LOGIN_ERROR, SmartErrorCode.LOGIN_ERROR],
105
- pytest.raises(AuthenticationException),
106
+ pytest.raises(AuthenticationError),
106
107
  3,
107
108
  ),
108
109
  (
109
110
  [SmartErrorCode.LOGIN_FAILED_ERROR],
110
- pytest.raises(AuthenticationException),
111
+ pytest.raises(AuthenticationError),
111
112
  1,
112
113
  ),
113
114
  (
114
115
  [SmartErrorCode.LOGIN_ERROR, SmartErrorCode.SESSION_TIMEOUT_ERROR],
115
- pytest.raises(SmartDeviceException),
116
+ pytest.raises(KasaException),
116
117
  3,
117
118
  ),
118
119
  ],
@@ -136,6 +137,7 @@ async def test_login_errors(mocker, inner_error_codes, expectation, call_count):
136
137
  transport._state = TransportState.LOGIN_REQUIRED
137
138
  transport._session_expire_at = time.time() + 86400
138
139
  transport._encryption_session = mock_aes_device.encryption_session
140
+ mocker.patch.object(transport, "BACKOFF_SECONDS_AFTER_LOGIN_ERROR", 0)
139
141
 
140
142
  assert transport._token_url is None
141
143
 
@@ -182,6 +184,67 @@ async def test_send(mocker, status_code, error_code, inner_error_code, expectati
182
184
  assert "result" in res
183
185
 
184
186
 
187
+ async def test_unencrypted_response(mocker, caplog):
188
+ host = "127.0.0.1"
189
+ mock_aes_device = MockAesDevice(host, 200, 0, 0, do_not_encrypt_response=True)
190
+ mocker.patch.object(aiohttp.ClientSession, "post", side_effect=mock_aes_device.post)
191
+
192
+ transport = AesTransport(
193
+ config=DeviceConfig(host, credentials=Credentials("foo", "bar"))
194
+ )
195
+ transport._state = TransportState.ESTABLISHED
196
+ transport._session_expire_at = time.time() + 86400
197
+ transport._encryption_session = mock_aes_device.encryption_session
198
+ transport._token_url = transport._app_url.with_query(
199
+ f"token={mock_aes_device.token}"
200
+ )
201
+
202
+ request = {
203
+ "method": "get_device_info",
204
+ "params": None,
205
+ "request_time_milis": round(time.time() * 1000),
206
+ "requestID": 1,
207
+ "terminal_uuid": "foobar",
208
+ }
209
+ caplog.set_level(logging.DEBUG)
210
+ res = await transport.send(json_dumps(request))
211
+ assert "result" in res
212
+ assert (
213
+ "Received unencrypted response over secure passthrough from 127.0.0.1"
214
+ in caplog.text
215
+ )
216
+
217
+
218
+ async def test_unencrypted_response_invalid_json(mocker, caplog):
219
+ host = "127.0.0.1"
220
+ mock_aes_device = MockAesDevice(
221
+ host, 200, 0, 0, do_not_encrypt_response=True, send_response=b"Foobar"
222
+ )
223
+ mocker.patch.object(aiohttp.ClientSession, "post", side_effect=mock_aes_device.post)
224
+
225
+ transport = AesTransport(
226
+ config=DeviceConfig(host, credentials=Credentials("foo", "bar"))
227
+ )
228
+ transport._state = TransportState.ESTABLISHED
229
+ transport._session_expire_at = time.time() + 86400
230
+ transport._encryption_session = mock_aes_device.encryption_session
231
+ transport._token_url = transport._app_url.with_query(
232
+ f"token={mock_aes_device.token}"
233
+ )
234
+
235
+ request = {
236
+ "method": "get_device_info",
237
+ "params": None,
238
+ "request_time_milis": round(time.time() * 1000),
239
+ "requestID": 1,
240
+ "terminal_uuid": "foobar",
241
+ }
242
+ caplog.set_level(logging.DEBUG)
243
+ msg = f"Unable to decrypt response from {host}, error: Incorrect padding, response: Foobar"
244
+ with pytest.raises(KasaException, match=msg):
245
+ await transport.send(json_dumps(request))
246
+
247
+
185
248
  ERRORS = [e for e in SmartErrorCode if e != 0]
186
249
 
187
250
 
@@ -207,10 +270,21 @@ async def test_passthrough_errors(mocker, error_code):
207
270
  "requestID": 1,
208
271
  "terminal_uuid": "foobar",
209
272
  }
210
- with pytest.raises(SmartDeviceException):
273
+ with pytest.raises(KasaException):
211
274
  await transport.send(json_dumps(request))
212
275
 
213
276
 
277
+ async def test_port_override():
278
+ """Test that port override sets the app_url."""
279
+ host = "127.0.0.1"
280
+ config = DeviceConfig(
281
+ host, credentials=Credentials("foo", "bar"), port_override=12345
282
+ )
283
+ transport = AesTransport(config=config)
284
+
285
+ assert str(transport._app_url) == "http://127.0.0.1:12345/app"
286
+
287
+
214
288
  class MockAesDevice:
215
289
  class _mock_response:
216
290
  def __init__(self, status, json: dict):
@@ -224,15 +298,28 @@ class MockAesDevice:
224
298
  pass
225
299
 
226
300
  async def read(self):
227
- return json_dumps(self._json).encode()
301
+ if isinstance(self._json, dict):
302
+ return json_dumps(self._json).encode()
303
+ return self._json
228
304
 
229
305
  encryption_session = AesEncyptionSession(KEY_IV[:16], KEY_IV[16:])
230
306
 
231
- def __init__(self, host, status_code=200, error_code=0, inner_error_code=0):
307
+ def __init__(
308
+ self,
309
+ host,
310
+ status_code=200,
311
+ error_code=0,
312
+ inner_error_code=0,
313
+ *,
314
+ do_not_encrypt_response=False,
315
+ send_response=None,
316
+ ):
232
317
  self.host = host
233
318
  self.status_code = status_code
234
319
  self.error_code = error_code
235
320
  self._inner_error_code = inner_error_code
321
+ self.do_not_encrypt_response = do_not_encrypt_response
322
+ self.send_response = send_response
236
323
  self.http_client = HttpClient(DeviceConfig(self.host))
237
324
  self.inner_call_count = 0
238
325
  self.token = "".join(random.choices(string.ascii_uppercase, k=32)) # noqa: S311
@@ -250,7 +337,7 @@ class MockAesDevice:
250
337
  json = json_loads(item.decode())
251
338
  return await self._post(url, json)
252
339
 
253
- async def _post(self, url: URL, json: Dict[str, Any]):
340
+ async def _post(self, url: URL, json: dict[str, Any]):
254
341
  if json["method"] == "handshake":
255
342
  return await self._return_handshake_response(url, json)
256
343
  elif json["method"] == "securePassthrough":
@@ -258,10 +345,10 @@ class MockAesDevice:
258
345
  elif json["method"] == "login_device":
259
346
  return await self._return_login_response(url, json)
260
347
  else:
261
- assert str(url) == f"http://{self.host}/app?token={self.token}"
348
+ assert str(url) == f"http://{self.host}:80/app?token={self.token}"
262
349
  return await self._return_send_response(url, json)
263
350
 
264
- async def _return_handshake_response(self, url: URL, json: Dict[str, Any]):
351
+ async def _return_handshake_response(self, url: URL, json: dict[str, Any]):
265
352
  start = len("-----BEGIN PUBLIC KEY-----\n")
266
353
  end = len("\n-----END PUBLIC KEY-----\n")
267
354
  client_pub_key = json["params"]["key"][start:-end]
@@ -274,24 +361,26 @@ class MockAesDevice:
274
361
  self.status_code, {"result": {"key": key_64}, "error_code": self.error_code}
275
362
  )
276
363
 
277
- async def _return_secure_passthrough_response(self, url: URL, json: Dict[str, Any]):
364
+ async def _return_secure_passthrough_response(self, url: URL, json: dict[str, Any]):
278
365
  encrypted_request = json["params"]["request"]
279
366
  decrypted_request = self.encryption_session.decrypt(encrypted_request.encode())
280
367
  decrypted_request_dict = json_loads(decrypted_request)
281
368
  decrypted_response = await self._post(url, decrypted_request_dict)
282
369
  async with decrypted_response:
283
- response_data = await decrypted_response.read()
284
- decrypted_response_dict = json_loads(response_data.decode())
285
- encrypted_response = self.encryption_session.encrypt(
286
- json_dumps(decrypted_response_dict).encode()
370
+ decrypted_response_data = await decrypted_response.read()
371
+ encrypted_response = self.encryption_session.encrypt(decrypted_response_data)
372
+ response = (
373
+ decrypted_response_data
374
+ if self.do_not_encrypt_response
375
+ else encrypted_response
287
376
  )
288
377
  result = {
289
- "result": {"response": encrypted_response.decode()},
378
+ "result": {"response": response.decode()},
290
379
  "error_code": self.error_code,
291
380
  }
292
381
  return self._mock_response(self.status_code, result)
293
382
 
294
- async def _return_login_response(self, url: URL, json: Dict[str, Any]):
383
+ async def _return_login_response(self, url: URL, json: dict[str, Any]):
295
384
  if "token=" in str(url):
296
385
  raise Exception("token should not be in url for a login request")
297
386
  self.token = "".join(random.choices(string.ascii_uppercase, k=32)) # noqa: S311
@@ -299,7 +388,8 @@ class MockAesDevice:
299
388
  self.inner_call_count += 1
300
389
  return self._mock_response(self.status_code, result)
301
390
 
302
- async def _return_send_response(self, url: URL, json: Dict[str, Any]):
391
+ async def _return_send_response(self, url: URL, json: dict[str, Any]):
303
392
  result = {"result": {"method": None}, "error_code": self.inner_error_code}
393
+ response = self.send_response if self.send_response else result
304
394
  self.inner_call_count += 1
305
- return self._mock_response(self.status_code, result)
395
+ return self._mock_response(self.status_code, response)