python-kasa 0.5.4__py3-none-any.whl → 0.6.0__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 (64) hide show
  1. kasa/__init__.py +18 -1
  2. kasa/aestransport.py +347 -0
  3. kasa/cli.py +235 -44
  4. kasa/credentials.py +4 -3
  5. kasa/device_factory.py +164 -0
  6. kasa/device_type.py +27 -0
  7. kasa/deviceconfig.py +185 -0
  8. kasa/discover.py +228 -106
  9. kasa/exceptions.py +98 -0
  10. kasa/httpclient.py +95 -0
  11. kasa/iotprotocol.py +89 -0
  12. kasa/klaptransport.py +477 -0
  13. kasa/modules/emeter.py +26 -9
  14. kasa/modules/usage.py +13 -12
  15. kasa/protocol.py +167 -22
  16. kasa/smartbulb.py +5 -5
  17. kasa/smartdevice.py +116 -43
  18. kasa/smartdimmer.py +5 -5
  19. kasa/smartlightstrip.py +5 -5
  20. kasa/smartplug.py +5 -5
  21. kasa/smartprotocol.py +251 -0
  22. kasa/smartstrip.py +5 -5
  23. kasa/tapo/__init__.py +6 -0
  24. kasa/tapo/tapobulb.py +261 -0
  25. kasa/tapo/tapodevice.py +341 -0
  26. kasa/tapo/tapoplug.py +45 -0
  27. kasa/tests/conftest.py +405 -83
  28. kasa/tests/fixtures/HS100(UK)_4.1_1.1.0.json +25 -22
  29. kasa/tests/fixtures/smart/EP25(US)_2.6_1.0.1.json +457 -0
  30. kasa/tests/fixtures/smart/KP125M(US)_1.0_1.1.3.json +175 -0
  31. kasa/tests/fixtures/smart/KS205(US)_1.0_1.0.2.json +243 -0
  32. kasa/tests/fixtures/smart/KS225(US)_1.0_1.0.2.json +269 -0
  33. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.0.6.json +425 -0
  34. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.0.json +440 -0
  35. kasa/tests/fixtures/smart/L900-10(EU)_1.0_1.0.17.json +441 -0
  36. kasa/tests/fixtures/smart/L900-5(EU)_1.0_1.0.17.json +306 -0
  37. kasa/tests/fixtures/smart/L920-5(US)_1.0_1.1.0.json +397 -0
  38. kasa/tests/fixtures/smart/P110(EU)_1.0_1.2.3.json +390 -0
  39. kasa/tests/fixtures/smart/P110(UK)_1.0_1.3.0.json +447 -0
  40. kasa/tests/fixtures/smart/P125M(US)_1.0_1.1.0.json +243 -0
  41. kasa/tests/newfakes.py +124 -15
  42. kasa/tests/test_aestransport.py +222 -0
  43. kasa/tests/test_bulb.py +15 -12
  44. kasa/tests/test_cli.py +289 -23
  45. kasa/tests/test_device_factory.py +158 -0
  46. kasa/tests/test_device_type.py +23 -0
  47. kasa/tests/test_deviceconfig.py +77 -0
  48. kasa/tests/test_discovery.py +205 -77
  49. kasa/tests/test_emeter.py +34 -4
  50. kasa/tests/test_klapprotocol.py +410 -0
  51. kasa/tests/test_plug.py +12 -1
  52. kasa/tests/test_protocol.py +172 -8
  53. kasa/tests/test_readme_examples.py +7 -7
  54. kasa/tests/test_smartdevice.py +69 -9
  55. kasa/tests/test_smartprotocol.py +82 -0
  56. kasa/tests/test_strip.py +1 -1
  57. kasa/tests/test_usage.py +65 -0
  58. python_kasa-0.6.0.dist-info/METADATA +362 -0
  59. {python_kasa-0.5.4.dist-info → python_kasa-0.6.0.dist-info}/RECORD +62 -33
  60. {python_kasa-0.5.4.dist-info → python_kasa-0.6.0.dist-info}/WHEEL +1 -1
  61. CHANGELOG.md +0 -1368
  62. python_kasa-0.5.4.dist-info/METADATA +0 -231
  63. {python_kasa-0.5.4.dist-info → python_kasa-0.6.0.dist-info}/LICENSE +0 -0
  64. {python_kasa-0.5.4.dist-info → python_kasa-0.6.0.dist-info}/entry_points.txt +0 -0
