python-kasa 0.6.2__py3-none-any.whl → 0.7.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 (181) hide show
  1. kasa/__init__.py +103 -33
  2. kasa/aestransport.py +55 -35
  3. kasa/cli.py +420 -171
  4. kasa/device.py +530 -0
  5. kasa/device_factory.py +83 -44
  6. kasa/device_type.py +7 -3
  7. kasa/deviceconfig.py +57 -25
  8. kasa/discover.py +207 -127
  9. kasa/emeterstatus.py +12 -7
  10. kasa/exceptions.py +41 -26
  11. kasa/feature.py +273 -0
  12. kasa/httpclient.py +46 -15
  13. kasa/interfaces/__init__.py +18 -0
  14. kasa/interfaces/energy.py +181 -0
  15. kasa/interfaces/fan.py +20 -0
  16. kasa/interfaces/led.py +38 -0
  17. kasa/interfaces/light.py +198 -0
  18. kasa/interfaces/lighteffect.py +120 -0
  19. kasa/interfaces/lightpreset.py +144 -0
  20. kasa/iot/__init__.py +18 -0
  21. kasa/{effects.py → iot/effects.py} +4 -2
  22. kasa/{smartbulb.py → iot/iotbulb.py} +103 -147
  23. kasa/{smartdevice.py → iot/iotdevice.py} +164 -347
  24. kasa/{smartdimmer.py → iot/iotdimmer.py} +45 -33
  25. kasa/iot/iotlightstrip.py +72 -0
  26. kasa/{modules/module.py → iot/iotmodule.py} +22 -42
  27. kasa/iot/iotplug.py +94 -0
  28. kasa/{smartstrip.py → iot/iotstrip.py} +186 -122
  29. kasa/{modules → iot/modules}/__init__.py +10 -2
  30. kasa/{modules → iot/modules}/ambientlight.py +31 -3
  31. kasa/{modules → iot/modules}/antitheft.py +1 -0
  32. kasa/{modules → iot/modules}/cloud.py +25 -6
  33. kasa/{modules → iot/modules}/countdown.py +1 -0
  34. kasa/{modules → iot/modules}/emeter.py +55 -15
  35. kasa/iot/modules/led.py +37 -0
  36. kasa/iot/modules/light.py +263 -0
  37. kasa/iot/modules/lighteffect.py +128 -0
  38. kasa/iot/modules/lightpreset.py +157 -0
  39. kasa/{modules → iot/modules}/motion.py +8 -8
  40. kasa/{modules → iot/modules}/rulemodule.py +11 -12
  41. kasa/{modules → iot/modules}/schedule.py +1 -0
  42. kasa/{modules → iot/modules}/time.py +5 -4
  43. kasa/{modules → iot/modules}/usage.py +10 -8
  44. kasa/iotprotocol.py +22 -20
  45. kasa/klaptransport.py +25 -15
  46. kasa/module.py +173 -0
  47. kasa/modulemapping.py +25 -0
  48. kasa/modulemapping.pyi +96 -0
  49. kasa/protocol.py +6 -4
  50. kasa/smart/__init__.py +6 -0
  51. kasa/smart/effects.py +429 -0
  52. kasa/smart/modules/__init__.py +57 -0
  53. kasa/smart/modules/alarm.py +142 -0
  54. kasa/smart/modules/autooff.py +110 -0
  55. kasa/smart/modules/batterysensor.py +54 -0
  56. kasa/smart/modules/brightness.py +66 -0
  57. kasa/smart/modules/childdevice.py +48 -0
  58. kasa/smart/modules/cloud.py +42 -0
  59. kasa/smart/modules/color.py +96 -0
  60. kasa/smart/modules/colortemperature.py +78 -0
  61. kasa/smart/modules/contactsensor.py +42 -0
  62. kasa/smart/modules/devicemodule.py +22 -0
  63. kasa/smart/modules/energy.py +99 -0
  64. kasa/smart/modules/fan.py +81 -0
  65. kasa/smart/modules/firmware.py +217 -0
  66. kasa/smart/modules/frostprotection.py +59 -0
  67. kasa/smart/modules/humiditysensor.py +55 -0
  68. kasa/smart/modules/led.py +49 -0
  69. kasa/smart/modules/light.py +166 -0
  70. kasa/smart/modules/lighteffect.py +115 -0
  71. kasa/smart/modules/lightpreset.py +153 -0
  72. kasa/smart/modules/lightstripeffect.py +145 -0
  73. kasa/smart/modules/lighttransition.py +193 -0
  74. kasa/smart/modules/reportmode.py +37 -0
  75. kasa/smart/modules/temperaturecontrol.py +177 -0
  76. kasa/smart/modules/temperaturesensor.py +77 -0
  77. kasa/smart/modules/time.py +63 -0
  78. kasa/smart/modules/waterleaksensor.py +66 -0
  79. kasa/smart/smartchilddevice.py +76 -0
  80. kasa/smart/smartdevice.py +613 -0
  81. kasa/smart/smartmodule.py +112 -0
  82. kasa/smartprotocol.py +109 -41
  83. kasa/tests/conftest.py +27 -551
  84. kasa/tests/device_fixtures.py +467 -0
  85. kasa/tests/discovery_fixtures.py +252 -0
  86. kasa/tests/{newfakes.py → fakeprotocol_iot.py} +94 -295
  87. kasa/tests/fakeprotocol_smart.py +336 -0
  88. kasa/tests/fixtureinfo.py +154 -0
  89. kasa/tests/fixtures/HS110(EU)_1.0_1.2.5.json +1 -1
  90. kasa/tests/fixtures/HS110(US)_1.0_1.2.6.json +37 -0
  91. kasa/tests/fixtures/HS220(US)_1.0_1.5.7.json +1 -1
  92. kasa/tests/fixtures/HS220(US)_2.0_1.0.3.json +1 -1
  93. kasa/tests/fixtures/HS300(US)_1.0_1.0.21.json +89 -0
  94. kasa/tests/fixtures/{LB120(US)_1.0_mocked.json → KL120(US)_1.0_1.8.11.json} +26 -44
  95. kasa/tests/fixtures/KL430(US)_1.0_1.0.10.json +51 -12
  96. kasa/tests/fixtures/KP303(UK)_1.0_1.0.3.json +1 -1
  97. kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +221 -0
  98. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +547 -0
  99. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +391 -0
  100. kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +1557 -0
  101. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +899 -0
  102. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +479 -0
  103. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +449 -0
  104. kasa/tests/fixtures/smart/L920-5(EU)_1.0_1.0.7.json +350 -0
  105. kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +173 -0
  106. kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +204 -0
  107. kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +566 -0
  108. kasa/tests/fixtures/smart/P115(EU)_1.0_1.2.3.json +386 -0
  109. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.13.json +13 -23
  110. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.15.json +966 -0
  111. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +6 -6
  112. kasa/tests/fixtures/smart/S505D(US)_1.0_1.1.0.json +262 -0
  113. kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +295 -0
  114. kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +423 -0
  115. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  116. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  117. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  118. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  119. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  120. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  121. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  122. kasa/tests/smart/__init__.py +0 -0
  123. kasa/tests/smart/features/__init__.py +0 -0
  124. kasa/tests/smart/features/test_brightness.py +55 -0
  125. kasa/tests/smart/features/test_colortemp.py +30 -0
  126. kasa/tests/smart/modules/__init__.py +0 -0
  127. kasa/tests/smart/modules/test_autooff.py +103 -0
  128. kasa/tests/smart/modules/test_contact.py +28 -0
  129. kasa/tests/smart/modules/test_fan.py +83 -0
  130. kasa/tests/smart/modules/test_firmware.py +119 -0
  131. kasa/tests/smart/modules/test_humidity.py +28 -0
  132. kasa/tests/smart/modules/test_light_effect.py +41 -0
  133. kasa/tests/smart/modules/test_temperature.py +47 -0
  134. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  135. kasa/tests/smart/modules/test_waterleak.py +42 -0
  136. kasa/tests/test_aestransport.py +204 -26
  137. kasa/tests/test_bulb.py +179 -91
  138. kasa/tests/test_childdevice.py +102 -0
  139. kasa/tests/test_cli.py +499 -100
  140. kasa/tests/test_common_modules.py +243 -0
  141. kasa/tests/test_device.py +299 -0
  142. kasa/tests/test_device_factory.py +69 -49
  143. kasa/tests/test_device_type.py +1 -1
  144. kasa/tests/test_deviceconfig.py +2 -5
  145. kasa/tests/test_dimmer.py +42 -33
  146. kasa/tests/test_discovery.py +173 -73
  147. kasa/tests/test_emeter.py +69 -14
  148. kasa/tests/test_feature.py +205 -0
  149. kasa/tests/test_httpclient.py +11 -11
  150. kasa/tests/test_iotdevice.py +294 -0
  151. kasa/tests/test_klapprotocol.py +94 -41
  152. kasa/tests/test_lightstrip.py +24 -19
  153. kasa/tests/test_plug.py +51 -9
  154. kasa/tests/test_protocol.py +8 -12
  155. kasa/tests/test_readme_examples.py +163 -30
  156. kasa/tests/test_smartdevice.py +218 -249
  157. kasa/tests/test_smartprotocol.py +130 -26
  158. kasa/tests/test_strip.py +23 -6
  159. kasa/tests/test_usage.py +1 -3
  160. kasa/xortransport.py +17 -14
  161. python_kasa-0.7.0.dist-info/METADATA +266 -0
  162. python_kasa-0.7.0.dist-info/RECORD +248 -0
  163. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dist-info}/WHEEL +1 -1
  164. kasa/smartlightstrip.py +0 -143
  165. kasa/smartplug.py +0 -91
  166. kasa/tapo/__init__.py +0 -7
  167. kasa/tapo/childdevice.py +0 -44
  168. kasa/tapo/tapobulb.py +0 -262
  169. kasa/tapo/tapodevice.py +0 -383
  170. kasa/tapo/tapoplug.py +0 -45
  171. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  172. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  173. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  174. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  175. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  176. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  177. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  178. python_kasa-0.6.2.dist-info/METADATA +0 -389
  179. python_kasa-0.6.2.dist-info/RECORD +0 -163
  180. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dist-info}/LICENSE +0 -0
  181. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dist-info}/entry_points.txt +0 -0
