python-kasa 0.6.0.dev2__py3-none-any.whl → 0.6.1__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 (72) hide show
  1. kasa/__init__.py +2 -2
  2. kasa/aestransport.py +154 -101
  3. kasa/cli.py +42 -23
  4. kasa/device_factory.py +4 -3
  5. kasa/deviceconfig.py +19 -10
  6. kasa/discover.py +28 -11
  7. kasa/exceptions.py +15 -1
  8. kasa/httpclient.py +113 -0
  9. kasa/iotprotocol.py +30 -26
  10. kasa/json.py +5 -1
  11. kasa/klaptransport.py +60 -75
  12. kasa/modules/emeter.py +1 -1
  13. kasa/protocol.py +61 -16
  14. kasa/smartbulb.py +2 -2
  15. kasa/smartdevice.py +11 -7
  16. kasa/smartdimmer.py +2 -2
  17. kasa/smartlightstrip.py +2 -2
  18. kasa/smartplug.py +2 -2
  19. kasa/smartprotocol.py +16 -38
  20. kasa/smartstrip.py +2 -2
  21. kasa/tapo/tapodevice.py +19 -4
  22. kasa/tapo/tapoplug.py +2 -2
  23. kasa/tests/conftest.py +24 -8
  24. kasa/tests/fixtures/HS100(UK)_1.0_1.2.6.json +28 -0
  25. kasa/tests/fixtures/HS100(UK)_4.1_1.1.0.json +3 -3
  26. kasa/tests/fixtures/HS110(EU)_1.0_1.2.5.json +11 -23
  27. kasa/tests/fixtures/HS110(EU)_4.0_1.0.4.json +40 -0
  28. kasa/tests/fixtures/HS300(US)_2.0_1.0.12.json +90 -0
  29. kasa/tests/fixtures/KL125(US)_4.0_1.0.5.json +93 -0
  30. kasa/tests/fixtures/KL130(EU)_1.0_1.8.8.json +15 -15
  31. kasa/tests/fixtures/KL430(US)_2.0_1.0.11.json +59 -0
  32. kasa/tests/fixtures/KP105(UK)_1.0_1.0.5.json +36 -0
  33. kasa/tests/fixtures/KP105(UK)_1.0_1.0.7.json +4 -4
  34. kasa/tests/fixtures/KP115(EU)_1.0_1.0.16.json +9 -9
  35. kasa/tests/fixtures/KP115(US)_1.0_1.0.21.json +42 -0
  36. kasa/tests/fixtures/KP303(UK)_1.0_1.0.3.json +9 -25
  37. kasa/tests/fixtures/smart/EP25(US)_2.6_1.0.2.json +414 -0
  38. kasa/tests/fixtures/smart/L510B(EU)_3.0_1.0.5.json +263 -0
  39. kasa/tests/fixtures/smart/L510E(US)_3.0_1.0.5.json +295 -0
  40. kasa/tests/fixtures/smart/L510E(US)_3.0_1.1.2.json +267 -0
  41. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.0.6.json +19 -19
  42. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.0.json +12 -12
  43. kasa/tests/fixtures/smart/L530E(US)_2.0_1.1.0.json +439 -0
  44. kasa/tests/fixtures/smart/L900-10(EU)_1.0_1.0.17.json +10 -10
  45. kasa/tests/fixtures/smart/L900-10(US)_1.0_1.0.11.json +428 -0
  46. kasa/tests/fixtures/smart/L900-5(EU)_1.0_1.0.17.json +98 -20
  47. kasa/tests/fixtures/smart/L900-5(EU)_1.0_1.1.0.json +390 -0
  48. kasa/tests/fixtures/smart/L920-5(US)_1.0_1.1.0.json +397 -0
  49. kasa/tests/fixtures/smart/L920-5(US)_1.0_1.1.3.json +415 -0
  50. kasa/tests/fixtures/smart/L930-5(US)_1.0_1.1.2.json +429 -0
  51. kasa/tests/fixtures/smart/P100_1.0.0_1.3.7.json +197 -0
  52. kasa/tests/fixtures/smart/P110(EU)_1.0_1.2.3.json +28 -19
  53. kasa/tests/fixtures/smart/P110(UK)_1.0_1.3.0.json +31 -31
  54. kasa/tests/fixtures/smart/P125M(US)_1.0_1.1.0.json +11 -11
  55. kasa/tests/fixtures/smart/P135(US)_1.0_1.0.5.json +317 -0
  56. kasa/tests/fixtures/smart/S500D(US)_1.0_1.0.5.json +317 -0
  57. kasa/tests/fixtures/smart/S505(US)_1.0_1.0.2.json +309 -0
  58. kasa/tests/newfakes.py +3 -0
  59. kasa/tests/test_aestransport.py +110 -22
  60. kasa/tests/test_cli.py +49 -2
  61. kasa/tests/test_device_factory.py +6 -4
  62. kasa/tests/test_deviceconfig.py +24 -9
  63. kasa/tests/test_discovery.py +126 -9
  64. kasa/tests/test_httpclient.py +100 -0
  65. kasa/tests/test_klapprotocol.py +70 -23
  66. kasa/tests/test_protocol.py +76 -2
  67. kasa/tests/test_smartprotocol.py +0 -1
  68. {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/METADATA +37 -15
  69. {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/RECORD +72 -49
  70. {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/LICENSE +0 -0
  71. {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/WHEEL +0 -0
  72. {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/entry_points.txt +0 -0
kasa/__init__.py CHANGED
@@ -29,7 +29,7 @@ from kasa.exceptions import (
29
29
  UnsupportedDeviceException,
30
30
  )
31
31
  from kasa.iotprotocol import IotProtocol
32
- from kasa.protocol import TPLinkProtocol, TPLinkSmartHomeProtocol
32
+ from kasa.protocol import BaseProtocol, TPLinkSmartHomeProtocol
33
33
  from kasa.smartbulb import SmartBulb, SmartBulbPreset, TurnOnBehavior, TurnOnBehaviors
34
34
  from kasa.smartdevice import DeviceType, SmartDevice
35
35
  from kasa.smartdimmer import SmartDimmer
@@ -44,7 +44,7 @@ __version__ = version("python-kasa")
44
44
  __all__ = [
45
45
  "Discover",
46
46
  "TPLinkSmartHomeProtocol",
47
- "TPLinkProtocol",
47
+ "BaseProtocol",
48
48
  "IotProtocol",
49
49
  "SmartProtocol",
50
50
  "SmartBulb",
kasa/aestransport.py CHANGED
@@ -8,9 +8,9 @@ import base64
8
8
  import hashlib
9
9
  import logging
10
10
  import time
11
- from typing import Optional
11
+ from enum import Enum, auto
12
+ from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, Optional, Tuple, cast
12
13
 
13
- import httpx
14
14
  from cryptography.hazmat.primitives import padding, serialization
15
15
  from cryptography.hazmat.primitives.asymmetric import padding as asymmetric_padding
16
16
  from cryptography.hazmat.primitives.asymmetric import rsa
@@ -28,19 +28,32 @@ from .exceptions import (
28
28
  SmartErrorCode,
29
29
  TimeoutException,
30
30
  )
31
+ from .httpclient import HttpClient
31
32
  from .json import dumps as json_dumps
32
33
  from .json import loads as json_loads
33
- from .protocol import BaseTransport
34
+ from .protocol import DEFAULT_CREDENTIALS, BaseTransport, get_default_credentials
34
35
 
35
36
  _LOGGER = logging.getLogger(__name__)
36
37
 
37
38
 
39
+ ONE_DAY_SECONDS = 86400
40
+ SESSION_EXPIRE_BUFFER_SECONDS = 60 * 20
41
+
42
+
38
43
  def _sha1(payload: bytes) -> str:
39
44
  sha1_algo = hashlib.sha1() # noqa: S324
40
45
  sha1_algo.update(payload)
41
46
  return sha1_algo.hexdigest()
42
47
 
43
48
 
49
+ class TransportState(Enum):
50
+ """Enum for AES state."""
51
+
52
+ HANDSHAKE_REQUIRED = auto() # Handshake needed
53
+ LOGIN_REQUIRED = auto() # Login needed
54
+ ESTABLISHED = auto() # Ready to send requests
55
+
56
+
44
57
  class AesTransport(BaseTransport):
45
58
  """Implementation of the AES encryption protocol.
46
59
 
@@ -50,11 +63,14 @@ class AesTransport(BaseTransport):
50
63
 
51
64
  DEFAULT_PORT: int = 80
52
65
  SESSION_COOKIE_NAME = "TP_SESSIONID"
66
+ TIMEOUT_COOKIE_NAME = "TIMEOUT"
53
67
  COMMON_HEADERS = {
54
68
  "Content-Type": "application/json",
55
69
  "requestByApp": "true",
56
70
  "Accept": "application/json",
57
71
  }
72
+ CONTENT_LENGTH = "Content-Length"
73
+ KEY_PAIR_CONTENT_LENGTH = 314
58
74
 
59
75
  def __init__(
60
76
  self,
@@ -69,27 +85,29 @@ class AesTransport(BaseTransport):
69
85
  ) and not self._credentials_hash:
70
86
  self._credentials = Credentials()
71
87
  if self._credentials:
72
- self._login_params = self._get_login_params()
88
+ self._login_params = self._get_login_params(self._credentials)
73
89
  else:
74
90
  self._login_params = json_loads(
75
91
  base64.b64decode(self._credentials_hash.encode()).decode() # type: ignore[union-attr]
76
92
  )
93
+ self._default_credentials: Optional[Credentials] = None
94
+ self._http_client: HttpClient = HttpClient(config)
77
95
 
78
- self._default_http_client: Optional[httpx.AsyncClient] = None
79
-
80
- self._handshake_done = False
96
+ self._state = TransportState.HANDSHAKE_REQUIRED
81
97
 
82
98
  self._encryption_session: Optional[AesEncyptionSession] = None
83
99
  self._session_expire_at: Optional[float] = None
84
100
 
85
- self._session_cookie = None
101
+ self._session_cookie: Optional[Dict[str, str]] = None
86
102
 
87
- self._login_token = None
103
+ self._login_token: Optional[str] = None
104
+
105
+ self._key_pair: Optional[KeyPair] = None
88
106
 
89
107
  _LOGGER.debug("Created AES transport for %s", self._host)
90
108
 
91
109
  @property
92
- def default_port(self):
110
+ def default_port(self) -> int:
93
111
  """Default port for the transport."""
94
112
  return self.DEFAULT_PORT
95
113
 
@@ -98,59 +116,25 @@ class AesTransport(BaseTransport):
98
116
  """The hashed credentials used by the transport."""
99
117
  return base64.b64encode(json_dumps(self._login_params).encode()).decode()
100
118
 
101
- @property
102
- def _http_client(self) -> httpx.AsyncClient:
103
- if self._config.http_client:
104
- return self._config.http_client
105
- if not self._default_http_client:
106
- self._default_http_client = httpx.AsyncClient()
107
- return self._default_http_client
108
-
109
- def _get_login_params(self):
119
+ def _get_login_params(self, credentials: Credentials) -> Dict[str, str]:
110
120
  """Get the login parameters based on the login_version."""
111
- un, pw = self.hash_credentials(self._login_version == 2)
121
+ un, pw = self.hash_credentials(self._login_version == 2, credentials)
112
122
  password_field_name = "password2" if self._login_version == 2 else "password"
113
123
  return {password_field_name: pw, "username": un}
114
124
 
115
- def hash_credentials(self, login_v2):
125
+ @staticmethod
126
+ def hash_credentials(login_v2: bool, credentials: Credentials) -> Tuple[str, str]:
116
127
  """Hash the credentials."""
128
+ un = base64.b64encode(_sha1(credentials.username.encode()).encode()).decode()
117
129
  if login_v2:
118
- un = base64.b64encode(
119
- _sha1(self._credentials.username.encode()).encode()
120
- ).decode()
121
130
  pw = base64.b64encode(
122
- _sha1(self._credentials.password.encode()).encode()
131
+ _sha1(credentials.password.encode()).encode()
123
132
  ).decode()
124
133
  else:
125
- un = base64.b64encode(
126
- _sha1(self._credentials.username.encode()).encode()
127
- ).decode()
128
- pw = base64.b64encode(self._credentials.password.encode()).decode()
134
+ pw = base64.b64encode(credentials.password.encode()).decode()
129
135
  return un, pw
130
136
 
131
- async def client_post(self, url, params=None, data=None, json=None, headers=None):
132
- """Send an http post request to the device."""
133
- response_data = None
134
- cookies = None
135
- if self._session_cookie:
136
- cookies = httpx.Cookies()
137
- cookies.set(self.SESSION_COOKIE_NAME, self._session_cookie)
138
- self._http_client.cookies.clear()
139
- resp = await self._http_client.post(
140
- url,
141
- params=params,
142
- data=data,
143
- json=json,
144
- timeout=self._timeout,
145
- cookies=cookies,
146
- headers=self.COMMON_HEADERS,
147
- )
148
- if resp.status_code == 200:
149
- response_data = resp.json()
150
-
151
- return resp.status_code, response_data
152
-
153
- def _handle_response_error_code(self, resp_dict: dict, msg: str):
137
+ def _handle_response_error_code(self, resp_dict: Any, msg: str) -> None:
154
138
  error_code = SmartErrorCode(resp_dict.get("error_code")) # type: ignore[arg-type]
155
139
  if error_code == SmartErrorCode.SUCCESS:
156
140
  return
@@ -160,15 +144,14 @@ class AesTransport(BaseTransport):
160
144
  if error_code in SMART_RETRYABLE_ERRORS:
161
145
  raise RetryableException(msg, error_code=error_code)
162
146
  if error_code in SMART_AUTHENTICATION_ERRORS:
163
- self._handshake_done = False
164
- self._login_token = None
147
+ self._state = TransportState.HANDSHAKE_REQUIRED
165
148
  raise AuthenticationException(msg, error_code=error_code)
166
149
  raise SmartDeviceException(msg, error_code=error_code)
167
150
 
168
- async def send_secure_passthrough(self, request: str):
151
+ async def send_secure_passthrough(self, request: str) -> Dict[str, Any]:
169
152
  """Send encrypted message as passthrough."""
170
153
  url = f"http://{self._host}/app"
171
- if self._login_token:
154
+ if self._state is TransportState.ESTABLISHED and self._login_token:
172
155
  url += f"?token={self._login_token}"
173
156
 
174
157
  encrypted_payload = self._encryption_session.encrypt(request.encode()) # type: ignore
@@ -176,7 +159,12 @@ class AesTransport(BaseTransport):
176
159
  "method": "securePassthrough",
177
160
  "params": {"request": encrypted_payload.decode()},
178
161
  }
179
- status_code, resp_dict = await self.client_post(url, json=passthrough_request)
162
+ status_code, resp_dict = await self._http_client.post(
163
+ url,
164
+ json=passthrough_request,
165
+ headers=self.COMMON_HEADERS,
166
+ cookies_dict=self._session_cookie,
167
+ )
180
168
  # _LOGGER.debug(f"secure_passthrough response is {status_code}: {resp_dict}")
181
169
 
182
170
  if status_code != 200:
@@ -189,18 +177,46 @@ class AesTransport(BaseTransport):
189
177
  resp_dict, "Error sending secure_passthrough message"
190
178
  )
191
179
 
192
- response = self._encryption_session.decrypt( # type: ignore
193
- resp_dict["result"]["response"].encode()
194
- )
195
- resp_dict = json_loads(response)
196
- return resp_dict
180
+ if TYPE_CHECKING:
181
+ resp_dict = cast(Dict[str, Any], resp_dict)
182
+ assert self._encryption_session is not None
183
+
184
+ raw_response: str = resp_dict["result"]["response"]
185
+ response = self._encryption_session.decrypt(raw_response.encode())
186
+ return json_loads(response) # type: ignore[return-value]
197
187
 
198
188
  async def perform_login(self):
199
189
  """Login to the device."""
200
- self._login_token = None
190
+ try:
191
+ await self.try_login(self._login_params)
192
+ except AuthenticationException as aex:
193
+ try:
194
+ if aex.error_code is not SmartErrorCode.LOGIN_ERROR:
195
+ raise aex
196
+ if self._default_credentials is None:
197
+ self._default_credentials = get_default_credentials(
198
+ DEFAULT_CREDENTIALS["TAPO"]
199
+ )
200
+ await self.perform_handshake()
201
+ await self.try_login(self._get_login_params(self._default_credentials))
202
+ _LOGGER.debug(
203
+ "%s: logged in with default credentials",
204
+ self._host,
205
+ )
206
+ except AuthenticationException:
207
+ raise
208
+ except Exception as ex:
209
+ raise AuthenticationException(
210
+ "Unable to login and trying default "
211
+ + "login raised another exception: %s",
212
+ ex,
213
+ ) from ex
214
+
215
+ async def try_login(self, login_params: Dict[str, Any]) -> None:
216
+ """Try to login with supplied login_params."""
201
217
  login_request = {
202
218
  "method": "login_device",
203
- "params": self._login_params,
219
+ "params": login_params,
204
220
  "request_time_milis": round(time.time() * 1000),
205
221
  }
206
222
  request = json_dumps(login_request)
@@ -208,34 +224,52 @@ class AesTransport(BaseTransport):
208
224
  resp_dict = await self.send_secure_passthrough(request)
209
225
  self._handle_response_error_code(resp_dict, "Error logging in")
210
226
  self._login_token = resp_dict["result"]["token"]
227
+ self._state = TransportState.ESTABLISHED
211
228
 
212
- async def perform_handshake(self):
213
- """Perform the handshake."""
214
- _LOGGER.debug("Will perform handshaking...")
215
- _LOGGER.debug("Generating keypair")
216
-
217
- self._handshake_done = False
218
- self._session_expire_at = None
219
- self._session_cookie = None
220
-
221
- url = f"http://{self._host}/app"
222
- key_pair = KeyPair.create_key_pair()
229
+ async def _generate_key_pair_payload(self) -> AsyncGenerator:
230
+ """Generate the request body and return an ascyn_generator.
223
231
 
232
+ This prevents the key pair being generated unless a connection
233
+ can be made to the device.
234
+ """
235
+ _LOGGER.debug("Generating keypair")
236
+ self._key_pair = KeyPair.create_key_pair()
224
237
  pub_key = (
225
238
  "-----BEGIN PUBLIC KEY-----\n"
226
- + key_pair.get_public_key()
239
+ + self._key_pair.get_public_key() # type: ignore[union-attr]
227
240
  + "\n-----END PUBLIC KEY-----\n"
228
241
  )
229
242
  handshake_params = {"key": pub_key}
230
243
  _LOGGER.debug(f"Handshake params: {handshake_params}")
231
-
232
244
  request_body = {"method": "handshake", "params": handshake_params}
233
-
234
245
  _LOGGER.debug(f"Request {request_body}")
246
+ yield json_dumps(request_body).encode()
235
247
 
236
- status_code, resp_dict = await self.client_post(url, json=request_body)
248
+ async def perform_handshake(self) -> None:
249
+ """Perform the handshake."""
250
+ _LOGGER.debug("Will perform handshaking...")
237
251
 
238
- _LOGGER.debug(f"Device responded with: {resp_dict}")
252
+ self._key_pair = None
253
+ self._login_token = None
254
+ self._session_expire_at = None
255
+ self._session_cookie = None
256
+
257
+ url = f"http://{self._host}/app"
258
+ # Device needs the content length or it will response with 500
259
+ headers = {
260
+ **self.COMMON_HEADERS,
261
+ self.CONTENT_LENGTH: str(self.KEY_PAIR_CONTENT_LENGTH),
262
+ }
263
+ http_client = self._http_client
264
+
265
+ status_code, resp_dict = await http_client.post(
266
+ url,
267
+ json=self._generate_key_pair_payload(),
268
+ headers=headers,
269
+ cookies_dict=self._session_cookie,
270
+ )
271
+
272
+ _LOGGER.debug("Device responded with: %s", resp_dict)
239
273
 
240
274
  if status_code != 200:
241
275
  raise SmartDeviceException(
@@ -245,22 +279,32 @@ class AesTransport(BaseTransport):
245
279
 
246
280
  self._handle_response_error_code(resp_dict, "Unable to complete handshake")
247
281
 
282
+ if TYPE_CHECKING:
283
+ resp_dict = cast(Dict[str, Any], resp_dict)
284
+
248
285
  handshake_key = resp_dict["result"]["key"]
249
286
 
250
- self._session_cookie = self._http_client.cookies.get( # type: ignore
251
- self.SESSION_COOKIE_NAME
287
+ if (
288
+ cookie := http_client.get_cookie(self.SESSION_COOKIE_NAME) # type: ignore
289
+ ) or (
290
+ cookie := http_client.get_cookie("SESSIONID") # type: ignore
291
+ ):
292
+ self._session_cookie = {self.SESSION_COOKIE_NAME: cookie}
293
+
294
+ timeout = int(
295
+ http_client.get_cookie(self.TIMEOUT_COOKIE_NAME) or ONE_DAY_SECONDS
252
296
  )
253
- if not self._session_cookie:
254
- self._session_cookie = self._http_client.cookies.get( # type: ignore
255
- "SESSIONID"
256
- )
257
-
258
- self._session_expire_at = time.time() + 86400
297
+ # There is a 24 hour timeout on the session cookie
298
+ # but the clock on the device is not always accurate
299
+ # so we set the expiry to 24 hours from now minus a buffer
300
+ self._session_expire_at = time.time() + timeout - SESSION_EXPIRE_BUFFER_SECONDS
301
+ if TYPE_CHECKING:
302
+ assert self._key_pair is not None
259
303
  self._encryption_session = AesEncyptionSession.create_from_keypair(
260
- handshake_key, key_pair
304
+ handshake_key, self._key_pair
261
305
  )
262
306
 
263
- self._handshake_done = True
307
+ self._state = TransportState.LOGIN_REQUIRED
264
308
 
265
309
  _LOGGER.debug("Handshake with %s complete", self._host)
266
310
 
@@ -271,23 +315,32 @@ class AesTransport(BaseTransport):
271
315
  or self._session_expire_at - time.time() <= 0
272
316
  )
273
317
 
274
- async def send(self, request: str):
318
+ async def send(self, request: str) -> Dict[str, Any]:
275
319
  """Send the request."""
276
- if not self._handshake_done or self._handshake_session_expired():
320
+ if (
321
+ self._state is TransportState.HANDSHAKE_REQUIRED
322
+ or self._handshake_session_expired()
323
+ ):
277
324
  await self.perform_handshake()
278
- if not self._login_token:
279
- await self.perform_login()
325
+ if self._state is not TransportState.ESTABLISHED:
326
+ try:
327
+ await self.perform_login()
328
+ # After a login failure handshake needs to
329
+ # be redone or a 9999 error is received.
330
+ except AuthenticationException as ex:
331
+ self._state = TransportState.HANDSHAKE_REQUIRED
332
+ raise ex
280
333
 
281
334
  return await self.send_secure_passthrough(request)
282
335
 
283
336
  async def close(self) -> None:
284
- """Close the protocol."""
285
- client = self._default_http_client
286
- self._default_http_client = None
287
- self._handshake_done = False
288
- self._login_token = None
289
- if client:
290
- await client.aclose()
337
+ """Close the http client and reset internal state."""
338
+ await self.reset()
339
+ await self._http_client.close()
340
+
341
+ async def reset(self) -> None:
342
+ """Reset internal handshake and login state."""
343
+ self._state = TransportState.HANDSHAKE_REQUIRED
291
344
 
292
345
 
293
346
  class AesEncyptionSession:
kasa/cli.py CHANGED
@@ -1,4 +1,5 @@
1
1
  """python-kasa cli tool."""
2
+ import ast
2
3
  import asyncio
3
4
  import json
4
5
  import logging
@@ -36,6 +37,11 @@ except ImportError:
36
37
  try:
37
38
  from rich import print as _do_echo
38
39
  except ImportError:
40
+ # Strip out rich formatting if rich is not installed
41
+ # but only lower case tags to avoid stripping out
42
+ # raw data from the device that is printed from
43
+ # the device state.
44
+ rich_formatting = re.compile(r"\[/?[a-z]+]")
39
45
 
40
46
  def _strip_rich_formatting(echo_func):
41
47
  """Strip rich formatting from messages."""
@@ -43,7 +49,7 @@ except ImportError:
43
49
  @wraps(echo_func)
44
50
  def wrapper(message=None, *args, **kwargs):
45
51
  if message is not None:
46
- message = re.sub(r"\[/?.+?]", "", message)
52
+ message = rich_formatting.sub("", message)
47
53
  echo_func(message, *args, **kwargs)
48
54
 
49
55
  return wrapper
@@ -69,6 +75,9 @@ DEVICE_FAMILY_TYPES = [
69
75
  device_family_type.value for device_family_type in DeviceFamilyType
70
76
  ]
71
77
 
78
+ # Block list of commands which require no update
79
+ SKIP_UPDATE_COMMANDS = ["wifi", "raw-command", "command"]
80
+
72
81
  click.anyio_backend = "asyncio"
73
82
 
74
83
  pass_dev = click.make_pass_decorator(SmartDevice)
@@ -317,7 +326,6 @@ async def cli(
317
326
 
318
327
  if type is not None:
319
328
  dev = TYPE_TO_CLASS[type](host)
320
- await dev.update()
321
329
  elif device_family and encrypt_type:
322
330
  ctype = ConnectionType(
323
331
  DeviceFamilyType(device_family),
@@ -339,6 +347,10 @@ async def cli(
339
347
  port=port,
340
348
  credentials=credentials,
341
349
  )
350
+
351
+ # Skip update on specific commands, or if device factory,
352
+ # that performs an update was used for the device.
353
+ if ctx.invoked_subcommand not in SKIP_UPDATE_COMMANDS and not device_family:
342
354
  await dev.update()
343
355
 
344
356
  ctx.obj = dev
@@ -390,7 +402,6 @@ async def discover(ctx):
390
402
  target = ctx.parent.params["target"]
391
403
  username = ctx.parent.params["username"]
392
404
  password = ctx.parent.params["password"]
393
- verbose = ctx.parent.params["verbose"]
394
405
  discovery_timeout = ctx.parent.params["discovery_timeout"]
395
406
  timeout = ctx.parent.params["timeout"]
396
407
  port = ctx.parent.params["port"]
@@ -429,9 +440,6 @@ async def discover(ctx):
429
440
  discovered[dev.host] = dev.internal_state
430
441
  ctx.parent.obj = dev
431
442
  await ctx.parent.invoke(state)
432
- if verbose:
433
- echo()
434
- _echo_discovery_info(dev._discovery_info)
435
443
  echo()
436
444
 
437
445
  await Discover.discover(
@@ -473,21 +481,20 @@ def _echo_discovery_info(discovery_info):
473
481
  return
474
482
 
475
483
  echo("\t[bold]== Discovery Result ==[/bold]")
476
- echo(f"\tDevice Type: {dr.device_type}")
477
- echo(f"\tDevice Model: {dr.device_model}")
478
- echo(f"\tIP: {dr.ip}")
479
- echo(f"\tMAC: {dr.mac}")
480
- echo(f"\tDevice Id (hash): {dr.device_id}")
481
- echo(f"\tOwner (hash): {dr.owner}")
482
- echo(f"\tHW Ver: {dr.hw_ver}")
483
- echo(f"\tIs Support IOT Cloud: {dr.is_support_iot_cloud})")
484
- echo(f"\tOBD Src: {dr.obd_src}")
485
- echo(f"\tFactory Default: {dr.factory_default}")
486
- echo("\t\t== Encryption Scheme ==")
487
- echo(f"\t\tEncrypt Type: {dr.mgt_encrypt_schm.encrypt_type}")
488
- echo(f"\t\tIs Support HTTPS: {dr.mgt_encrypt_schm.is_support_https}")
489
- echo(f"\t\tHTTP Port: {dr.mgt_encrypt_schm.http_port}")
490
- echo(f"\t\tLV (Login Level): {dr.mgt_encrypt_schm.lv}")
484
+ echo(f"\tDevice Type: {dr.device_type}")
485
+ echo(f"\tDevice Model: {dr.device_model}")
486
+ echo(f"\tIP: {dr.ip}")
487
+ echo(f"\tMAC: {dr.mac}")
488
+ echo(f"\tDevice Id (hash): {dr.device_id}")
489
+ echo(f"\tOwner (hash): {dr.owner}")
490
+ echo(f"\tHW Ver: {dr.hw_ver}")
491
+ echo(f"\tSupports IOT Cloud: {dr.is_support_iot_cloud}")
492
+ echo(f"\tOBD Src: {dr.obd_src}")
493
+ echo(f"\tFactory Default: {dr.factory_default}")
494
+ echo(f"\tEncrypt Type: {dr.mgt_encrypt_schm.encrypt_type}")
495
+ echo(f"\tSupports HTTPS: {dr.mgt_encrypt_schm.is_support_https}")
496
+ echo(f"\tHTTP Port: {dr.mgt_encrypt_schm.http_port}")
497
+ echo(f"\tLV (Login Level): {dr.mgt_encrypt_schm.lv}")
491
498
 
492
499
 
493
500
  async def find_host_from_alias(alias, target="255.255.255.255", timeout=1, attempts=3):
@@ -562,6 +569,8 @@ async def state(ctx, dev: SmartDevice):
562
569
  echo(f"\tDevice ID: {dev.device_id}")
563
570
  for feature in dev.features:
564
571
  echo(f"\tFeature: {feature}")
572
+ echo()
573
+ _echo_discovery_info(dev._discovery_info)
565
574
  return dev.internal_state
566
575
 
567
576
 
@@ -593,13 +602,23 @@ async def alias(dev, new_alias, index):
593
602
 
594
603
  @cli.command()
595
604
  @pass_dev
605
+ @click.pass_context
596
606
  @click.argument("module")
597
607
  @click.argument("command")
598
608
  @click.argument("parameters", default=None, required=False)
599
- async def raw_command(dev: SmartDevice, module, command, parameters):
609
+ async def raw_command(ctx, dev: SmartDevice, module, command, parameters):
600
610
  """Run a raw command on the device."""
601
- import ast
611
+ logging.warning("Deprecated, use 'kasa command --module %s %s'", module, command)
612
+ return await ctx.forward(cmd_command)
602
613
 
614
+
615
+ @cli.command(name="command")
616
+ @pass_dev
617
+ @click.option("--module", required=False, help="Module for IOT protocol.")
618
+ @click.argument("command")
619
+ @click.argument("parameters", default=None, required=False)
620
+ async def cmd_command(dev: SmartDevice, module, command, parameters):
621
+ """Run a raw command on the device."""
603
622
  if parameters is not None:
604
623
  parameters = ast.literal_eval(parameters)
605
624
 
kasa/device_factory.py CHANGED
@@ -9,8 +9,8 @@ from .exceptions import SmartDeviceException, UnsupportedDeviceException
9
9
  from .iotprotocol import IotProtocol
10
10
  from .klaptransport import KlapTransport, KlapTransportV2
11
11
  from .protocol import (
12
+ BaseProtocol,
12
13
  BaseTransport,
13
- TPLinkProtocol,
14
14
  TPLinkSmartHomeProtocol,
15
15
  _XorTransport,
16
16
  )
@@ -131,6 +131,7 @@ def get_device_class_from_family(device_type: str) -> Optional[Type[SmartDevice]
131
131
  supported_device_types: Dict[str, Type[SmartDevice]] = {
132
132
  "SMART.TAPOPLUG": TapoPlug,
133
133
  "SMART.TAPOBULB": TapoBulb,
134
+ "SMART.TAPOSWITCH": TapoBulb,
134
135
  "SMART.KASAPLUG": TapoPlug,
135
136
  "SMART.KASASWITCH": TapoBulb,
136
137
  "IOT.SMARTPLUGSWITCH": SmartPlug,
@@ -141,14 +142,14 @@ def get_device_class_from_family(device_type: str) -> Optional[Type[SmartDevice]
141
142
 
142
143
  def get_protocol(
143
144
  config: DeviceConfig,
144
- ) -> Optional[TPLinkProtocol]:
145
+ ) -> Optional[BaseProtocol]:
145
146
  """Return the protocol from the connection name."""
146
147
  protocol_name = config.connection_type.device_family.value.split(".")[0]
147
148
  protocol_transport_key = (
148
149
  protocol_name + "." + config.connection_type.encryption_type.value
149
150
  )
150
151
  supported_device_protocols: Dict[
151
- str, Tuple[Type[TPLinkProtocol], Type[BaseTransport]]
152
+ str, Tuple[Type[BaseProtocol], Type[BaseTransport]]
152
153
  ] = {
153
154
  "IOT.XOR": (TPLinkSmartHomeProtocol, _XorTransport),
154
155
  "IOT.KLAP": (IotProtocol, KlapTransport),
kasa/deviceconfig.py CHANGED
@@ -2,13 +2,14 @@
2
2
  import logging
3
3
  from dataclasses import asdict, dataclass, field, fields, is_dataclass
4
4
  from enum import Enum
5
- from typing import Dict, Optional, Union
6
-
7
- import httpx
5
+ from typing import TYPE_CHECKING, Dict, Optional, Union
8
6
 
9
7
  from .credentials import Credentials
10
8
  from .exceptions import SmartDeviceException
11
9
 
10
+ if TYPE_CHECKING:
11
+ from aiohttp import ClientSession
12
+
12
13
  _LOGGER = logging.getLogger(__name__)
13
14
 
14
15
 
@@ -29,6 +30,7 @@ class DeviceFamilyType(Enum):
29
30
  SmartKasaSwitch = "SMART.KASASWITCH"
30
31
  SmartTapoPlug = "SMART.TAPOPLUG"
31
32
  SmartTapoBulb = "SMART.TAPOBULB"
33
+ SmartTapoSwitch = "SMART.TAPOSWITCH"
32
34
 
33
35
 
34
36
  def _dataclass_from_dict(klass, in_val):
@@ -36,11 +38,16 @@ def _dataclass_from_dict(klass, in_val):
36
38
  fieldtypes = {f.name: f.type for f in fields(klass)}
37
39
  val = {}
38
40
  for dict_key in in_val:
39
- if dict_key in fieldtypes and hasattr(fieldtypes[dict_key], "from_dict"):
40
- val[dict_key] = fieldtypes[dict_key].from_dict(in_val[dict_key])
41
+ if dict_key in fieldtypes:
42
+ if hasattr(fieldtypes[dict_key], "from_dict"):
43
+ val[dict_key] = fieldtypes[dict_key].from_dict(in_val[dict_key])
44
+ else:
45
+ val[dict_key] = _dataclass_from_dict(
46
+ fieldtypes[dict_key], in_val[dict_key]
47
+ )
41
48
  else:
42
- val[dict_key] = _dataclass_from_dict(
43
- fieldtypes[dict_key], in_val[dict_key]
49
+ raise SmartDeviceException(
50
+ f"Cannot create dataclass from dict, unknown key: {dict_key}"
44
51
  )
45
52
  return klass(**val)
46
53
  else:
@@ -150,7 +157,7 @@ class DeviceConfig:
150
157
 
151
158
  # compare=False will be excluded from the serialization and object comparison.
152
159
  #: Set a custom http_client for the device to use.
153
- http_client: Optional[httpx.AsyncClient] = field(default=None, compare=False)
160
+ http_client: Optional["ClientSession"] = field(default=None, compare=False)
154
161
 
155
162
  def __post_init__(self):
156
163
  if self.connection_type is None:
@@ -172,6 +179,8 @@ class DeviceConfig:
172
179
  return _dataclass_to_dict(self)
173
180
 
174
181
  @staticmethod
175
- def from_dict(cparam_dict: Dict[str, Dict[str, str]]) -> "DeviceConfig":
182
+ def from_dict(config_dict: Dict[str, Dict[str, str]]) -> "DeviceConfig":
176
183
  """Return device config from dict."""
177
- return _dataclass_from_dict(DeviceConfig, cparam_dict)
184
+ if isinstance(config_dict, dict):
185
+ return _dataclass_from_dict(DeviceConfig, config_dict)
186
+ raise SmartDeviceException(f"Invalid device config data: {config_dict}")