kasa/__init__.py CHANGED
@@ -14,19 +14,28 @@ to be handled by the user of the library.
14
14
  from importlib.metadata import version
15
15
 
16
16
  from kasa.credentials import Credentials
17
+ from kasa.deviceconfig import (
18
+ ConnectionType,
19
+ DeviceConfig,
20
+ DeviceFamilyType,
21
+ EncryptType,
22
+ )
17
23
  from kasa.discover import Discover
18
24
  from kasa.emeterstatus import EmeterStatus
19
25
  from kasa.exceptions import (
20
26
  AuthenticationException,
21
27
  SmartDeviceException,
28
+ TimeoutException,
22
29
  UnsupportedDeviceException,
23
30
  )
24
- from kasa.protocol import TPLinkSmartHomeProtocol
31
+ from kasa.iotprotocol import IotProtocol
32
+ from kasa.protocol import TPLinkProtocol, TPLinkSmartHomeProtocol
25
33
  from kasa.smartbulb import SmartBulb, SmartBulbPreset, TurnOnBehavior, TurnOnBehaviors
26
34
  from kasa.smartdevice import DeviceType, SmartDevice
27
35
  from kasa.smartdimmer import SmartDimmer
28
36
  from kasa.smartlightstrip import SmartLightStrip
29
37
  from kasa.smartplug import SmartPlug
38
+ from kasa.smartprotocol import SmartProtocol
30
39
  from kasa.smartstrip import SmartStrip
31
40
 
32
41
  __version__ = version("python-kasa")
