python-kasa 0.6.2.1__py3-none-any.whl → 0.7.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. kasa/__init__.py +90 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +414 -0
  5. kasa/device_factory.py +83 -44
  6. kasa/device_type.py +7 -3
  7. kasa/deviceconfig.py +16 -9
  8. kasa/discover.py +100 -81
  9. kasa/emeterstatus.py +7 -5
  10. kasa/exceptions.py +41 -26
  11. kasa/feature.py +201 -0
  12. kasa/httpclient.py +21 -14
  13. kasa/interfaces/__init__.py +16 -0
  14. kasa/interfaces/fan.py +20 -0
  15. kasa/interfaces/led.py +38 -0
  16. kasa/interfaces/light.py +138 -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} +103 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +176 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +45 -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 +263 -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 +166 -0
  69. kasa/smart/modules/lighteffect.py +115 -0
  70. kasa/smart/modules/lightpreset.py +142 -0
  71. kasa/smart/modules/lightstripeffect.py +135 -0
  72. kasa/smart/modules/lighttransition.py +183 -0
  73. kasa/smart/modules/reportmode.py +36 -0
  74. kasa/smart/modules/temperaturecontrol.py +177 -0
  75. kasa/smart/modules/temperaturesensor.py +77 -0
  76. kasa/smart/modules/time.py +57 -0
  77. kasa/smart/modules/waterleaksensor.py +66 -0
  78. kasa/smart/smartchilddevice.py +65 -0
  79. kasa/smart/smartdevice.py +653 -0
  80. kasa/smart/smartmodule.py +112 -0
  81. kasa/smartprotocol.py +107 -41
  82. kasa/tests/conftest.py +27 -562
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/fakeprotocol_iot.py +64 -6
  86. kasa/tests/fakeprotocol_smart.py +215 -22
  87. kasa/tests/fixtureinfo.py +154 -0
  88. kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +221 -0
  89. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +547 -0
  90. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +391 -0
  91. kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +1557 -0
  92. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +899 -0
  93. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +479 -0
  94. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +449 -0
  95. kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +173 -0
  96. kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +204 -0
  97. kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +566 -0
  98. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  99. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  100. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  101. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  102. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  103. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  104. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  105. kasa/tests/smart/__init__.py +0 -0
  106. kasa/tests/smart/features/__init__.py +0 -0
  107. kasa/tests/smart/features/test_brightness.py +55 -0
  108. kasa/tests/smart/features/test_colortemp.py +30 -0
  109. kasa/tests/smart/modules/__init__.py +0 -0
  110. kasa/tests/smart/modules/test_contact.py +28 -0
  111. kasa/tests/smart/modules/test_fan.py +79 -0
  112. kasa/tests/smart/modules/test_firmware.py +108 -0
  113. kasa/tests/smart/modules/test_humidity.py +28 -0
  114. kasa/tests/smart/modules/test_light_effect.py +41 -0
  115. kasa/tests/smart/modules/test_temperature.py +47 -0
  116. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  117. kasa/tests/smart/modules/test_waterleak.py +42 -0
  118. kasa/tests/test_aestransport.py +115 -23
  119. kasa/tests/test_bulb.py +116 -86
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +242 -0
  123. kasa/tests/test_device.py +268 -0
  124. kasa/tests/test_device_factory.py +61 -35
  125. kasa/tests/test_device_type.py +1 -1
  126. kasa/tests/test_deviceconfig.py +2 -2
  127. kasa/tests/test_dimmer.py +42 -33
  128. kasa/tests/test_discovery.py +112 -63
  129. kasa/tests/test_emeter.py +14 -10
  130. kasa/tests/test_feature.py +205 -0
  131. kasa/tests/test_httpclient.py +9 -9
  132. kasa/tests/test_iotdevice.py +286 -0
  133. kasa/tests/test_klapprotocol.py +94 -37
  134. kasa/tests/test_lightstrip.py +24 -19
  135. kasa/tests/test_plug.py +46 -8
  136. kasa/tests/test_protocol.py +8 -10
  137. kasa/tests/test_readme_examples.py +87 -26
  138. kasa/tests/test_smartdevice.py +203 -311
  139. kasa/tests/test_smartprotocol.py +130 -25
  140. kasa/tests/test_strip.py +15 -6
  141. kasa/tests/test_usage.py +1 -1
  142. kasa/xortransport.py +15 -12
  143. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev1.dist-info/RECORD +239 -0
  145. kasa/modules/emeter.py +0 -111
  146. kasa/smartlightstrip.py +0 -143
  147. kasa/smartplug.py +0 -91
  148. kasa/tapo/__init__.py +0 -7
  149. kasa/tapo/childdevice.py +0 -41
  150. kasa/tapo/tapobulb.py +0 -262
  151. kasa/tapo/tapodevice.py +0 -409
  152. kasa/tapo/tapoplug.py +0 -45
  153. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  154. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  155. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  156. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  157. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  158. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  159. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  160. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  161. python_kasa-0.6.2.1.dist-info/RECORD +0 -167
  162. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/entry_points.txt +0 -0