kasa/__init__.py CHANGED
@@ -1,46 +1,48 @@
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
- ConnectionType,
20
23
  DeviceConfig,
21
- DeviceFamilyType,
22
- EncryptType,
24
+ DeviceConnectionParameters,
25
+ DeviceEncryptionType,
26
+ DeviceFamily,
23
27
  )
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,33 +52,101 @@ __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
- "ConnectionType",
71
- "EncryptType",
72
- "DeviceFamilyType",
74
+ "DeviceConnectionParameters",
75
+ "DeviceEncryptionType",
76
+ "DeviceFamily",
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_classes = {
93
+ "SmartDeviceException": KasaException,
94
+ "UnsupportedDeviceException": UnsupportedDeviceError,
95
+ "AuthenticationException": AuthenticationError,
96
+ "TimeoutException": TimeoutError,
97
+ "ConnectionType": DeviceConnectionParameters,
98
+ "EncryptType": DeviceEncryptionType,
99
+ "DeviceFamilyType": DeviceFamily,
100
+ }
76
101
 
77
102
 
78
103
  def __getattr__(name):
79
104
  if name in deprecated_names:
80
105
  warn(f"{name} is deprecated", DeprecationWarning, stacklevel=1)
81
106
  return globals()[f"_deprecated_{name}"]