@@ -35,6 +44,9 @@ __version__ = version("python-kasa")
35
44
  __all__ = [
36
45
  "Discover",
37
46
  "TPLinkSmartHomeProtocol",
47
+ "TPLinkProtocol",
48
+ "IotProtocol",
49
+ "SmartProtocol",
38
50
  "SmartBulb",
39
51
  "SmartBulbPreset",
40
52
  "TurnOnBehaviors",
@@ -49,5 +61,10 @@ __all__ = [
49
61
  "SmartLightStrip",
50
62
  "AuthenticationException",
51
63
  "UnsupportedDeviceException",
64
+ "TimeoutException",
52
65
  "Credentials",
66
+ "DeviceConfig",
67
+ "ConnectionType",
68
+ "EncryptType",
69
+ "DeviceFamilyType",
53
70
  ]
kasa/aestransport.py ADDED
@@ -0,0 +1,347 @@
1
+ """Implementation of the TP-Link AES transport.
2
+
3
+ Based on the work of https://github.com/petretiandrea/plugp100
4
+ under compatible GNU GPL3 license.
5
+ """
6
+
7
+ import base64
8
+ import hashlib
9
+ import logging
10
+ import time
11
+ from typing import Dict, Optional, cast
12
+
13
+ from cryptography.hazmat.primitives import padding, serialization
14
+ from cryptography.hazmat.primitives.asymmetric import padding as asymmetric_padding
15
+ from cryptography.hazmat.primitives.asymmetric import rsa
16
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
17
+
18
+ from .credentials import Credentials
19
+ from .deviceconfig import DeviceConfig
20
+ from .exceptions import (
21
+ SMART_AUTHENTICATION_ERRORS,
22
+ SMART_RETRYABLE_ERRORS,
23
+ SMART_TIMEOUT_ERRORS,
24
+ AuthenticationException,
25
+ RetryableException,
26
+ SmartDeviceException,
27
+ SmartErrorCode,
28
+ TimeoutException,
29
+ )
30
+ from .httpclient import HttpClient
31
+ from .json import dumps as json_dumps
32
+ from .json import loads as json_loads
33
+ from .protocol import BaseTransport
34
+
35
+ _LOGGER = logging.getLogger(__name__)
36
+
37
+
38
+ def _sha1(payload: bytes) -> str:
39
+ sha1_algo = hashlib.sha1() # noqa: S324
40
+ sha1_algo.update(payload)
41
+ return sha1_algo.hexdigest()
42
+
43
+
44
+ class AesTransport(BaseTransport):
45
+ """Implementation of the AES encryption protocol.
46
+
47
+ AES is the name used in device discovery for TP-Link's TAPO encryption
48
+ protocol, sometimes used by newer firmware versions on kasa devices.
49
+ """
50
+
51
+ DEFAULT_PORT: int = 80
52
+ SESSION_COOKIE_NAME = "TP_SESSIONID"
53
+ COMMON_HEADERS = {
54
+ "Content-Type": "application/json",
55
+ "requestByApp": "true",
56
+ "Accept": "application/json",
57
+ }
58
+
59
+ def __init__(
60
+ self,
61
+ *,
62
+ config: DeviceConfig,
63
+ ) -> None:
64
+ super().__init__(config=config)
65
+
66
+ self._login_version = config.connection_type.login_version
67
+ if (
68
+ not self._credentials or self._credentials.username is None
69
+ ) and not self._credentials_hash:
70
+ self._credentials = Credentials()
71
+ if self._credentials:
72
+ self._login_params = self._get_login_params()
73
+ else:
74
+ self._login_params = json_loads(
75
+ base64.b64decode(self._credentials_hash.encode()).decode() # type: ignore[union-attr]
76
+ )
77
+
78
+ self._http_client: HttpClient = HttpClient(config)
79
+
80
+ self._handshake_done = False
81
+
82
+ self._encryption_session: Optional[AesEncyptionSession] = None
83
+ self._session_expire_at: Optional[float] = None
84
+
85
+ self._session_cookie: Optional[Dict[str, str]] = None
86
+
87
+ self._login_token = None
88
+
89
+ _LOGGER.debug("Created AES transport for %s", self._host)
90
+
91
+ @property
92
+ def default_port(self):
93
+ """Default port for the transport."""
94
+ return self.DEFAULT_PORT
95
+
96
+ @property
97
+ def credentials_hash(self) -> str:
98
+ """The hashed credentials used by the transport."""
99
+ return base64.b64encode(json_dumps(self._login_params).encode()).decode()
100
+
101
+ def _get_login_params(self):
102
+ """Get the login parameters based on the login_version."""
103
+ un, pw = self.hash_credentials(self._login_version == 2)
104
+ password_field_name = "password2" if self._login_version == 2 else "password"
105
+ return {password_field_name: pw, "username": un}
106
+
107
+ def hash_credentials(self, login_v2):
108
+ """Hash the credentials."""
109
+ if login_v2:
110
+ un = base64.b64encode(
111
+ _sha1(self._credentials.username.encode()).encode()
112
+ ).decode()
113
+ pw = base64.b64encode(
114
+ _sha1(self._credentials.password.encode()).encode()
115
+ ).decode()
116
+ else:
117
+ un = base64.b64encode(
118
+ _sha1(self._credentials.username.encode()).encode()
119
+ ).decode()
120
+ pw = base64.b64encode(self._credentials.password.encode()).decode()
121
+ return un, pw
122
+
123
+ def _handle_response_error_code(self, resp_dict: dict, msg: str):
124
+ error_code = SmartErrorCode(resp_dict.get("error_code")) # type: ignore[arg-type]
125
+ if error_code == SmartErrorCode.SUCCESS:
126
+ return
127
+ msg = f"{msg}: {self._host}: {error_code.name}({error_code.value})"
128
+ if error_code in SMART_TIMEOUT_ERRORS:
129
+ raise TimeoutException(msg, error_code=error_code)
130
+ if error_code in SMART_RETRYABLE_ERRORS:
131
+ raise RetryableException(msg, error_code=error_code)
132
+ if error_code in SMART_AUTHENTICATION_ERRORS:
133
+ self._handshake_done = False
134
+ self._login_token = None
135
+ raise AuthenticationException(msg, error_code=error_code)
136
+ raise SmartDeviceException(msg, error_code=error_code)
137
+
138
+ async def send_secure_passthrough(self, request: str):
139
+ """Send encrypted message as passthrough."""
140
+ url = f"http://{self._host}/app"
141
+ if self._login_token:
142
+ url += f"?token={self._login_token}"
143
+
144
+ encrypted_payload = self._encryption_session.encrypt(request.encode()) # type: ignore
145
+ passthrough_request = {
146
+ "method": "securePassthrough",
147
+ "params": {"request": encrypted_payload.decode()},
148
+ }
149
+ status_code, resp_dict = await self._http_client.post(
150
+ url,
151
+ json=passthrough_request,
152
+ headers=self.COMMON_HEADERS,
153
+ cookies_dict=self._session_cookie,
154
+ )
155
+ # _LOGGER.debug(f"secure_passthrough response is {status_code}: {resp_dict}")
156
+
157
+ if status_code != 200:
158
+ raise SmartDeviceException(
159
+ f"{self._host} responded with an unexpected "
160
+ + f"status code {status_code} to passthrough"
161
+ )
162
+
163
+ resp_dict = cast(Dict, resp_dict)
164
+ self._handle_response_error_code(
165
+ resp_dict, "Error sending secure_passthrough message"
166
+ )
167
+
168
+ response = self._encryption_session.decrypt( # type: ignore
169
+ resp_dict["result"]["response"].encode()
170
+ )
171
+ resp_dict = json_loads(response)
172
+ return resp_dict
173
+
174
+ async def perform_login(self):
175
+ """Login to the device."""
176
+ self._login_token = None
177
+ login_request = {
178
+ "method": "login_device",
179
+ "params": self._login_params,
180
+ "request_time_milis": round(time.time() * 1000),
181
+ }
182
+ request = json_dumps(login_request)
183
+
184
+ resp_dict = await self.send_secure_passthrough(request)
185
+ self._handle_response_error_code(resp_dict, "Error logging in")
186
+ self._login_token = resp_dict["result"]["token"]
187
+
188
+ async def perform_handshake(self):
189
+ """Perform the handshake."""
190
+ _LOGGER.debug("Will perform handshaking...")
191
+ _LOGGER.debug("Generating keypair")
192
+
193
+ self._handshake_done = False
194
+ self._session_expire_at = None
195
+ self._session_cookie = None
196
+
197
+ url = f"http://{self._host}/app"
198
+ key_pair = KeyPair.create_key_pair()
199
+
200
+ pub_key = (
201
+ "-----BEGIN PUBLIC KEY-----\n"
202
+ + key_pair.get_public_key()
203
+ + "\n-----END PUBLIC KEY-----\n"
204
+ )
205
+ handshake_params = {"key": pub_key}
206
+ _LOGGER.debug(f"Handshake params: {handshake_params}")
207
+
208
+ request_body = {"method": "handshake", "params": handshake_params}
209
+
210
+ _LOGGER.debug(f"Request {request_body}")
211
+
212
+ status_code, resp_dict = await self._http_client.post(
213
+ url,
214
+ json=request_body,
215
+ headers=self.COMMON_HEADERS,
216
+ cookies_dict=self._session_cookie,
217
+ )
218
+
219
+ _LOGGER.debug(f"Device responded with: {resp_dict}")
220
+
221
+ if status_code != 200:
222
+ raise SmartDeviceException(
223
+ f"{self._host} responded with an unexpected "
224
+ + f"status code {status_code} to handshake"
225
+ )
226
+
227
+ self._handle_response_error_code(resp_dict, "Unable to complete handshake")
228
+
229
+ handshake_key = resp_dict["result"]["key"]
230
+
231
+ if (
232
+ cookie := self._http_client.get_cookie( # type: ignore
233
+ self.SESSION_COOKIE_NAME
234
+ )
235
+ ) or (
236
+ cookie := self._http_client.get_cookie( # type: ignore
237
+ "SESSIONID"
238
+ )
239
+ ):
240
+ self._session_cookie = {self.SESSION_COOKIE_NAME: cookie}
241
+
242
+ self._session_expire_at = time.time() + 86400
243
+ self._encryption_session = AesEncyptionSession.create_from_keypair(
244
+ handshake_key, key_pair
245
+ )
246
+
247
+ self._handshake_done = True
248
+
249
+ _LOGGER.debug("Handshake with %s complete", self._host)
250
+
251
+ def _handshake_session_expired(self):
252
+ """Return true if session has expired."""
253
+ return (
254
+ self._session_expire_at is None
255
+ or self._session_expire_at - time.time() <= 0
256
+ )
257
+
258
+ async def send(self, request: str):
259
+ """Send the request."""
260
+ if not self._handshake_done or self._handshake_session_expired():
261
+ await self.perform_handshake()
262
+ if not self._login_token:
263
+ await self.perform_login()
264
+
265
+ return await self.send_secure_passthrough(request)
266
+
267
+ async def close(self) -> None:
268
+ """Close the transport."""
269
+ self._handshake_done = False
270
+ self._login_token = None
271
+ await self._http_client.close()
272
+
273
+
274
+ class AesEncyptionSession:
275
+ """Class for an AES encryption session."""
276
+
277
+ @staticmethod
278
+ def create_from_keypair(handshake_key: str, keypair):
279
+ """Create the encryption session."""
280
+ handshake_key_bytes: bytes = base64.b64decode(handshake_key.encode("UTF-8"))
281
+ private_key_data = base64.b64decode(keypair.get_private_key().encode("UTF-8"))
282
+
283
+ private_key = serialization.load_der_private_key(private_key_data, None, None)
284
+ key_and_iv = private_key.decrypt(
285
+ handshake_key_bytes, asymmetric_padding.PKCS1v15()
286
+ )
287
+ if key_and_iv is None:
288
+ raise ValueError("Decryption failed!")
289
+
290
+ return AesEncyptionSession(key_and_iv[:16], key_and_iv[16:])
291
+
292
+ def __init__(self, key, iv):
293
+ self.cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
294
+ self.padding_strategy = padding.PKCS7(algorithms.AES.block_size)
295
+
296
+ def encrypt(self, data) -> bytes:
297
+ """Encrypt the message."""
298
+ encryptor = self.cipher.encryptor()
299
+ padder = self.padding_strategy.padder()
300
+ padded_data = padder.update(data) + padder.finalize()
301
+ encrypted = encryptor.update(padded_data) + encryptor.finalize()
302
+ return base64.b64encode(encrypted)
303
+
304
+ def decrypt(self, data) -> str:
305
+ """Decrypt the message."""
306
+ decryptor = self.cipher.decryptor()
307
+ unpadder = self.padding_strategy.unpadder()
308
+ decrypted = decryptor.update(base64.b64decode(data)) + decryptor.finalize()
309
+ unpadded_data = unpadder.update(decrypted) + unpadder.finalize()
310
+ return unpadded_data.decode()
311
+
312
+
313
+ class KeyPair:
314
+ """Class for generating key pairs."""
315
+
316
+ @staticmethod
317
+ def create_key_pair(key_size: int = 1024):
318
+ """Create a key pair."""
319
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size)
320
+ public_key = private_key.public_key()
321
+
322
+ private_key_bytes = private_key.private_bytes(
323
+ encoding=serialization.Encoding.DER,
324
+ format=serialization.PrivateFormat.PKCS8,
325
+ encryption_algorithm=serialization.NoEncryption(),
326
+ )
327
+ public_key_bytes = public_key.public_bytes(
328
+ encoding=serialization.Encoding.DER,
329
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
330
+ )
331
+
332
+ return KeyPair(
333
+ private_key=base64.b64encode(private_key_bytes).decode("UTF-8"),
334
+ public_key=base64.b64encode(public_key_bytes).decode("UTF-8"),
335
+ )
336
+
337
+ def __init__(self, private_key: str, public_key: str):
338
+ self.private_key = private_key
339
+ self.public_key = public_key
340
+
341
+ def get_private_key(self) -> str:
342
+ """Get the private key."""
343
+ return self.private_key
344
+
345
+ def get_public_key(self) -> str:
346
+ """Get the public key."""
347
+ return self.public_key