kasa/__init__.py CHANGED
@@ -1,20 +1,24 @@
1
1
  """Python interface for TP-Link's smart home devices.
2
2
 
3
- All common, shared functionalities are available through `SmartDevice` class::
3
+ All common, shared functionalities are available through `Device` class::
4
4
 
5
- x = SmartDevice("192.168.1.1")
6
- print(x.sys_info)
5
+ >>> from kasa import Discover
6
+ >>> x = await Discover.discover_single("192.168.1.1")
7
+ >>> print(x.model)
7
8
 
8
- For device type specific actions `SmartBulb`, `SmartPlug`, or `SmartStrip`
9
- should be used instead.
9
+ For device type specific actions `modules` and `features` should be used instead.
10
10
 
11
- Module-specific errors are raised as `SmartDeviceException` and are expected
11
+ Module-specific errors are raised as `KasaException` and are expected
12
12
  to be handled by the user of the library.
13
13
  """
14
+
14
15
  from importlib.metadata import version
16
+ from typing import TYPE_CHECKING
15
17
  from warnings import warn
16
18
 
17
19
  from kasa.credentials import Credentials
20
+ from kasa.device import Device
21
+ from kasa.device_type import DeviceType
18
22
  from kasa.deviceconfig import (
19
23
  ConnectionType,
20
24
  DeviceConfig,
@@ -24,23 +28,21 @@ from kasa.deviceconfig import (
24
28
  from kasa.discover import Discover
25
29
  from kasa.emeterstatus import EmeterStatus
26
30
  from kasa.exceptions import (
27
- AuthenticationException,
28
- SmartDeviceException,
29
- TimeoutException,
30
- UnsupportedDeviceException,
31
+ AuthenticationError,
32
+ DeviceError,
33
+ KasaException,
34
+ TimeoutError,
35
+ UnsupportedDeviceError,
31
36
  )
37
+ from kasa.feature import Feature
38
+ from kasa.interfaces.light import HSV, ColorTempRange, Light, LightState
32
39
  from kasa.iotprotocol import (
33
40
  IotProtocol,
34
41
  _deprecated_TPLinkSmartHomeProtocol, # noqa: F401
35
42
  )
43
+ from kasa.module import Module
36
44
  from kasa.protocol import BaseProtocol
37
- from kasa.smartbulb import SmartBulb, SmartBulbPreset, TurnOnBehavior, TurnOnBehaviors
38
- from kasa.smartdevice import DeviceType, SmartDevice
39
- from kasa.smartdimmer import SmartDimmer
40
- from kasa.smartlightstrip import SmartLightStrip
41
- from kasa.smartplug import SmartPlug
42
45
  from kasa.smartprotocol import SmartProtocol
43
- from kasa.smartstrip import SmartStrip
44
46
 
45
47
  __version__ = version("python-kasa")
46
48
 
@@ -50,21 +52,23 @@ __all__ = [
50
52
  "BaseProtocol",
51
53
  "IotProtocol",
52
54
  "SmartProtocol",
53
- "SmartBulb",
54
- "SmartBulbPreset",
55
+ "LightState",
55
56
  "TurnOnBehaviors",
56
57
  "TurnOnBehavior",
57
58
  "DeviceType",
59
+ "Feature",
58
60
  "EmeterStatus",
59
- "SmartDevice",
60
- "SmartDeviceException",
61
- "SmartPlug",
62
- "SmartStrip",
63
- "SmartDimmer",
64
- "SmartLightStrip",
65
- "AuthenticationException",
66
- "UnsupportedDeviceException",
67
- "TimeoutException",
61
+ "Device",
62
+ "Light",
63
+ "ColorTempRange",
64
+ "HSV",
65
+ "Plug",
66
+ "Module",
67
+ "KasaException",
68
+ "AuthenticationError",
69
+ "DeviceError",
70
+ "UnsupportedDeviceError",
71
+ "TimeoutError",
68
72
  "Credentials",
69
73
  "DeviceConfig",
70
74
  "ConnectionType",
@@ -72,11 +76,70 @@ __all__ = [
72
76
  "DeviceFamilyType",
73
77
  ]
74
78
 
79
+ from . import iot
80
+ from .iot.modules.lightpreset import IotLightPreset
81
+
75
82
  deprecated_names = ["TPLinkSmartHomeProtocol"]
83
+ deprecated_smart_devices = {
84
+ "SmartDevice": iot.IotDevice,
85
+ "SmartPlug": iot.IotPlug,
86
+ "SmartBulb": iot.IotBulb,
87
+ "SmartLightStrip": iot.IotLightStrip,
88
+ "SmartStrip": iot.IotStrip,
89
+ "SmartDimmer": iot.IotDimmer,
90
+ "SmartBulbPreset": IotLightPreset,
91
+ }
92
+ deprecated_exceptions = {
93
+ "SmartDeviceException": KasaException,
94
+ "UnsupportedDeviceException": UnsupportedDeviceError,
95
+ "AuthenticationException": AuthenticationError,
96
+ "TimeoutException": TimeoutError,
97
+ }
76
98
 
77
99
 
78
100
  def __getattr__(name):
79
101
  if name in deprecated_names:
80
102
  warn(f"{name} is deprecated", DeprecationWarning, stacklevel=1)
81
103
  return globals()[f"_deprecated_{name}"]
104
+ if name in deprecated_smart_devices:
105
+ new_class = deprecated_smart_devices[name]
106
+ package_name = ".".join(new_class.__module__.split(".")[:-1])
107
+ warn(
108
+ f"{name} is deprecated, use {new_class.__name__} "
109
+ + f"from package {package_name} instead or use Discover.discover_single()"
110
+ + " and Device.connect() to support new protocols",
111
+ DeprecationWarning,
112
+ stacklevel=1,
113
+ )
114
+ return new_class
115
+ if name in deprecated_exceptions:
116
+ new_class = deprecated_exceptions[name]
117
+ msg = f"{name} is deprecated, use {new_class.__name__} instead"
118
+ warn(msg, DeprecationWarning, stacklevel=1)
119
+ return new_class
82
120
  raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
121
+
122
+
123
+ if TYPE_CHECKING:
124
+ SmartDevice = Device
125
+ SmartBulb = iot.IotBulb
126
+ SmartPlug = iot.IotPlug
127
+ SmartLightStrip = iot.IotLightStrip
128
+ SmartStrip = iot.IotStrip
129
+ SmartDimmer = iot.IotDimmer
130
+ SmartBulbPreset = IotLightPreset
131
+
132
+ SmartDeviceException = KasaException
133
+ UnsupportedDeviceException = UnsupportedDeviceError
134
+ AuthenticationException = AuthenticationError
135
+ TimeoutException = TimeoutError
136
+ # Instanstiate all classes so the type checkers catch abstract issues
137
+ from . import smart
138
+
139
+ smart.SmartDevice("127.0.0.1")
140
+ iot.IotDevice("127.0.0.1")
141
+ iot.IotPlug("127.0.0.1")
142
+ iot.IotBulb("127.0.0.1")
143
+ iot.IotLightStrip("127.0.0.1")
144
+ iot.IotStrip("127.0.0.1")
145
+ iot.IotDimmer("127.0.0.1")
kasa/aestransport.py CHANGED
@@ -4,12 +4,15 @@ Based on the work of https://github.com/petretiandrea/plugp100
4
4
  under compatible GNU GPL3 license.
5
5
  """
6
6
 
7
+ from __future__ import annotations
8
+
9
+ import asyncio
7
10
  import base64
8
11
  import hashlib
9
12
  import logging
10
13
  import time
11
14
  from enum import Enum, auto
12
- from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, Optional, Tuple, cast
15
+ from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, cast
13
16
 
14
17
  from cryptography.hazmat.primitives import padding, serialization
15
18
  from cryptography.hazmat.primitives.asymmetric import padding as asymmetric_padding
@@ -22,12 +25,11 @@ from .deviceconfig import DeviceConfig
22
25
  from .exceptions import (
23
26
  SMART_AUTHENTICATION_ERRORS,
24
27
  SMART_RETRYABLE_ERRORS,
25
- SMART_TIMEOUT_ERRORS,
26
- AuthenticationException,
27
- RetryableException,
28
- SmartDeviceException,
28
+ AuthenticationError,
29
+ DeviceError,
30
+ KasaException,
29
31
  SmartErrorCode,
30
- TimeoutException,
32
+ _RetryableError,
31
33
  )
32
34
  from .httpclient import HttpClient
33
35
  from .json import dumps as json_dumps
@@ -72,6 +74,7 @@ class AesTransport(BaseTransport):
72
74
  }
73
75
  CONTENT_LENGTH = "Content-Length"
74
76
  KEY_PAIR_CONTENT_LENGTH = 314
77
+ BACKOFF_SECONDS_AFTER_LOGIN_ERROR = 1
75
78
 
76
79
  def __init__(
77
80
  self,
@@ -91,19 +94,19 @@ class AesTransport(BaseTransport):
91
94
  self._login_params = json_loads(
92
95
  base64.b64decode(self._credentials_hash.encode()).decode() # type: ignore[union-attr]
93
96
  )
94
- self._default_credentials: Optional[Credentials] = None
97
+ self._default_credentials: Credentials | None = None
95
98
  self._http_client: HttpClient = HttpClient(config)
96
99
 
97
100
  self._state = TransportState.HANDSHAKE_REQUIRED
98
101
 
99
- self._encryption_session: Optional[AesEncyptionSession] = None
100
- self._session_expire_at: Optional[float] = None
102
+ self._encryption_session: AesEncyptionSession | None = None
103
+ self._session_expire_at: float | None = None
101
104
 
102
- self._session_cookie: Optional[Dict[str, str]] = None
105
+ self._session_cookie: dict[str, str] | None = None
103
106
 
104
- self._key_pair: Optional[KeyPair] = None
105
- self._app_url = URL(f"http://{self._host}/app")
106
- self._token_url: Optional[URL] = None
107
+ self._key_pair: KeyPair | None = None
108
+ self._app_url = URL(f"http://{self._host}:{self._port}/app")
109
+ self._token_url: URL | None = None
107
110
 
108
111
  _LOGGER.debug("Created AES transport for %s", self._host)
109
112
 
@@ -117,14 +120,14 @@ class AesTransport(BaseTransport):
117
120
  """The hashed credentials used by the transport."""
118
121
  return base64.b64encode(json_dumps(self._login_params).encode()).decode()
119
122
 
120
- def _get_login_params(self, credentials: Credentials) -> Dict[str, str]:
123
+ def _get_login_params(self, credentials: Credentials) -> dict[str, str]:
121
124
  """Get the login parameters based on the login_version."""
122
125
  un, pw = self.hash_credentials(self._login_version == 2, credentials)
123
126
  password_field_name = "password2" if self._login_version == 2 else "password"
124
127
  return {password_field_name: pw, "username": un}
125
128
 
126
129
  @staticmethod
127
- def hash_credentials(login_v2: bool, credentials: Credentials) -> Tuple[str, str]:
130
+ def hash_credentials(login_v2: bool, credentials: Credentials) -> tuple[str, str]:
128
131
  """Hash the credentials."""
129
132
  un = base64.b64encode(_sha1(credentials.username.encode()).encode()).decode()
130
133
  if login_v2:
@@ -140,16 +143,14 @@ class AesTransport(BaseTransport):
140
143
  if error_code == SmartErrorCode.SUCCESS:
141
144
  return
142
145
  msg = f"{msg}: {self._host}: {error_code.name}({error_code.value})"
143
- if error_code in SMART_TIMEOUT_ERRORS:
144
- raise TimeoutException(msg, error_code=error_code)
145
146
  if error_code in SMART_RETRYABLE_ERRORS:
146
- raise RetryableException(msg, error_code=error_code)
147
+ raise _RetryableError(msg, error_code=error_code)
147
148
  if error_code in SMART_AUTHENTICATION_ERRORS:
148
149
  self._state = TransportState.HANDSHAKE_REQUIRED
149
- raise AuthenticationException(msg, error_code=error_code)
150
- raise SmartDeviceException(msg, error_code=error_code)
150
+ raise AuthenticationError(msg, error_code=error_code)
151
+ raise DeviceError(msg, error_code=error_code)
151
152
 
152
- async def send_secure_passthrough(self, request: str) -> Dict[str, Any]:
153
+ async def send_secure_passthrough(self, request: str) -> dict[str, Any]:
153
154
  """Send encrypted message as passthrough."""
154
155
  if self._state is TransportState.ESTABLISHED and self._token_url:
155
156
  url = self._token_url
@@ -170,7 +171,7 @@ class AesTransport(BaseTransport):
170
171
  # _LOGGER.debug(f"secure_passthrough response is {status_code}: {resp_dict}")
171
172
 
172
173
  if status_code != 200:
173
- raise SmartDeviceException(
174
+ raise KasaException(
174
175
  f"{self._host} responded with an unexpected "
175
176
  + f"status code {status_code} to passthrough"
176
177
  )
@@ -184,14 +185,30 @@ class AesTransport(BaseTransport):
184
185
  assert self._encryption_session is not None
185
186
 
186
187
  raw_response: str = resp_dict["result"]["response"]
187
- response = self._encryption_session.decrypt(raw_response.encode())
188
- return json_loads(response) # type: ignore[return-value]
188
+
189
+ try:
190
+ response = self._encryption_session.decrypt(raw_response.encode())
191
+ ret_val = json_loads(response)
192
+ except Exception as ex:
193
+ try:
194
+ ret_val = json_loads(raw_response)
195
+ _LOGGER.debug(
196
+ "Received unencrypted response over secure passthrough from %s",
197
+ self._host,
198
+ )
199
+ except Exception:
200
+ raise KasaException(
201
+ f"Unable to decrypt response from {self._host}, "
202
+ + f"error: {ex}, response: {raw_response}",
203
+ ex,
204
+ ) from ex
205
+ return ret_val # type: ignore[return-value]
189
206
 
190
207
  async def perform_login(self):
191
208
  """Login to the device."""
192
209
  try:
193
210
  await self.try_login(self._login_params)
194
- except AuthenticationException as aex:
211
+ except AuthenticationError as aex:
195
212
  try:
196
213
  if aex.error_code is not SmartErrorCode.LOGIN_ERROR:
197
214
  raise aex
@@ -199,22 +216,23 @@ class AesTransport(BaseTransport):
199
216
  self._default_credentials = get_default_credentials(
200
217
  DEFAULT_CREDENTIALS["TAPO"]
201
218
  )
219
+ await asyncio.sleep(self.BACKOFF_SECONDS_AFTER_LOGIN_ERROR)
202
220
  await self.perform_handshake()
203
221
  await self.try_login(self._get_login_params(self._default_credentials))
204
222
  _LOGGER.debug(
205
223
  "%s: logged in with default credentials",
206
224
  self._host,
207
225
  )
208
- except AuthenticationException:
226
+ except AuthenticationError:
209
227
  raise
210
228
  except Exception as ex:
211
- raise AuthenticationException(
229
+ raise KasaException(
212
230
  "Unable to login and trying default "
213
- + "login raised another exception: %s",
231
+ + f"login raised another exception: {ex}",
214
232
  ex,
215
233
  ) from ex
216
234
 
217
- async def try_login(self, login_params: Dict[str, Any]) -> None:
235
+ async def try_login(self, login_params: dict[str, Any]) -> None:
218
236
  """Try to login with supplied login_params."""
219
237
  login_request = {
220
238
  "method": "login_device",
@@ -257,7 +275,6 @@ class AesTransport(BaseTransport):
257
275
  self._session_expire_at = None
258
276
  self._session_cookie = None
259
277
 
260
- url = f"http://{self._host}/app"
261
278
  # Device needs the content length or it will response with 500
262
279
  headers = {
263
280
  **self.COMMON_HEADERS,
@@ -266,7 +283,7 @@ class AesTransport(BaseTransport):
266
283
  http_client = self._http_client
267
284
 
268
285
  status_code, resp_dict = await http_client.post(
269
- url,
286
+ self._app_url,
270
287
  json=self._generate_key_pair_payload(),
271
288
  headers=headers,
272
289
  cookies_dict=self._session_cookie,
@@ -275,7 +292,7 @@ class AesTransport(BaseTransport):
275
292
  _LOGGER.debug("Device responded with: %s", resp_dict)
276
293
 
277
294
  if status_code != 200:
278
- raise SmartDeviceException(
295
+ raise KasaException(
279
296
  f"{self._host} responded with an unexpected "
280
297
  + f"status code {status_code} to handshake"
281
298
  )
@@ -318,7 +335,7 @@ class AesTransport(BaseTransport):
318
335
  or self._session_expire_at - time.time() <= 0
319
336
  )
320
337
 
321
- async def send(self, request: str) -> Dict[str, Any]:
338
+ async def send(self, request: str) -> dict[str, Any]:
322
339
  """Send the request."""
323
340
  if (
324
341
  self._state is TransportState.HANDSHAKE_REQUIRED
@@ -330,7 +347,7 @@ class AesTransport(BaseTransport):
330
347
  await self.perform_login()
331
348
  # After a login failure handshake needs to
332
349
  # be redone or a 9999 error is received.
333
- except AuthenticationException as ex:
350
+ except AuthenticationError as ex:
334
351
  self._state = TransportState.HANDSHAKE_REQUIRED
335
352
  raise ex
336
353