107
+ if name in deprecated_smart_devices:
108
+ new_class = deprecated_smart_devices[name]
109
+ package_name = ".".join(new_class.__module__.split(".")[:-1])
110
+ warn(
111
+ f"{name} is deprecated, use {new_class.__name__} "
112
+ + f"from package {package_name} instead or use Discover.discover_single()"
113
+ + " and Device.connect() to support new protocols",
114
+ DeprecationWarning,
115
+ stacklevel=1,
116
+ )
117
+ return new_class
118
+ if name in deprecated_classes:
119
+ new_class = deprecated_classes[name]
120
+ msg = f"{name} is deprecated, use {new_class.__name__} instead"
121
+ warn(msg, DeprecationWarning, stacklevel=1)
122
+ return new_class
82
123
  raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
124
+
125
+
126
+ if TYPE_CHECKING:
127
+ SmartDevice = Device
128
+ SmartBulb = iot.IotBulb
129
+ SmartPlug = iot.IotPlug
130
+ SmartLightStrip = iot.IotLightStrip
131
+ SmartStrip = iot.IotStrip
132
+ SmartDimmer = iot.IotDimmer
133
+ SmartBulbPreset = IotLightPreset
134
+
135
+ SmartDeviceException = KasaException
136
+ UnsupportedDeviceException = UnsupportedDeviceError
137
+ AuthenticationException = AuthenticationError
138
+ TimeoutException = TimeoutError
139
+ ConnectionType = DeviceConnectionParameters
140
+ EncryptType = DeviceEncryptionType
141
+ DeviceFamilyType = DeviceFamily
142
+
143
+ # Instanstiate all classes so the type checkers catch abstract issues
144
+ from . import smart
145
+
146
+ smart.SmartDevice("127.0.0.1")
147
+ iot.IotDevice("127.0.0.1")
148
+ iot.IotPlug("127.0.0.1")
149
+ iot.IotBulb("127.0.0.1")
150
+ iot.IotLightStrip("127.0.0.1")
151
+ iot.IotStrip("127.0.0.1")
152
+ 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
+
7
9
  import base64
