python-kasa 0.12.0__py3-none-any.whl → 0.13.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.
kasa/__init__.py CHANGED
@@ -30,9 +30,11 @@ from kasa.emeterstatus import EmeterStatus
30
30
  from kasa.exceptions import (
31
31
  AuthenticationError,
32
32
  DeviceError,
33
+ DeviceUnavailableError,
33
34
  KasaException,
34
35
  TimeoutError,
35
36
  UnsupportedDeviceError,
37
+ UnsupportedEncryptionError,
36
38
  )
37
39
  from kasa.feature import Feature
38
40
  from kasa.interfaces.light import HSV, ColorTempRange, Light, LightState
@@ -68,7 +70,9 @@ __all__ = [
68
70
  "KasaException",
69
71
  "AuthenticationError",
70
72
  "DeviceError",
73
+ "DeviceUnavailableError",
71
74
  "UnsupportedDeviceError",
75
+ "UnsupportedEncryptionError",
72
76
  "TimeoutError",
73
77
  "Credentials",
74
78
  "DeviceConfig",
kasa/cli/common.py CHANGED
@@ -41,7 +41,7 @@ except ImportError:
41
41
 
42
42
  @wraps(echo_func)
43
43
  def wrapper(message=None, *args, **kwargs) -> None:
44
- if message is not None:
44
+ if isinstance(message, str):
45
45
  message = rich_formatting.sub("", message)
46
46
  echo_func(message, *args, **kwargs)
47
47
 
kasa/cli/discover.py CHANGED
@@ -14,6 +14,7 @@ from kasa import (
14
14
  Device,
15
15
  Discover,
16
16
  UnsupportedDeviceError,
17
+ UnsupportedEncryptionError,
17
18
  )
18
19
  from kasa.discover import (
19
20
  NEW_DISCOVERY_REDACTORS,
@@ -170,7 +171,11 @@ async def list(ctx: click.Context) -> DeviceDict:
170
171
 
171
172
  async def print_unsupported(unsupported_exception: UnsupportedDeviceError):
172
173
  if host := unsupported_exception.host:
173
- echo(f"{host:<15} UNSUPPORTED DEVICE")
174
+ if isinstance(unsupported_exception, UnsupportedEncryptionError):
175
+ reason = f"ENCRYPTION {unsupported_exception.encryption_type}"
176
+ echo(f"{host:<15} UNSUPPORTED {reason}")
177
+ else:
178
+ echo(f"{host:<15} UNSUPPORTED DEVICE")
174
179
 
175
180
  echo(
176
181
  f"{'HOST':<15} {'MODEL':<9} {'DEVICE FAMILY':<20} {'ENCRYPT':<7} "
kasa/cli/hub.py CHANGED
@@ -34,8 +34,12 @@ async def hub(dev: Device):
34
34
  @pass_dev
35
35
  async def hub_list(dev: Device):
36
36
  """List hub paired child devices."""
37
- for c in dev.children:
38
- echo(f"{c.device_id}: {c}")
37
+ echo(f"{'INDEX':<5} {'DEVICE ID':<40} {'MODEL':<9} {'AVAILABLE':<9} ALIAS")
38
+ for index, child in enumerate(dev.children):
39
+ echo(
40
+ f"{index:<5} {child.device_id:<40} {child.model:<9} "
41
+ f"{child.is_available!s:<9} {child.alias}"
42
+ )
39
43
 
40
44
 
41
45
  @hub.command(name="supported")
kasa/device.py CHANGED
@@ -277,6 +277,11 @@ class Device(ABC):
277
277
  """Return True if device is off."""
278
278
  return not self.is_on
279
279
 
280
+ @property
281
+ def is_available(self) -> bool:
282
+ """Return False if the device is known to be unreachable."""
283
+ return True
284
+
280
285
  @abstractmethod
281
286
  async def turn_on(self, **kwargs) -> dict:
282
287
  """Turn on the device."""
kasa/discover.py CHANGED
@@ -124,6 +124,7 @@ from kasa.exceptions import (
124
124
  KasaException,
125
125
  TimeoutError,
126
126
  UnsupportedDeviceError,
127
+ UnsupportedEncryptionError,
127
128
  )
128
129
  from kasa.iot.iotdevice import IotDevice, _extract_sys_info
129
130
  from kasa.json import DataClassJSONMixin
@@ -845,6 +846,16 @@ class Discover:
845
846
  discovery_result=discovery_result.to_dict(),
846
847
  host=discovery_result.ip,
847
848
  )
849
+
850
+ if encrypt_type not in {e.value for e in DeviceEncryptionType}:
851
+ raise UnsupportedEncryptionError(
852
+ f"Device {discovery_result.ip} ({type_}) uses unsupported "
853
+ f"encryption type {encrypt_type}, enabling third-party "
854
+ "compatibility in the official app may help",
855
+ discovery_result=discovery_result.to_dict(),
856
+ host=discovery_result.ip,
857
+ encryption_type=encrypt_type,
858
+ )
848
859
  return DeviceConnectionParameters.from_values(
849
860
  type_,
850
861
  encrypt_type,
kasa/exceptions.py CHANGED
@@ -35,6 +35,18 @@ class UnsupportedDeviceError(KasaException):
35
35
  super().__init__(*args)
36
36
 
37
37
 
38
+ class UnsupportedEncryptionError(UnsupportedDeviceError):
39
+ """Exception for devices using an encryption scheme not implemented here.
40
+
41
+ The device type may still be supported on firmware using another scheme.
42
+ ``encryption_type`` is the raw scheme name the device reported, e.g. ``TPAP``.
43
+ """
44
+
45
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
46
+ self.encryption_type: str = kwargs["encryption_type"]
47
+ super().__init__(*args, **kwargs)
48
+
49
+
38
50
  class DeviceError(KasaException):
39
51
  """Base exception for device errors."""
40
52
 
@@ -55,6 +67,10 @@ class AuthenticationError(DeviceError):
55
67
  """Base exception for device authentication errors."""
56
68
 
57
69
 
70
+ class DeviceUnavailableError(DeviceError):
71
+ """Exception for commands to an unreachable device."""
72
+
73
+
58
74
  class _RetryableError(DeviceError):
59
75
  """Retryable exception for device errors."""
60
76
 
kasa/httpclient.py CHANGED
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  import builtins
7
7
  import logging
8
+ import re
8
9
  import ssl
9
10
  import time
10
11
  from typing import Any
@@ -22,6 +23,9 @@ from .json import loads as json_loads
22
23
 
23
24
  _LOGGER = logging.getLogger(__name__)
24
25
 
26
+ # The session token in /stok=<token>/ds URLs, e.g. after a camera's secure login
27
+ _SESSION_TOKEN = re.compile(r"(stok=)[^/?#]+")
28
+
25
29
 
26
30
  def get_cookie_jar() -> aiohttp.CookieJar:
27
31
  """Return a new cookie jar with the correct options for device communication."""
@@ -86,7 +90,8 @@ class HttpClient:
86
90
  )
87
91
  await asyncio.sleep(sleep)
88
92
 
89
- _LOGGER.debug("Posting to %s", url)
93
+ if _LOGGER.isEnabledFor(logging.DEBUG):
94
+ _LOGGER.debug("Posting to %s", _SESSION_TOKEN.sub(r"\1REDACTED", str(url)))
90
95
  response_data = None
91
96
  self._last_url = url
92
97
  self.client.cookie_jar.clear()
kasa/iot/iotbulb.py CHANGED
@@ -90,7 +90,7 @@ TPLINK_KELVIN = {
90
90
  "KL135": ColorTempRange(2500, 9000),
91
91
  r"KL120\(EU\)": ColorTempRange(2700, 6500),
92
92
  r"KL120\(US\)": ColorTempRange(2700, 5000),
93
- r"KL400L5": ColorTempRange(2500, 9000),
93
+ r"KL400": ColorTempRange(2500, 9000),
94
94
  r"KL420": ColorTempRange(2500, 9000),
95
95
  r"KL430": ColorTempRange(2500, 9000),
96
96
  }
@@ -539,8 +539,3 @@ class IotBulb(IotDevice):
539
539
  return await self._query_helper(
540
540
  "smartlife.iot.common.system", "set_dev_alias", {"alias": alias}
541
541
  )
542
-
543
- @property
544
- def max_device_response_size(self) -> int:
545
- """Returns the maximum response size the device can safely construct."""
546
- return 4096
kasa/iot/iotdevice.py CHANGED
@@ -24,7 +24,7 @@ from warnings import warn
24
24
 
25
25
  from ..device import Device, DeviceInfo, WifiNetwork
26
26
  from ..device_type import DeviceType
27
- from ..deviceconfig import DeviceConfig
27
+ from ..deviceconfig import DeviceConfig, DeviceEncryptionType
28
28
  from ..exceptions import KasaException, TimeoutError, UnsupportedDeviceError
29
29
  from ..feature import Feature
30
30
  from ..module import Module
@@ -730,6 +730,13 @@ class IotDevice(Device):
730
730
  @property
731
731
  def max_device_response_size(self) -> int:
732
732
  """Returns the maximum response size the device can safely construct."""
733
+ # Over KLAP, some devices answer a request whose response would be
734
+ # larger than about 4 KiB with a plain html page instead of a response,
735
+ # and have even less room right after a state change.
736
+ if self.config.connection_type.encryption_type is DeviceEncryptionType.Klap:
737
+ return 2048
738
+ if self.device_type in {DeviceType.Bulb, DeviceType.LightStrip}:
739
+ return 4096
733
740
  return 16 * 1024
734
741
 
735
742
  @property
kasa/module.py CHANGED
@@ -160,6 +160,9 @@ class Module(ABC):
160
160
  )
161
161
  ChildLock: Final[ModuleName[smart.ChildLock]] = ModuleName("ChildLock")
162
162
  TriggerLogs: Final[ModuleName[smart.TriggerLogs]] = ModuleName("TriggerLogs")
163
+ TemperatureRecords: Final[ModuleName[smart.TemperatureRecords]] = ModuleName(
164
+ "TemperatureRecords"
165
+ )
163
166
  PowerProtection: Final[ModuleName[smart.PowerProtection]] = ModuleName(
164
167
  "PowerProtection"
165
168
  )
@@ -55,6 +55,7 @@ REDACTORS: dict[str, Callable[[Any], Any] | None] = {
55
55
  "lo": lambda x: 0, # lon on ks240
56
56
  "device_id": lambda x: "REDACTED_" + x[9::],
57
57
  "parent_device_id": lambda x: "REDACTED_" + x[9::], # Hub attached children
58
+ "temp_sensor_device_id": lambda x: "REDACTED_" + x[9::], # Thermostat source
58
59
  "original_device_id": lambda x: "REDACTED_" + x[9::], # Strip children
59
60
  "nickname": lambda x: "I01BU0tFRF9OQU1FIw==" if x else "",
60
61
  "mac": mask_mac,
@@ -223,18 +224,9 @@ class SmartProtocol(BaseProtocol):
223
224
  # Break the requests down as there can be a size limit
224
225
  step = self._multi_request_batch_size
225
226
  if step == 1:
226
- # If step is 1 do not send request batches
227
- for request in multi_requests:
228
- method = request["method"]
229
- req = self.get_smart_request(method, request.get("params"))
230
- resp = await self._transport.send(req)
231
- self._handle_response_error_code(
232
- resp, method, raise_on_error=raise_on_error
233
- )
234
- multi_result[method] = resp["result"]
235
- return multi_result
236
-
237
- for batch_num, i in enumerate(range(0, end, step)):
227
+ # Batching is off, so the loop at the end sends each request on its own
228
+ multi_requests = []
229
+ for batch_num, i in enumerate(range(0, len(multi_requests), step)):
238
230
  requests_step = multi_requests[i : i + step]
239
231
 
240
232
  smart_params = {"requests": requests_step}
@@ -253,8 +245,7 @@ class SmartProtocol(BaseProtocol):
253
245
  if self.REQUIRES_MULTIREQUESTS:
254
246
  raise
255
247
  # P300 does not respond to some batched requests (e.g. both child
256
- # list requests together) so disable batching. Batch size is never
257
- # 1 here as that case sends single requests above.
248
+ # list requests together) so disable batching.
258
249
  self._multi_request_batch_size = 1
259
250
  raise _RetryableError(
260
251
  "Timeout during multi request, multi requests disabled"
@@ -327,7 +318,12 @@ class SmartProtocol(BaseProtocol):
327
318
  self._handle_response_error_code(
328
319
  resp, method, raise_on_error=raise_on_error
329
320
  )
330
- multi_result[method] = resp.get("result")
321
+ result = resp.get("result")
322
+ if iterate_list_pages and result:
323
+ await self._handle_response_lists(
324
+ result, method, params, retry_count=retry_count
325
+ )
326
+ multi_result[method] = result
331
327
  return multi_result
332
328
 
333
329
  async def _execute_query(
@@ -39,6 +39,7 @@ from .powerprotection import PowerProtection
39
39
  from .reportmode import ReportMode
40
40
  from .speaker import Speaker
41
41
  from .temperaturecontrol import TemperatureControl
42
+ from .temperaturerecords import TemperatureRecords
42
43
  from .temperaturesensor import TemperatureSensor
43
44
  from .thermostat import Thermostat
44
45
  from .time import Time
@@ -78,6 +79,7 @@ __all__ = [
78
79
  "TriggerLogs",
79
80
  "FrostProtection",
80
81
  "Thermostat",
82
+ "TemperatureRecords",
81
83
  "Clean",
82
84
  "Consumables",
83
85
  "CleanRecords",
@@ -0,0 +1,32 @@
1
+ """Implementation of the thermostat temperature records module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import timedelta
6
+
7
+ from ..smartmodule import SmartModule
8
+
9
+ #: Value the device uses for slots without a reading.
10
+ NO_READING = -1000
11
+
12
+
13
+ class TemperatureRecords(SmartModule):
14
+ """Implementation of the temperature history of a thermostat.
15
+
16
+ The device keeps a reading for every 15 minutes of the last 24 hours,
17
+ ordered oldest first, with the most recent reading last.
18
+ """
19
+
20
+ REQUIRED_COMPONENT = "temp_record"
21
+ QUERY_GETTER_NAME = "get_temperature_records"
22
+ INTERVAL = timedelta(minutes=15)
23
+ MINIMUM_UPDATE_INTERVAL_SECS = 15 * 60
24
+ MINIMUM_HUB_CHILD_UPDATE_INTERVAL_SECS = 15 * 60
25
+
26
+ @property
27
+ def temperatures(self) -> list[float | None]:
28
+ """Return the readings oldest first, None where there is no reading."""
29
+ return [
30
+ None if value == NO_READING else value / 10
31
+ for value in self.data.get("temp_data", [])
32
+ ]
@@ -9,6 +9,8 @@ from typing import Any
9
9
  from ..device import DeviceInfo
10
10
  from ..device_type import DeviceType
11
11
  from ..deviceconfig import DeviceConfig
12
+ from ..exceptions import DeviceUnavailableError
13
+ from ..feature import Feature
12
14
  from ..protocols.smartprotocol import SmartProtocol, _ChildProtocolWrapper
13
15
  from .smartdevice import ComponentsRaw, SmartDevice
14
16
  from .smartmodule import SmartModule
@@ -49,6 +51,7 @@ class SmartChildDevice(SmartDevice):
49
51
  _protocol = protocol or _ChildProtocolWrapper(self._id, parent.protocol)
50
52
  super().__init__(parent.host, config=parent.config, protocol=_protocol)
51
53
  self._parent = parent
54
+ self._was_available = True
52
55
  self._update_internal_state(info)
53
56
  self._components_raw = component_info_raw
54
57
  self._components = self._parse_components(self._components_raw)
@@ -83,6 +86,10 @@ class SmartChildDevice(SmartDevice):
83
86
  Internal implementation to allow patching of public update in the cli
84
87
  or test framework.
85
88
  """
89
+ if (available := self.is_available) != self._was_available:
90
+ self._was_available = available
91
+ _LOGGER.debug("%s (%s) available: %s", self.alias, self._id, available)
92
+
86
93
  now = time.monotonic()
87
94
  module_queries: list[SmartModule] = []
88
95
  req: dict[str, Any] = {}
@@ -160,6 +167,34 @@ class SmartChildDevice(SmartDevice):
160
167
 
161
168
  return self._device_type
162
169
 
170
+ @property
171
+ def is_available(self) -> bool:
172
+ """Return False if the hub reports the device offline or no longer lists it."""
173
+ listed = self._parent is None or self._id in self._parent._children
174
+ return listed and self._info.get("status") != "offline"
175
+
176
+ async def _initialize_features(self) -> None:
177
+ """Initialize device features."""
178
+ await super()._initialize_features()
179
+ if "status" in self._info:
180
+ self._add_feature(
181
+ Feature(
182
+ self,
183
+ id="available",
184
+ name="Available",
185
+ attribute_getter="is_available",
186
+ category=Feature.Category.Info,
187
+ type=Feature.Type.BinarySensor,
188
+ )
189
+ )
190
+
191
+ async def _query_helper(self, method: str, params: dict | None = None) -> dict:
192
+ # Fail fast on writes, the hub rejects them only after a timeout.
193
+ if not method.startswith("get") and not self.is_available:
194
+ raise DeviceUnavailableError(f"{self.alias} is not available")
195
+
196
+ return await super()._query_helper(method, params)
197
+
163
198
  def __repr__(self) -> str:
164
199
  if not self._parent:
165
200
  return f"<{self.device_type}(child) without parent>"
kasa/smart/smartdevice.py CHANGED
@@ -730,7 +730,7 @@ class SmartDevice(Device):
730
730
 
731
731
  See :meth:`is_on`.
732
732
  """
733
- return await self.protocol.query({"set_device_info": {"device_on": on}})
733
+ return await self._query_helper("set_device_info", {"device_on": on})
734
734
 
735
735
  async def turn_on(self, **kwargs: Any) -> dict:
736
736
  """Turn on the device."""
@@ -833,8 +833,8 @@ class SmartDevice(Device):
833
833
 
834
834
  async def set_alias(self, alias: str) -> dict:
835
835
  """Set the device name (alias)."""
836
- return await self.protocol.query(
837
- {"set_device_info": {"nickname": base64.b64encode(alias.encode()).decode()}}
836
+ return await self._query_helper(
837
+ "set_device_info", {"nickname": base64.b64encode(alias.encode()).decode()}
838
838
  )
839
839
 
840
840
  async def reboot(self, delay: int = 1) -> None:
@@ -843,14 +843,14 @@ class SmartDevice(Device):
843
843
  Note that giving a delay of zero causes this to block,
844
844
  as the device reboots immediately without responding to the call.
845
845
  """
846
- await self.protocol.query({"device_reboot": {"delay": delay}})
846
+ await self._query_helper("device_reboot", {"delay": delay})
847
847
 
848
848
  async def factory_reset(self) -> None:
849
849
  """Reset device back to factory settings.
850
850
 
851
851
  Note, this does not downgrade the firmware.
852
852
  """
853
- await self.protocol.query("device_reset")
853
+ await self._query_helper("device_reset")
854
854
 
855
855
  @property
856
856
  def device_type(self) -> DeviceType:
@@ -85,6 +85,12 @@ class SmartCamChild(SmartChildDevice, SmartCamDevice):
85
85
  # devices
86
86
  self._info = self._map_child_info_from_parent(info)
87
87
 
88
+ @property
89
+ def is_available(self) -> bool:
90
+ """Return False if the hub reports the camera offline or no longer lists it."""
91
+ # Camera children report "online" instead of an "offline" status.
92
+ return super().is_available and self._info.get("online") is not False
93
+
88
94
  @property
89
95
  def device_type(self) -> DeviceType:
90
96
  """Return the device type."""
@@ -215,7 +215,7 @@ class SmartCamDevice(SmartDevice):
215
215
  async def _query_setter_helper(
216
216
  self, method: str, module: str, section: str, params: dict | None = None
217
217
  ) -> dict:
218
- res = await self.protocol.query({method: {module: {section: params}}})
218
+ res = await self._query_helper(method, {module: {section: params}})
219
219
 
220
220
  return res
221
221
 
@@ -293,10 +293,8 @@ class SmartCamDevice(SmartDevice):
293
293
 
294
294
  async def set_alias(self, alias: str) -> dict:
295
295
  """Set the device name (alias)."""
296
- return await self.protocol.query(
297
- {
298
- "setDeviceAlias": {"system": {"sys": {"dev_alias": alias}}},
299
- }
296
+ return await self._query_helper(
297
+ "setDeviceAlias", {"system": {"sys": {"dev_alias": alias}}}
300
298
  )
301
299
 
302
300
  @property
@@ -46,6 +46,7 @@ import asyncio
46
46
  import base64
47
47
  import datetime
48
48
  import hashlib
49
+ import hmac
49
50
  import logging
50
51
  import secrets
51
52
  import struct
@@ -116,8 +117,6 @@ class KlapTransport(BaseTransport):
116
117
  self._local_auth_owner = self.generate_owner_hash(self._credentials).hex()
117
118
  else:
118
119
  self._local_auth_hash = base64.b64decode(self._credentials_hash.encode()) # type: ignore[union-attr]
119
- self._default_credentials_auth_hash: dict[str, bytes] = {}
120
- self._blank_auth_hash: bytes | None = None
121
120
  self._handshake_lock = asyncio.Lock()
122
121
  self._query_lock = asyncio.Lock()
123
122
  self._handshake_done: bool = False
@@ -229,48 +228,21 @@ class KlapTransport(BaseTransport):
229
228
  _LOGGER.debug("handshake1 hashes match with expected credentials")
230
229
  return local_seed, remote_seed, self._local_auth_hash # type: ignore
231
230
 
232
- # Now check against the default setup credentials
233
- for key, value in DEFAULT_CREDENTIALS.items():
234
- if key not in self._default_credentials_auth_hash:
235
- default_credentials = get_default_credentials(value)
236
- self._default_credentials_auth_hash[key] = self.generate_auth_hash(
237
- default_credentials
238
- )
239
-
240
- default_credentials_seed_auth_hash = self.handshake1_seed_auth_hash(
241
- local_seed,
242
- remote_seed,
243
- self._default_credentials_auth_hash[key], # type: ignore
244
- )
245
-
246
- if default_credentials_seed_auth_hash == server_hash:
247
- _LOGGER.debug(
248
- "Device response did not match our expected hash on ip %s,"
249
- "but an authentication with %s default credentials worked",
250
- self._host,
251
- key,
252
- )
253
- return local_seed, remote_seed, self._default_credentials_auth_hash[key] # type: ignore
254
-
255
- # Finally check against blank credentials if not already blank
256
- blank_creds = Credentials()
257
- if self._credentials != blank_creds:
258
- if not self._blank_auth_hash:
259
- self._blank_auth_hash = self.generate_auth_hash(blank_creds)
260
-
261
- blank_seed_auth_hash = self.handshake1_seed_auth_hash(
262
- local_seed,
263
- remote_seed,
264
- self._blank_auth_hash, # type: ignore
265
- )
266
-
267
- if blank_seed_auth_hash == server_hash:
231
+ for description, auth_hash, save_hash in self._fallback_auth_hashes():
232
+ if (
233
+ self.handshake1_seed_auth_hash(local_seed, remote_seed, auth_hash)
234
+ == server_hash
235
+ ):
268
236
  _LOGGER.debug(
269
237
  "Device response did not match our expected hash on ip %s, "
270
- "but an authentication with blank credentials worked",
238
+ "but %s worked",
271
239
  self._host,
240
+ description,
272
241
  )
273
- return local_seed, remote_seed, self._blank_auth_hash # type: ignore
242
+ if save_hash:
243
+ # A stored hash has no e-mail to rebuild this one from
244
+ self._local_auth_hash = auth_hash
245
+ return local_seed, remote_seed, auth_hash
274
246
 
275
247
  msg = (
276
248
  f"Device response did not match our challenge on ip {self._host}, "
@@ -279,6 +251,32 @@ class KlapTransport(BaseTransport):
279
251
  _LOGGER.debug(msg)
280
252
  raise AuthenticationError(msg)
281
253
 
254
+ def _fallback_auth_hashes(self) -> list[tuple[str, bytes, bool]]:
255
+ """Return fallback descriptions, auth hashes and whether to save the hash."""
256
+ username = self._credentials.username if self._credentials else ""
257
+ setup_password = get_default_credentials(DEFAULT_CREDENTIALS["KASA"]).password
258
+ # The Kasa app uses this pair, with the e-mail trimmed and lowercased,
259
+ # when the discovery reply has ANS
260
+ fallbacks = [
261
+ (
262
+ "the account e-mail with the setup password",
263
+ Credentials(name, setup_password),
264
+ True,
265
+ )
266
+ for name in dict.fromkeys([username, username.strip().lower()])
267
+ if name
268
+ ]
269
+ fallbacks += [
270
+ (f"the {key} default credentials", get_default_credentials(value), False)
271
+ for key, value in DEFAULT_CREDENTIALS.items()
272
+ ]
273
+ fallbacks.append(("blank credentials", Credentials(), False))
274
+ return [
275
+ (description, self.generate_auth_hash(credentials), save_hash)
276
+ for description, credentials, save_hash in fallbacks
277
+ if credentials != self._credentials
278
+ ]
279
+
282
280
  async def perform_handshake2(
283
281
  self, local_seed: bytes, remote_seed: bytes, auth_hash: bytes
284
282
  ) -> KlapEncryptionSession:
@@ -396,6 +394,18 @@ class KlapTransport(BaseTransport):
396
394
  if TYPE_CHECKING:
397
395
  assert self._encryption_session
398
396
  assert isinstance(response_data, bytes)
397
+ # A message is a 32 byte signature followed by whole AES blocks.
398
+ # Some devices answer with a plain html page instead.
399
+ if len(response_data) < 48 or (len(response_data) - 32) % 16:
400
+ raise KasaException(
401
+ f"Device {self._host} sent a response that is not a KLAP "
402
+ f"message ({len(response_data)} bytes): {response_data[:64]!r}"
403
+ )
404
+ if not self._encryption_session.is_signed(response_data, seq):
405
+ raise KasaException(
406
+ f"Device {self._host} sent a response with an invalid "
407
+ f"signature for request with seq {seq}"
408
+ )
399
409
  try:
400
410
  decrypted_response = self._encryption_session.decrypt(response_data)
401
411
  except Exception as ex:
@@ -535,6 +545,11 @@ class KlapEncryptionSession:
535
545
  ).digest()
536
546
  return (signature + ciphertext, self._seq)
537
547
 
548
+ def is_signed(self, msg: bytes, seq: int) -> bool:
549
+ """Return whether the message is signed for the request with seq."""
550
+ signature = _sha256(self._sig + PACK_SIGNED_LONG(seq) + msg[32:])
551
+ return hmac.compare_digest(msg[:32], signature)
552
+
538
553
  def decrypt(self, msg: bytes) -> str:
539
554
  """Decrypt the data."""
540
555
  decryptor = self._cipher.decryptor()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-kasa
3
- Version: 0.12.0
3
+ Version: 0.13.0
4
4
  Summary: Python API for TP-Link Kasa and Tapo devices
5
5
  Project-URL: Homepage, https://github.com/python-kasa/python-kasa
6
6
  Project-URL: Bug Tracker, https://github.com/python-kasa/python-kasa/issues
@@ -211,17 +211,20 @@ The following devices have been tested and confirmed as working. If your device
211
211
  > [!NOTE]
212
212
  > The hub attached Tapo buttons S200B and S200D do not currently support alerting when the button is pressed.
213
213
 
214
- > [!NOTE]
214
+ > [!WARNING]
215
215
  > Some firmware versions of Tapo Cameras will not authenticate unless you enable "Tapo Lab" > "Third-Party Compatibility" in the native Tapo app.
216
216
  > Alternatively, you can factory reset and then prevent the device from accessing the internet.
217
+ >
218
+ > Devices using the TPAP encryption, found on some newer devices and/or firmware versions, are not currently supported.
219
+ > Enabling third-party compatibility may help on some of them as well.
217
220
 
218
221
  <!--Do not edit text inside the SUPPORTED section below -->
219
222
  <!--SUPPORTED_START-->
220
223
  ### Supported Kasa devices
221
224
 
222
- - **Plugs**: EP10, EP25[^2], HS100[^2], HS103, HS105, HS110, KP100, KP105, KP115, KP125, KP125M[^1], KP401
225
+ - **Plugs**: EP10, EP25[^2][^4], HS100[^2], HS103, HS105, HS110, KP100, KP105, KP115, KP125, KP125M[^1][^4], KP401
223
226
  - **Power Strips**: EP40, EP40M[^1], HS107, HS300, KP200, KP303, KP400
224
- - **Wall Switches**: ES20M, HS200[^2], HS210, HS220[^2], KP405, KS200, KS200M, KS205[^1], KS220, KS220M, KS225[^1], KS230, KS240[^1]
227
+ - **Wall Switches**: ES20M, HS200[^2], HS210, HS220[^2], KP405, KS200, KS200M, KS205[^1], KS220, KS220M, KS225[^1], KS230[^2], KS240[^1]
225
228
  - **Bulbs**: KL110, KL110B, KL120, KL125, KL130, KL135, KL50, KL60, LB100, LB110, LB130
226
229
  - **Light Strips**: KL400L10, KL400L5, KL420L5, KL430
227
230
  - **Hubs**: KH100[^1]
@@ -229,21 +232,22 @@ The following devices have been tested and confirmed as working. If your device
229
232
 
230
233
  ### Supported Tapo[^1] devices
231
234
 
232
- - **Plugs**: P100, P105, P110, P110M, P115, P116M, P125M, P135, TP10, TP15
235
+ - **Plugs**: P100, P105, P110[^4], P110M[^4], P115, P116M, P125M, P135, TP10, TP15
233
236
  - **Power Strips**: P210M, P300, P304M, P306, P316M, TP25
234
- - **Wall Switches**: S210, S220, S500, S500D, S505, S505D, S515D, TS15
237
+ - **Wall Switches**: S210, S220, S500, S500D, S505, S505D[^4], S515D, TS15
235
238
  - **Bulbs**: L430C, L430P, L510B, L510E, L530B, L530E, L530EA, L535E, L630
236
239
  - **Light Strips**: L900-10, L900-5, L920-5, L930-5
237
240
  - **Cameras**: C100, C101, C110, C200, C210, C220, C225, C325WB, C460, C520WS, C720, TC40, TC65, TC70
238
241
  - **Doorbells and chimes**: D100C, D130, D230, TD21
239
- - **Vacuums**: RV20 Max Plus, RV30 Max
242
+ - **Vacuums**: RV20 Max Plus[^4], RV30 Max
240
243
  - **Hubs**: H100, H200
241
244
  - **Hub-Connected Devices[^3]**: S200B, S200D, T100, T110, T300, T310, T315
242
245
 
243
- <!--SUPPORTED_END-->
244
246
  [^1]: Model requires authentication
245
247
  [^2]: Newer versions require authentication
246
248
  [^3]: Devices may work across TAPO/KASA branded hubs
249
+ [^4]: Some versions are not supported, see SUPPORTED.md
250
+ <!--SUPPORTED_END-->
247
251
 
248
252
  See [supported devices in our documentation](SUPPORTED.md) for more detailed information about tested hardware and software versions.
249
253
 
@@ -1,27 +1,27 @@
1
- kasa/__init__.py,sha256=Bpu9H0z_6vNEIZqtejXSiXU4X_-CdqW841aOG7wJ-6o,4868
1
+ kasa/__init__.py,sha256=PZkwVx03wu6uvVM_ea-_LU1gbT71uxS6BOxWXP2jKcI,4992
2
2
  kasa/cachedzoneinfo.py,sha256=wrttrnBRqbjKDpYeuGkdNSASHABQxHVFzi1811-IkyE,777
3
3
  kasa/credentials.py,sha256=9O5CTiNcoy3-LPT2vbFey5iGpAj7JMSP4s1n_RPdPno,1999
4
- kasa/device.py,sha256=aIZk4faleLgkOjo1mt0Hoq8JtzH97fs5tKqIII908uQ,20936
4
+ kasa/device.py,sha256=3Mxl6yslGNcqL0DkkXnALjT1UrvonGqmqXXATIy1E5E,21076
5
5
  kasa/device_factory.py,sha256=I2nUORVky2PM5reZp4DGklYNCB19f8vlSw0k7_XnRmc,8823
6
6
  kasa/device_type.py,sha256=1PMELn2IuMEfuNrHn8rjTiC5AShYCvQf3x8gYvoMLlA,834
7
7
  kasa/deviceconfig.py,sha256=0y4wZVA1ClZ0rrdh1VkxQdmuW34aipDC6KpYbTtBk2M,6595
8
- kasa/discover.py,sha256=-xZGcmEoWSO1YzCm2ARhSS_R-BTtObD1lfbXLeIZO1o,37297
8
+ kasa/discover.py,sha256=2aHQchh4USozlVGGRsS6cowTaj6gTjp1RiPIvUF99fY,37822
9
9
  kasa/emeterstatus.py,sha256=5JtJFWQcpaqquHxvYD9-TsbAbdHGEJiuT7wxVueDV_M,2558
10
- kasa/exceptions.py,sha256=6-t31yuWt5I2wtfW5w34W4swsaSss4B4xz4LSyUlSyQ,6013
10
+ kasa/exceptions.py,sha256=N1CRh4xBUe-SBSW_QVJOAcsBA9PlLLJf2I2w3r_I52o,6588
11
11
  kasa/feature.py,sha256=-x5pck17MDtirZvcqIGyJuJ3TGKczaLuy0wuyaYBlKA,11729
12
- kasa/httpclient.py,sha256=LPmBWYYWj5aF9DaARxB4EJ31Q5WY886S-osWkvAeau0,6472
12
+ kasa/httpclient.py,sha256=x43X2sWWkdg0qv8MpD5Pciyky19ZBj0-CNNgrLQiSbA,6703
13
13
  kasa/json.py,sha256=KMJh-A5nQR2Uny8nKRzJEJc2o-JRewTarok_nqS7hX4,1021
14
- kasa/module.py,sha256=zGS4WxMEmfFXrNDFMDPK8atHvUSWuIiiDIqEFP5CVyI,12086
14
+ kasa/module.py,sha256=K-xoo0r8Ey8ECvbwtPkrBlF7IflU8-9Pd8KXBjVrEo0,12203
15
15
  kasa/modulemapping.py,sha256=79mtaewNYvhFjn1Jo39xE57aid5gn08A-45bOS0vgMs,499
16
16
  kasa/modulemapping.pyi,sha256=sUntMvhBf6eoFK61aAanXBjEqXlVEaiPS2cvrX-3RAI,3819
17
17
  kasa/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
18
  kasa/cli/__init__.py,sha256=S8z6xs4EPXXtF2wLwuvDLjcuy46c0jWaG0wiqqU5FiY,27
19
19
  kasa/cli/__main__.py,sha256=B5nsKIZhYL1upQHrrKXnqE3t261v8nthD52e8m3DAgY,88
20
- kasa/cli/common.py,sha256=Jc6ZkeJDD3z3cMrwT1WUmmOPQPvrTVZ_FCriqC5XCZ0,9413
20
+ kasa/cli/common.py,sha256=TTzSFyTkrTeAzoQSxlECq1K4UGullR_liyjGH7f0LkE,9418
21
21
  kasa/cli/device.py,sha256=wAAENY8Z7Xcb35aKrGKrJspeOyNBCauuTO50nVHRJ5k,5861
22
- kasa/cli/discover.py,sha256=SUQ396O-Jr0Gp0jP8yafpS2AsLrtClRn7pTrspr_F18,12598
22
+ kasa/cli/discover.py,sha256=Qx_4xuAX7XPCnPIlpEVq2Hxym7eqaG9roPwHTLjMvOU,12866
23
23
  kasa/cli/feature.py,sha256=ThQj-Tg_lauA2l58HVLUvr5WJ8sXHUz2ivTGkg8c-dk,4328
24
- kasa/cli/hub.py,sha256=qU_ri4GRXXYCQfLpYYDk_ONZFNEBbdo8Qo6GYZmtQp4,2412
24
+ kasa/cli/hub.py,sha256=_Otf-8oVZYixB_0ZcC5D6jPj2a-ZoNRwTOzEtgH0rpY,2623
25
25
  kasa/cli/lazygroup.py,sha256=7UhsP1WKDXUdc-XhN66e7ueQvLZAzWBJByBM7wUDXgw,2536
26
26
  kasa/cli/light.py,sha256=gIwHTFZ8xRAdl6G4AHRreRiy9tk5M3cQwtLkz_3J-fo,7561
27
27
  kasa/cli/main.py,sha256=kwRDTSi6uBQkxsOdYjfJmi4xJ5Ry3HxFNp9WHI6uVlQ,11661
@@ -43,9 +43,9 @@ kasa/interfaces/thermostat.py,sha256=F2NG7CuS0_wSldyj_qmZQF1xhFafNyKikw59e5mgSGY
43
43
  kasa/interfaces/time.py,sha256=MTrhDdzMc4Cad9AB3CC0yhHCif7tIipK4dgcJ-Lt7GA,585
44
44
  kasa/iot/__init__.py,sha256=Ib0O2S13k2_JaOlmDe4x16HZCDIK39n3hgdEeton00I,449
45
45
  kasa/iot/effects.py,sha256=au35HDrHso7JRdv9bPSdkepdpR8NbSp-gFGHW2SKZUw,7506
46
- kasa/iot/iotbulb.py,sha256=M8rYonMS590n41-7q5vInutGXaOP6I2yvh7M9bBpYgY,19054
46
+ kasa/iot/iotbulb.py,sha256=_-EU_6caV-xG6ZWgb3ls5UZ084kb3BGctP-AmEO76Rg,18889
47
47
  kasa/iot/iotcamera.py,sha256=TmALKJCAqaDz4OxmkWD8lJdTzBf_TLPP8zGESvivKjI,1064
48
- kasa/iot/iotdevice.py,sha256=TMFrA5TV8ByjNASqlDToTbS-RzxfPBfl-BR4AhUap8I,28983
48
+ kasa/iot/iotdevice.py,sha256=P37shp7hWjtOzEpsRebybmclS9MSkfVDtJZ1mgpmvoM,29428
49
49
  kasa/iot/iotdimmer.py,sha256=p60obMjnmcOAKAgUX4mWEjLaG7jIrHXOe1VtkpPDbt0,7945
50
50
  kasa/iot/iotlightstrip.py,sha256=mCovTLr2LmFrHfmGykyAwUfdDZK_n99fBvhcjSHG6u4,2109
51
51
  kasa/iot/iotmodule.py,sha256=CnH0Vy8dSVohSF5c8ikuJapdLZOz6LdINvSjSPAf3u8,2342
@@ -73,13 +73,13 @@ kasa/protocols/__init__.py,sha256=KnYWXtdpF2AXM0pZ7JSMTDnYs6sfSB1du7juX_WY8tU,34
73
73
  kasa/protocols/iotprotocol.py,sha256=W4q8SnWTcSsGVbZBLKGDaEZ1cBgGbIy5dOFmc7mxNY4,6868
74
74
  kasa/protocols/protocol.py,sha256=oy4Rqrp6pn6mG77xjiGv3Xq2pxHRm8_-D_LXx7y3ScM,3133
75
75
  kasa/protocols/smartcamprotocol.py,sha256=7gA2rRQS6Qrtb-MIBoPzlbDECfsKtcGUUDPH8jLuAu4,8989
76
- kasa/protocols/smartprotocol.py,sha256=5GeI0Qhx4EIG_GYTsBbqnA2a-snxUU2O0JNwJixHRjA,20647
76
+ kasa/protocols/smartprotocol.py,sha256=7E8TJqu2i0LbHWUfhgbNvXw3gJTdh7XHQcXmYusgrBc,20514
77
77
  kasa/smart/__init__.py,sha256=gdmi-Doe7dnv7e8ab_892lr9IdOXeFa3XlU3u_CePCk,198
78
78
  kasa/smart/effects.py,sha256=J_mkX2L-7IJSaL5K4CpBaOdk-humx3cVxg7yioGhtF4,11498
79
- kasa/smart/smartchilddevice.py,sha256=QiYkKm2P5mfotAB3vqhGAscDlMR9TCQIwgpz1cywbas,6042
80
- kasa/smart/smartdevice.py,sha256=f3i_tva597sDUJHcaKmSvKBeJlogjgUR8n-MztgUjOM,34794
79
+ kasa/smart/smartchilddevice.py,sha256=p7kFXH-Y6TNLJ54LBvHnYNKgJhtYhTW479uC7Ftr4QE,7510
80
+ kasa/smart/smartdevice.py,sha256=u-TUhMmH7ZX3pdWcfGD5NBV6Cbu949mwF7oyUq7iqBE,34784
81
81
  kasa/smart/smartmodule.py,sha256=8PAh6KCiO4NWCJuevSgxA6CIwZFliDzD2t8CwaYs_Uc,8986
82
- kasa/smart/modules/__init__.py,sha256=h0_CK6gXMCujwvmo6j47Kcnw9BsiXm7-2D5pUltU8Hg,2430
82
+ kasa/smart/modules/__init__.py,sha256=z82b9uykmG8OHi5hLKKXIPd7by_bRXPGHi7DfJguwyg,2507
83
83
  kasa/smart/modules/alarm.py,sha256=LpeHbgZdG4uTxebNvd0gE_Y5iEJQW9jWQdi5in1QvX4,8556
84
84
  kasa/smart/modules/autooff.py,sha256=TAk-YWRy8EikXesJbDe20HlV-UgtuHD6mCvn3jE0MzA,3285
85
85
  kasa/smart/modules/batterysensor.py,sha256=yjETEmFpQ-ivaZzxSSUgq-y5zulTNQ-14nRFNaD_BG4,2314
@@ -118,6 +118,7 @@ kasa/smart/modules/powerprotection.py,sha256=zW4bgaC0UZnEFpTt06bHIzHbwIMG5vjgM7s
118
118
  kasa/smart/modules/reportmode.py,sha256=LxnKEseugqooNnz5BM4edow_Tc7Twu6hX7_aMnLMruE,1070
119
119
  kasa/smart/modules/speaker.py,sha256=nBxYS5avSgx2Vpn4gJUD4UHkyTAKXZk3fdU-_8nZUps,1938
120
120
  kasa/smart/modules/temperaturecontrol.py,sha256=hPVmzxCsFIusYOs2IA64sfI47cruQu7S949iwjIXn0w,5688
121
+ kasa/smart/modules/temperaturerecords.py,sha256=WlXb6tXjV19PQutgi4QnSa1Qa7y2XyvnqFq1qm4lEd4,1006
121
122
  kasa/smart/modules/temperaturesensor.py,sha256=IM-V9yDEME_rhfut9KqNpaGt459Zhsm9yEIxzyPq2xY,2718
122
123
  kasa/smart/modules/thermostat.py,sha256=E4vteL09VvlU3LKSBibGvEfeZR4IfU4wFZjvdQ4Qpn4,2670
123
124
  kasa/smart/modules/time.py,sha256=g7wEYeYBqX5RPshwzzcr-6GsrxzOx2klQ-Tslma6f-k,3190
@@ -125,8 +126,8 @@ kasa/smart/modules/triggerlogs.py,sha256=_8-138YuVNDbXsNmbmRn4_a_efE2N4OR_nKCYSR
125
126
  kasa/smart/modules/waterleaksensor.py,sha256=3PvnEGbXK7sNh9f4O_xwIs1kuS8MDGC49-GoKNc4TGQ,3080
126
127
  kasa/smartcam/__init__.py,sha256=hZcUU3A6NRSjlSPVadbFMYlCKfqiKTxr4uh7Ja69kZ0,247
127
128
  kasa/smartcam/detectionmodule.py,sha256=st4HQeC2yt5f9NHuvXVXE-IW5LUX8YFCkZJ9PVP5Sb4,1827
128
- kasa/smartcam/smartcamchild.py,sha256=WNU8_bRMhVUcRzsojxhADxyL79ovfNT7cBa0NrWShHI,4222
129
- kasa/smartcam/smartcamdevice.py,sha256=F4-2PGtqij1KaByoEl9p7_NkhkP5RmkKwzciKShnx0s,16969
129
+ kasa/smartcam/smartcamchild.py,sha256=aMA0pzA8yP8eoHAKlBZZc3OCta5tZTbiWxeDKqECbtI,4513
130
+ kasa/smartcam/smartcamdevice.py,sha256=hLENs1TPKjRJdETBgj1qOox_4Xchk3E8JuNQO1n9uUE,16932
130
131
  kasa/smartcam/smartcammodule.py,sha256=aUGI_PnpI3z9ib98BpAEERhsivUj3B_Gr6g3OdRVw_g,4453
131
132
  kasa/smartcam/modules/__init__.py,sha256=P9WiUgVWc0ksmjEakqrEXOj25AGEg-QRZfHI3dvyZiI,1337
132
133
  kasa/smartcam/modules/alarm.py,sha256=dvpok39Yq-UVFWHJboFwRRYLi2aNCWiphXZLXr3nfLE,6926
@@ -155,14 +156,14 @@ kasa/smartcam/modules/vehicledetection.py,sha256=SaFBOSY4C9sQtvVWNA8qIFqj45ROhO_
155
156
  kasa/transports/__init__.py,sha256=JRY_-AfZ9y4e3HN9sEH76kStPFW7Gg_rymw8NtzRQZs,632
156
157
  kasa/transports/aestransport.py,sha256=8z0mAxheDCq9iz2zeI55zuw518VC-ajeXfCoPIqlkQM,18959
157
158
  kasa/transports/basetransport.py,sha256=O6fySc-jg05jfE-Dy0qmhme5KNOW14gtZOo5gOck2kk,2439
158
- kasa/transports/klaptransport.py,sha256=_WLj3On51T3tIsUt1WO5c3P6TxjA5ybKCqZnPEqW6I4,20411
159
+ kasa/transports/klaptransport.py,sha256=zpckYNSu7_tPLVZ7bTLPiIxqAEAKyrRWRark7rriuy4,21243
159
160
  kasa/transports/linkietransport.py,sha256=e8zNRHt12_KKzLp-fmYpwLKNyEwdsiqu3yK3tUlxv6k,4020
160
161
  kasa/transports/sslaestransport.py,sha256=cF0JM7PKGVb500mRA6yGnnzosii2iiHK_nw0hIL9_MU,24631
161
162
  kasa/transports/sslcontext.py,sha256=4L6Bdg804mCuazxImJt8M_Ved-UP6RtUU-D7dBjKpnc,1214
162
163
  kasa/transports/ssltransport.py,sha256=qtRfjRq0VAmp_h_XeR4NlaV2uCH55GwHqujq3KA8pJk,8352
163
164
  kasa/transports/xortransport.py,sha256=Q35Wiju681iSI979NcQT6djv698KTaj9YKp0iQi1OFw,8908
164
- python_kasa-0.12.0.dist-info/METADATA,sha256=UrkftteT93OiqFaIpH5p0eJJ0iQ5IQNFw3gVRtNj-qQ,12154
165
- python_kasa-0.12.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
166
- python_kasa-0.12.0.dist-info/entry_points.txt,sha256=gTVS_oUcmt4q77WSkppQofMelqufh0zeXvvUkmBPRJA,47
167
- python_kasa-0.12.0.dist-info/licenses/LICENSE,sha256=Klt9aEsei738epLgYqeikhpdBWwMvU1VAli14Bxlc5c,33218
168
- python_kasa-0.12.0.dist-info/RECORD,,
165
+ python_kasa-0.13.0.dist-info/METADATA,sha256=C0yHvSQ0yD8C1JcdmpAzVgDsjEZ0ed9Nt8l5U5UUAO8,12434
166
+ python_kasa-0.13.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
167
+ python_kasa-0.13.0.dist-info/entry_points.txt,sha256=gTVS_oUcmt4q77WSkppQofMelqufh0zeXvvUkmBPRJA,47
168
+ python_kasa-0.13.0.dist-info/licenses/LICENSE,sha256=Klt9aEsei738epLgYqeikhpdBWwMvU1VAli14Bxlc5c,33218
169
+ python_kasa-0.13.0.dist-info/RECORD,,