8
10
  import hashlib
9
11
  import logging
10
12
  import time
13
+ from collections.abc import AsyncGenerator
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, 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,13 @@ 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
+ TimeoutError,
33
+ _ConnectionError,
34
+ _RetryableError,
31
35
  )
32
36
  from .httpclient import HttpClient
33
37
  from .json import dumps as json_dumps
@@ -91,19 +95,19 @@ class AesTransport(BaseTransport):
91
95
  self._login_params = json_loads(
92
96
  base64.b64decode(self._credentials_hash.encode()).decode() # type: ignore[union-attr]
93
97
  )
94
- self._default_credentials: Optional[Credentials] = None
98
+ self._default_credentials: Credentials | None = None
95
99
  self._http_client: HttpClient = HttpClient(config)
96
100
 
97
101
  self._state = TransportState.HANDSHAKE_REQUIRED
98
102
 
99
- self._encryption_session: Optional[AesEncyptionSession] = None
100
- self._session_expire_at: Optional[float] = None
103
+ self._encryption_session: AesEncyptionSession | None = None
104
+ self._session_expire_at: float | None = None
101
105
 
102
- self._session_cookie: Optional[Dict[str, str]] = None
106
+ self._session_cookie: dict[str, str] | None = None
103
107
 
104
- self._key_pair: Optional[KeyPair] = None
105
- self._app_url = URL(f"http://{self._host}/app")
106
- self._token_url: Optional[URL] = None
108
+ self._key_pair: KeyPair | None = None
109
+ self._app_url = URL(f"http://{self._host}:{self._port}/app")
110
+ self._token_url: URL | None = None
107
111
 
108
112
  _LOGGER.debug("Created AES transport for %s", self._host)
109
113
 
@@ -117,14 +121,14 @@ class AesTransport(BaseTransport):
117
121
  """The hashed credentials used by the transport."""
118
122
  return base64.b64encode(json_dumps(self._login_params).encode()).decode()
119
123
 
120
- def _get_login_params(self, credentials: Credentials) -> Dict[str, str]:
124
+ def _get_login_params(self, credentials: Credentials) -> dict[str, str]:
121
125
  """Get the login parameters based on the login_version."""
122
126
  un, pw = self.hash_credentials(self._login_version == 2, credentials)
123
127
  password_field_name = "password2" if self._login_version == 2 else "password"
124
128
  return {password_field_name: pw, "username": un}
125
129
 
126
130
  @staticmethod
127
- def hash_credentials(login_v2: bool, credentials: Credentials) -> Tuple[str, str]:
131
+ def hash_credentials(login_v2: bool, credentials: Credentials) -> tuple[str, str]:
128
132
  """Hash the credentials."""
129
133
  un = base64.b64encode(_sha1(credentials.username.encode()).encode()).decode()
130
134
  if login_v2:
@@ -140,16 +144,14 @@ class AesTransport(BaseTransport):
140
144
  if error_code == SmartErrorCode.SUCCESS:
141
145
  return
142
146
  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
147
  if error_code in SMART_RETRYABLE_ERRORS:
146
- raise RetryableException(msg, error_code=error_code)
148
+ raise _RetryableError(msg, error_code=error_code)
147
149
  if error_code in SMART_AUTHENTICATION_ERRORS:
148
150
  self._state = TransportState.HANDSHAKE_REQUIRED
149
- raise AuthenticationException(msg, error_code=error_code)
150
- raise SmartDeviceException(msg, error_code=error_code)
151
+ raise AuthenticationError(msg, error_code=error_code)
152
+ raise DeviceError(msg, error_code=error_code)
151
153
 
152
- async def send_secure_passthrough(self, request: str) -> Dict[str, Any]:
154
+ async def send_secure_passthrough(self, request: str) -> dict[str, Any]:
153
155
  """Send encrypted message as passthrough."""
154
156
  if self._state is TransportState.ESTABLISHED and self._token_url:
155
157
  url = self._token_url
@@ -170,7 +172,7 @@ class AesTransport(BaseTransport):
170
172
  # _LOGGER.debug(f"secure_passthrough response is {status_code}: {resp_dict}")
171
173
 
172
174
  if status_code != 200:
173
- raise SmartDeviceException(
175
+ raise KasaException(
174
176
  f"{self._host} responded with an unexpected "
175
177
  + f"status code {status_code} to passthrough"
176
178
  )
@@ -184,14 +186,30 @@ class AesTransport(BaseTransport):
184
186
  assert self._encryption_session is not None
185
187
 
186
188
  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]
189
+
190
+ try:
191
+ response = self._encryption_session.decrypt(raw_response.encode())
192
+ ret_val = json_loads(response)
193
+ except Exception as ex:
194
+ try:
195
+ ret_val = json_loads(raw_response)
196
+ _LOGGER.debug(
197
+ "Received unencrypted response over secure passthrough from %s",
198
+ self._host,
199
+ )
200
+ except Exception:
201
+ raise KasaException(
202
+ f"Unable to decrypt response from {self._host}, "
203
+ + f"error: {ex}, response: {raw_response}",
204
+ ex,
205
+ ) from ex
206
+ return ret_val # type: ignore[return-value]
189
207
 
190
208
  async def perform_login(self):
191
209
  """Login to the device."""
192
210
  try:
193
211
  await self.try_login(self._login_params)
194
- except AuthenticationException as aex:
212
+ except AuthenticationError as aex:
195
213
  try:
196
214
  if aex.error_code is not SmartErrorCode.LOGIN_ERROR:
197
215
  raise aex
@@ -205,16 +223,16 @@ class AesTransport(BaseTransport):
205
223
  "%s: logged in with default credentials",
206
224
  self._host,
207
225
  )
208
- except AuthenticationException:
226
+ except (AuthenticationError, _ConnectionError, TimeoutError):
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
 
@@ -355,7 +372,10 @@ class AesEncyptionSession:
355
372
  handshake_key_bytes: bytes = base64.b64decode(handshake_key.encode("UTF-8"))
356
373
  private_key_data = base64.b64decode(keypair.get_private_key().encode("UTF-8"))
357
374
 
358
- private_key = serialization.load_der_private_key(private_key_data, None, None)
375
+ private_key = cast(
376
+ rsa.RSAPrivateKey,
377
+ serialization.load_der_private_key(private_key_data, None, None),
378
+ )
359
379
  key_and_iv = private_key.decrypt(
360
380
  handshake_key_bytes, asymmetric_padding.PKCS1v15()
361
381
  )