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.
- kasa/__init__.py +2 -2
- kasa/aestransport.py +154 -101
- kasa/cli.py +42 -23
- kasa/device_factory.py +4 -3
- kasa/deviceconfig.py +19 -10
- kasa/discover.py +28 -11
- kasa/exceptions.py +15 -1
- kasa/httpclient.py +113 -0
- kasa/iotprotocol.py +30 -26
- kasa/json.py +5 -1
- kasa/klaptransport.py +60 -75
- kasa/modules/emeter.py +1 -1
- kasa/protocol.py +61 -16
- kasa/smartbulb.py +2 -2
- kasa/smartdevice.py +11 -7
- kasa/smartdimmer.py +2 -2
- kasa/smartlightstrip.py +2 -2
- kasa/smartplug.py +2 -2
- kasa/smartprotocol.py +16 -38
- kasa/smartstrip.py +2 -2
- kasa/tapo/tapodevice.py +19 -4
- kasa/tapo/tapoplug.py +2 -2
- kasa/tests/conftest.py +24 -8
- kasa/tests/fixtures/HS100(UK)_1.0_1.2.6.json +28 -0
- kasa/tests/fixtures/HS100(UK)_4.1_1.1.0.json +3 -3
- kasa/tests/fixtures/HS110(EU)_1.0_1.2.5.json +11 -23
- kasa/tests/fixtures/HS110(EU)_4.0_1.0.4.json +40 -0
- kasa/tests/fixtures/HS300(US)_2.0_1.0.12.json +90 -0
- kasa/tests/fixtures/KL125(US)_4.0_1.0.5.json +93 -0
- kasa/tests/fixtures/KL130(EU)_1.0_1.8.8.json +15 -15
- kasa/tests/fixtures/KL430(US)_2.0_1.0.11.json +59 -0
- kasa/tests/fixtures/KP105(UK)_1.0_1.0.5.json +36 -0
- kasa/tests/fixtures/KP105(UK)_1.0_1.0.7.json +4 -4
- kasa/tests/fixtures/KP115(EU)_1.0_1.0.16.json +9 -9
- kasa/tests/fixtures/KP115(US)_1.0_1.0.21.json +42 -0
- kasa/tests/fixtures/KP303(UK)_1.0_1.0.3.json +9 -25
- kasa/tests/fixtures/smart/EP25(US)_2.6_1.0.2.json +414 -0
- kasa/tests/fixtures/smart/L510B(EU)_3.0_1.0.5.json +263 -0
- kasa/tests/fixtures/smart/L510E(US)_3.0_1.0.5.json +295 -0
- kasa/tests/fixtures/smart/L510E(US)_3.0_1.1.2.json +267 -0
- kasa/tests/fixtures/smart/L530E(EU)_3.0_1.0.6.json +19 -19
- kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.0.json +12 -12
- kasa/tests/fixtures/smart/L530E(US)_2.0_1.1.0.json +439 -0
- kasa/tests/fixtures/smart/L900-10(EU)_1.0_1.0.17.json +10 -10
- kasa/tests/fixtures/smart/L900-10(US)_1.0_1.0.11.json +428 -0
- kasa/tests/fixtures/smart/L900-5(EU)_1.0_1.0.17.json +98 -20
- kasa/tests/fixtures/smart/L900-5(EU)_1.0_1.1.0.json +390 -0
- kasa/tests/fixtures/smart/L920-5(US)_1.0_1.1.0.json +397 -0
- kasa/tests/fixtures/smart/L920-5(US)_1.0_1.1.3.json +415 -0
- kasa/tests/fixtures/smart/L930-5(US)_1.0_1.1.2.json +429 -0
- kasa/tests/fixtures/smart/P100_1.0.0_1.3.7.json +197 -0
- kasa/tests/fixtures/smart/P110(EU)_1.0_1.2.3.json +28 -19
- kasa/tests/fixtures/smart/P110(UK)_1.0_1.3.0.json +31 -31
- kasa/tests/fixtures/smart/P125M(US)_1.0_1.1.0.json +11 -11
- kasa/tests/fixtures/smart/P135(US)_1.0_1.0.5.json +317 -0
- kasa/tests/fixtures/smart/S500D(US)_1.0_1.0.5.json +317 -0
- kasa/tests/fixtures/smart/S505(US)_1.0_1.0.2.json +309 -0
- kasa/tests/newfakes.py +3 -0
- kasa/tests/test_aestransport.py +110 -22
- kasa/tests/test_cli.py +49 -2
- kasa/tests/test_device_factory.py +6 -4
- kasa/tests/test_deviceconfig.py +24 -9
- kasa/tests/test_discovery.py +126 -9
- kasa/tests/test_httpclient.py +100 -0
- kasa/tests/test_klapprotocol.py +70 -23
- kasa/tests/test_protocol.py +76 -2
- kasa/tests/test_smartprotocol.py +0 -1
- {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/METADATA +37 -15
- {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/RECORD +72 -49
- {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/LICENSE +0 -0
- {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/WHEEL +0 -0
- {python_kasa-0.6.0.dev2.dist-info → python_kasa-0.6.1.dist-info}/entry_points.txt +0 -0
kasa/discover.py
CHANGED
|
@@ -49,6 +49,7 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
49
49
|
on_discovered: Optional[OnDiscoveredCallable] = None,
|
|
50
50
|
target: str = "255.255.255.255",
|
|
51
51
|
discovery_packets: int = 3,
|
|
52
|
+
discovery_timeout: int = 5,
|
|
52
53
|
interface: Optional[str] = None,
|
|
53
54
|
on_unsupported: Optional[
|
|
54
55
|
Callable[[UnsupportedDeviceException], Awaitable[None]]
|
|
@@ -65,7 +66,8 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
65
66
|
|
|
66
67
|
self.port = port
|
|
67
68
|
self.discovery_port = port or Discover.DISCOVERY_PORT
|
|
68
|
-
self.target =
|
|
69
|
+
self.target = target
|
|
70
|
+
self.target_1 = (target, self.discovery_port)
|
|
69
71
|
self.target_2 = (target, Discover.DISCOVERY_PORT_2)
|
|
70
72
|
|
|
71
73
|
self.discovered_devices = {}
|
|
@@ -75,7 +77,9 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
75
77
|
self.discovered_event = discovered_event
|
|
76
78
|
self.credentials = credentials
|
|
77
79
|
self.timeout = timeout
|
|
80
|
+
self.discovery_timeout = discovery_timeout
|
|
78
81
|
self.seen_hosts: Set[str] = set()
|
|
82
|
+
self.discover_task: Optional[asyncio.Task] = None
|
|
79
83
|
|
|
80
84
|
def connection_made(self, transport) -> None:
|
|
81
85
|
"""Set socket options for broadcasting."""
|
|
@@ -93,16 +97,21 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
93
97
|
socket.SOL_SOCKET, socket.SO_BINDTODEVICE, self.interface.encode()
|
|
94
98
|
)
|
|
95
99
|
|
|
96
|
-
self.do_discover()
|
|
100
|
+
self.discover_task = asyncio.create_task(self.do_discover())
|
|
97
101
|
|
|
98
|
-
def do_discover(self) -> None:
|
|
102
|
+
async def do_discover(self) -> None:
|
|
99
103
|
"""Send number of discovery datagrams."""
|
|
100
104
|
req = json_dumps(Discover.DISCOVERY_QUERY)
|
|
101
105
|
_LOGGER.debug("[DISCOVERY] %s >> %s", self.target, Discover.DISCOVERY_QUERY)
|
|
102
106
|
encrypted_req = TPLinkSmartHomeProtocol.encrypt(req)
|
|
103
|
-
|
|
104
|
-
|
|
107
|
+
sleep_between_packets = self.discovery_timeout / self.discovery_packets
|
|
108
|
+
for i in range(self.discovery_packets):
|
|
109
|
+
if self.target in self.seen_hosts: # Stop sending for discover_single
|
|
110
|
+
break
|
|
111
|
+
self.transport.sendto(encrypted_req[4:], self.target_1) # type: ignore
|
|
105
112
|
self.transport.sendto(Discover.DISCOVERY_QUERY_2, self.target_2) # type: ignore
|
|
113
|
+
if i < self.discovery_packets - 1:
|
|
114
|
+
await asyncio.sleep(sleep_between_packets)
|
|
106
115
|
|
|
107
116
|
def datagram_received(self, data, addr) -> None:
|
|
108
117
|
"""Handle discovery responses."""
|
|
@@ -132,14 +141,12 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
132
141
|
self.unsupported_device_exceptions[ip] = udex
|
|
133
142
|
if self.on_unsupported is not None:
|
|
134
143
|
asyncio.ensure_future(self.on_unsupported(udex))
|
|
135
|
-
|
|
136
|
-
self.discovered_event.set()
|
|
144
|
+
self._handle_discovered_event()
|
|
137
145
|
return
|
|
138
146
|
except SmartDeviceException as ex:
|
|
139
147
|
_LOGGER.debug(f"[DISCOVERY] Unable to find device type for {ip}: {ex}")
|
|
140
148
|
self.invalid_device_exceptions[ip] = ex
|
|
141
|
-
|
|
142
|
-
self.discovered_event.set()
|
|
149
|
+
self._handle_discovered_event()
|
|
143
150
|
return
|
|
144
151
|
|
|
145
152
|
self.discovered_devices[ip] = device
|
|
@@ -147,15 +154,23 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
147
154
|
if self.on_discovered is not None:
|
|
148
155
|
asyncio.ensure_future(self.on_discovered(device))
|
|
149
156
|
|
|
157
|
+
self._handle_discovered_event()
|
|
158
|
+
|
|
159
|
+
def _handle_discovered_event(self):
|
|
160
|
+
"""If discovered_event is available set it and cancel discover_task."""
|
|
150
161
|
if self.discovered_event is not None:
|
|
162
|
+
if self.discover_task:
|
|
163
|
+
self.discover_task.cancel()
|
|
151
164
|
self.discovered_event.set()
|
|
152
165
|
|
|
153
166
|
def error_received(self, ex):
|
|
154
167
|
"""Handle asyncio.Protocol errors."""
|
|
155
168
|
_LOGGER.error("Got error: %s", ex)
|
|
156
169
|
|
|
157
|
-
def connection_lost(self, ex):
|
|
158
|
-
"""
|
|
170
|
+
def connection_lost(self, ex): # pragma: no cover
|
|
171
|
+
"""Cancel the discover task if running."""
|
|
172
|
+
if self.discover_task:
|
|
173
|
+
self.discover_task.cancel()
|
|
159
174
|
|
|
160
175
|
|
|
161
176
|
class Discover:
|
|
@@ -260,6 +275,7 @@ class Discover:
|
|
|
260
275
|
on_unsupported=on_unsupported,
|
|
261
276
|
credentials=credentials,
|
|
262
277
|
timeout=timeout,
|
|
278
|
+
discovery_timeout=discovery_timeout,
|
|
263
279
|
port=port,
|
|
264
280
|
),
|
|
265
281
|
local_addr=("0.0.0.0", 0), # noqa: S104
|
|
@@ -334,6 +350,7 @@ class Discover:
|
|
|
334
350
|
discovered_event=event,
|
|
335
351
|
credentials=credentials,
|
|
336
352
|
timeout=timeout,
|
|
353
|
+
discovery_timeout=discovery_timeout,
|
|
337
354
|
),
|
|
338
355
|
local_addr=("0.0.0.0", 0), # noqa: S104
|
|
339
356
|
)
|
kasa/exceptions.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"""python-kasa exceptions."""
|
|
2
|
+
from asyncio import TimeoutError
|
|
2
3
|
from enum import IntEnum
|
|
3
4
|
from typing import Optional
|
|
4
5
|
|
|
@@ -27,9 +28,19 @@ class RetryableException(SmartDeviceException):
|
|
|
27
28
|
"""Retryable exception for device errors."""
|
|
28
29
|
|
|
29
30
|
|
|
30
|
-
class TimeoutException(SmartDeviceException):
|
|
31
|
+
class TimeoutException(SmartDeviceException, TimeoutError):
|
|
31
32
|
"""Timeout exception for device errors."""
|
|
32
33
|
|
|
34
|
+
def __repr__(self):
|
|
35
|
+
return SmartDeviceException.__repr__(self)
|
|
36
|
+
|
|
37
|
+
def __str__(self):
|
|
38
|
+
return SmartDeviceException.__str__(self)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ConnectionException(SmartDeviceException):
|
|
42
|
+
"""Connection exception for device errors."""
|
|
43
|
+
|
|
33
44
|
|
|
34
45
|
class SmartErrorCode(IntEnum):
|
|
35
46
|
"""Enum for SMART Error Codes."""
|
|
@@ -42,6 +53,8 @@ class SmartErrorCode(IntEnum):
|
|
|
42
53
|
HTTP_TRANSPORT_FAILED_ERROR = 1112
|
|
43
54
|
LOGIN_FAILED_ERROR = 1111
|
|
44
55
|
HAND_SHAKE_FAILED_ERROR = 1100
|
|
56
|
+
#: Real description unknown, seen after an encryption-changing fw upgrade
|
|
57
|
+
TRANSPORT_UNKNOWN_CREDENTIALS_ERROR = 1003
|
|
45
58
|
TRANSPORT_NOT_AVAILABLE_ERROR = 1002
|
|
46
59
|
CMD_COMMAND_CANCEL_ERROR = 1001
|
|
47
60
|
NULL_TRANSPORT_ERROR = 1000
|
|
@@ -100,6 +113,7 @@ SMART_AUTHENTICATION_ERRORS = [
|
|
|
100
113
|
SmartErrorCode.LOGIN_FAILED_ERROR,
|
|
101
114
|
SmartErrorCode.AES_DECODE_FAIL_ERROR,
|
|
102
115
|
SmartErrorCode.HAND_SHAKE_FAILED_ERROR,
|
|
116
|
+
SmartErrorCode.TRANSPORT_UNKNOWN_CREDENTIALS_ERROR,
|
|
103
117
|
]
|
|
104
118
|
|
|
105
119
|
SMART_TIMEOUT_ERRORS = [
|
kasa/httpclient.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Module for HttpClientSession class."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from typing import Any, Dict, Optional, Tuple, Union
|
|
4
|
+
|
|
5
|
+
import aiohttp
|
|
6
|
+
|
|
7
|
+
from .deviceconfig import DeviceConfig
|
|
8
|
+
from .exceptions import (
|
|
9
|
+
ConnectionException,
|
|
10
|
+
SmartDeviceException,
|
|
11
|
+
TimeoutException,
|
|
12
|
+
)
|
|
13
|
+
from .json import loads as json_loads
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_cookie_jar() -> aiohttp.CookieJar:
|
|
17
|
+
"""Return a new cookie jar with the correct options for device communication."""
|
|
18
|
+
return aiohttp.CookieJar(unsafe=True, quote_cookie=False)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class HttpClient:
|
|
22
|
+
"""HttpClient Class."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, config: DeviceConfig) -> None:
|
|
25
|
+
self._config = config
|
|
26
|
+
self._client_session: aiohttp.ClientSession = None
|
|
27
|
+
self._jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False)
|
|
28
|
+
self._last_url = f"http://{self._config.host}/"
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def client(self) -> aiohttp.ClientSession:
|
|
32
|
+
"""Return the underlying http client."""
|
|
33
|
+
if self._config.http_client and issubclass(
|
|
34
|
+
self._config.http_client.__class__, aiohttp.ClientSession
|
|
35
|
+
):
|
|
36
|
+
return self._config.http_client
|
|
37
|
+
|
|
38
|
+
if not self._client_session:
|
|
39
|
+
self._client_session = aiohttp.ClientSession(cookie_jar=get_cookie_jar())
|
|
40
|
+
return self._client_session
|
|
41
|
+
|
|
42
|
+
async def post(
|
|
43
|
+
self,
|
|
44
|
+
url: str,
|
|
45
|
+
*,
|
|
46
|
+
params: Optional[Dict[str, Any]] = None,
|
|
47
|
+
data: Optional[bytes] = None,
|
|
48
|
+
json: Optional[Union[Dict, Any]] = None,
|
|
49
|
+
headers: Optional[Dict[str, str]] = None,
|
|
50
|
+
cookies_dict: Optional[Dict[str, str]] = None,
|
|
51
|
+
) -> Tuple[int, Optional[Union[Dict, bytes]]]:
|
|
52
|
+
"""Send an http post request to the device.
|
|
53
|
+
|
|
54
|
+
If the request is provided via the json parameter json will be returned.
|
|
55
|
+
"""
|
|
56
|
+
response_data = None
|
|
57
|
+
self._last_url = url
|
|
58
|
+
self.client.cookie_jar.clear()
|
|
59
|
+
return_json = bool(json)
|
|
60
|
+
# If json is not a dict send as data.
|
|
61
|
+
# This allows the json parameter to be used to pass other
|
|
62
|
+
# types of data such as async_generator and still have json
|
|
63
|
+
# returned.
|
|
64
|
+
if json and not isinstance(json, Dict):
|
|
65
|
+
data = json
|
|
66
|
+
json = None
|
|
67
|
+
try:
|
|
68
|
+
resp = await self.client.post(
|
|
69
|
+
url,
|
|
70
|
+
params=params,
|
|
71
|
+
data=data,
|
|
72
|
+
json=json,
|
|
73
|
+
timeout=self._config.timeout,
|
|
74
|
+
cookies=cookies_dict,
|
|
75
|
+
headers=headers,
|
|
76
|
+
)
|
|
77
|
+
async with resp:
|
|
78
|
+
if resp.status == 200:
|
|
79
|
+
response_data = await resp.read()
|
|
80
|
+
if return_json:
|
|
81
|
+
response_data = json_loads(response_data.decode())
|
|
82
|
+
|
|
83
|
+
except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError) as ex:
|
|
84
|
+
raise ConnectionException(
|
|
85
|
+
f"Device connection error: {self._config.host}: {ex}", ex
|
|
86
|
+
) from ex
|
|
87
|
+
except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as ex:
|
|
88
|
+
raise TimeoutException(
|
|
89
|
+
"Unable to query the device, "
|
|
90
|
+
+ f"timed out: {self._config.host}: {ex}",
|
|
91
|
+
ex,
|
|
92
|
+
) from ex
|
|
93
|
+
except Exception as ex:
|
|
94
|
+
raise SmartDeviceException(
|
|
95
|
+
f"Unable to query the device: {self._config.host}: {ex}", ex
|
|
96
|
+
) from ex
|
|
97
|
+
|
|
98
|
+
return resp.status, response_data
|
|
99
|
+
|
|
100
|
+
def get_cookie(self, cookie_name: str) -> Optional[str]:
|
|
101
|
+
"""Return the cookie with cookie_name."""
|
|
102
|
+
if cookie := self.client.cookie_jar.filter_cookies(self._last_url).get(
|
|
103
|
+
cookie_name
|
|
104
|
+
):
|
|
105
|
+
return cookie.value
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
async def close(self) -> None:
|
|
109
|
+
"""Close the ClientSession."""
|
|
110
|
+
client = self._client_session
|
|
111
|
+
self._client_session = None
|
|
112
|
+
if client:
|
|
113
|
+
await client.close()
|
kasa/iotprotocol.py
CHANGED
|
@@ -3,18 +3,24 @@ import asyncio
|
|
|
3
3
|
import logging
|
|
4
4
|
from typing import Dict, Union
|
|
5
5
|
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
AuthenticationException,
|
|
8
|
+
ConnectionException,
|
|
9
|
+
RetryableException,
|
|
10
|
+
SmartDeviceException,
|
|
11
|
+
TimeoutException,
|
|
12
|
+
)
|
|
9
13
|
from .json import dumps as json_dumps
|
|
10
|
-
from .protocol import
|
|
14
|
+
from .protocol import BaseProtocol, BaseTransport
|
|
11
15
|
|
|
12
16
|
_LOGGER = logging.getLogger(__name__)
|
|
13
17
|
|
|
14
18
|
|
|
15
|
-
class IotProtocol(
|
|
19
|
+
class IotProtocol(BaseProtocol):
|
|
16
20
|
"""Class for the legacy TPLink IOT KASA Protocol."""
|
|
17
21
|
|
|
22
|
+
BACKOFF_SECONDS_AFTER_TIMEOUT = 1
|
|
23
|
+
|
|
18
24
|
def __init__(
|
|
19
25
|
self,
|
|
20
26
|
*,
|
|
@@ -38,40 +44,38 @@ class IotProtocol(TPLinkProtocol):
|
|
|
38
44
|
for retry in range(retry_count + 1):
|
|
39
45
|
try:
|
|
40
46
|
return await self._execute_query(request, retry)
|
|
41
|
-
except
|
|
47
|
+
except ConnectionException as sdex:
|
|
42
48
|
if retry >= retry_count:
|
|
43
|
-
await self.close()
|
|
44
49
|
_LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
|
|
45
|
-
raise
|
|
46
|
-
f"Unable to connect to the device: {self._host}: {sdex}"
|
|
47
|
-
) from sdex
|
|
50
|
+
raise sdex
|
|
48
51
|
continue
|
|
49
|
-
except TimeoutError as tex:
|
|
50
|
-
await self.close()
|
|
51
|
-
raise SmartDeviceException(
|
|
52
|
-
f"Unable to connect to the device, timed out: {self._host}: {tex}"
|
|
53
|
-
) from tex
|
|
54
52
|
except AuthenticationException as auex:
|
|
55
|
-
await self.
|
|
53
|
+
await self._transport.reset()
|
|
56
54
|
_LOGGER.debug(
|
|
57
55
|
"Unable to authenticate with %s, not retrying", self._host
|
|
58
56
|
)
|
|
59
57
|
raise auex
|
|
58
|
+
except RetryableException as ex:
|
|
59
|
+
await self._transport.reset()
|
|
60
|
+
if retry >= retry_count:
|
|
61
|
+
_LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
|
|
62
|
+
raise ex
|
|
63
|
+
continue
|
|
64
|
+
except TimeoutException as ex:
|
|
65
|
+
await self._transport.reset()
|
|
66
|
+
if retry >= retry_count:
|
|
67
|
+
_LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
|
|
68
|
+
raise ex
|
|
69
|
+
await asyncio.sleep(self.BACKOFF_SECONDS_AFTER_TIMEOUT)
|
|
70
|
+
continue
|
|
60
71
|
except SmartDeviceException as ex:
|
|
72
|
+
await self._transport.reset()
|
|
61
73
|
_LOGGER.debug(
|
|
62
|
-
"Unable to
|
|
74
|
+
"Unable to query the device: %s, not retrying: %s",
|
|
63
75
|
self._host,
|
|
64
76
|
ex,
|
|
65
77
|
)
|
|
66
78
|
raise ex
|
|
67
|
-
except Exception as ex:
|
|
68
|
-
if retry >= retry_count:
|
|
69
|
-
await self.close()
|
|
70
|
-
_LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
|
|
71
|
-
raise SmartDeviceException(
|
|
72
|
-
f"Unable to connect to the device: {self._host}: {ex}"
|
|
73
|
-
) from ex
|
|
74
|
-
continue
|
|
75
79
|
|
|
76
80
|
# make mypy happy, this should never be reached..
|
|
77
81
|
raise SmartDeviceException("Query reached somehow to unreachable")
|
|
@@ -80,5 +84,5 @@ class IotProtocol(TPLinkProtocol):
|
|
|
80
84
|
return await self._transport.send(request)
|
|
81
85
|
|
|
82
86
|
async def close(self) -> None:
|
|
83
|
-
"""Close the
|
|
87
|
+
"""Close the underlying transport."""
|
|
84
88
|
await self._transport.close()
|
kasa/json.py
CHANGED
kasa/klaptransport.py
CHANGED
|
@@ -26,11 +26,11 @@ finds a match it moves onto handshake2
|
|
|
26
26
|
|
|
27
27
|
handshake2: client sends sha25(remote_seed + auth_hash) to
|
|
28
28
|
the device along with the TP_SESSIONID. Device responds with
|
|
29
|
-
200 if
|
|
30
|
-
|
|
29
|
+
200 if successful. It generally will be because this
|
|
30
|
+
implementation checks the auth_hash it received during handshake1
|
|
31
31
|
|
|
32
32
|
encryption: local_seed, remote_seed and auth_hash are now used
|
|
33
|
-
for encryption. The last 4 bytes of the
|
|
33
|
+
for encryption. The last 4 bytes of the initialization vector
|
|
34
34
|
are used as a sequence number that increments every time the
|
|
35
35
|
client calls encrypt and this sequence number is sent as a
|
|
36
36
|
url parameter to the device along with the encrypted payload
|
|
@@ -48,20 +48,23 @@ import logging
|
|
|
48
48
|
import secrets
|
|
49
49
|
import time
|
|
50
50
|
from pprint import pformat as pf
|
|
51
|
-
from typing import Any, Optional, Tuple
|
|
51
|
+
from typing import Any, Dict, Optional, Tuple, cast
|
|
52
52
|
|
|
53
|
-
import httpx
|
|
54
53
|
from cryptography.hazmat.primitives import hashes, padding
|
|
55
54
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
56
55
|
|
|
57
56
|
from .credentials import Credentials
|
|
58
57
|
from .deviceconfig import DeviceConfig
|
|
59
58
|
from .exceptions import AuthenticationException, SmartDeviceException
|
|
59
|
+
from .httpclient import HttpClient
|
|
60
60
|
from .json import loads as json_loads
|
|
61
|
-
from .protocol import BaseTransport, md5
|
|
61
|
+
from .protocol import DEFAULT_CREDENTIALS, BaseTransport, get_default_credentials, md5
|
|
62
62
|
|
|
63
63
|
_LOGGER = logging.getLogger(__name__)
|
|
64
|
-
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
ONE_DAY_SECONDS = 86400
|
|
67
|
+
SESSION_EXPIRE_BUFFER_SECONDS = 60 * 20
|
|
65
68
|
|
|
66
69
|
|
|
67
70
|
def _sha256(payload: bytes) -> bytes:
|
|
@@ -86,10 +89,8 @@ class KlapTransport(BaseTransport):
|
|
|
86
89
|
|
|
87
90
|
DEFAULT_PORT: int = 80
|
|
88
91
|
DISCOVERY_QUERY = {"system": {"get_sysinfo": None}}
|
|
89
|
-
|
|
90
|
-
KASA_SETUP_EMAIL = "kasa@tp-link.net"
|
|
91
|
-
KASA_SETUP_PASSWORD = "kasaSetup" # noqa: S105
|
|
92
92
|
SESSION_COOKIE_NAME = "TP_SESSIONID"
|
|
93
|
+
TIMEOUT_COOKIE_NAME = "TIMEOUT"
|
|
93
94
|
|
|
94
95
|
def __init__(
|
|
95
96
|
self,
|
|
@@ -98,7 +99,7 @@ class KlapTransport(BaseTransport):
|
|
|
98
99
|
) -> None:
|
|
99
100
|
super().__init__(config=config)
|
|
100
101
|
|
|
101
|
-
self.
|
|
102
|
+
self._http_client = HttpClient(config)
|
|
102
103
|
self._local_seed: Optional[bytes] = None
|
|
103
104
|
if (
|
|
104
105
|
not self._credentials or self._credentials.username is None
|
|
@@ -109,7 +110,7 @@ class KlapTransport(BaseTransport):
|
|
|
109
110
|
self._local_auth_owner = self.generate_owner_hash(self._credentials).hex()
|
|
110
111
|
else:
|
|
111
112
|
self._local_auth_hash = base64.b64decode(self._credentials_hash.encode()) # type: ignore[union-attr]
|
|
112
|
-
self.
|
|
113
|
+
self._default_credentials_auth_hash: Dict[str, bytes] = {}
|
|
113
114
|
self._blank_auth_hash = None
|
|
114
115
|
self._handshake_lock = asyncio.Lock()
|
|
115
116
|
self._query_lock = asyncio.Lock()
|
|
@@ -118,7 +119,7 @@ class KlapTransport(BaseTransport):
|
|
|
118
119
|
self._encryption_session: Optional[KlapEncryptionSession] = None
|
|
119
120
|
self._session_expire_at: Optional[float] = None
|
|
120
121
|
|
|
121
|
-
self._session_cookie = None
|
|
122
|
+
self._session_cookie: Optional[Dict[str, Any]] = None
|
|
122
123
|
|
|
123
124
|
_LOGGER.debug("Created KLAP transport for %s", self._host)
|
|
124
125
|
|
|
@@ -132,34 +133,6 @@ class KlapTransport(BaseTransport):
|
|
|
132
133
|
"""The hashed credentials used by the transport."""
|
|
133
134
|
return base64.b64encode(self._local_auth_hash).decode()
|
|
134
135
|
|
|
135
|
-
@property
|
|
136
|
-
def _http_client(self) -> httpx.AsyncClient:
|
|
137
|
-
if self._config.http_client:
|
|
138
|
-
return self._config.http_client
|
|
139
|
-
if not self._default_http_client:
|
|
140
|
-
self._default_http_client = httpx.AsyncClient()
|
|
141
|
-
return self._default_http_client
|
|
142
|
-
|
|
143
|
-
async def client_post(self, url, params=None, data=None):
|
|
144
|
-
"""Send an http post request to the device."""
|
|
145
|
-
response_data = None
|
|
146
|
-
cookies = None
|
|
147
|
-
if self._session_cookie:
|
|
148
|
-
cookies = httpx.Cookies()
|
|
149
|
-
cookies.set(self.SESSION_COOKIE_NAME, self._session_cookie)
|
|
150
|
-
self._http_client.cookies.clear()
|
|
151
|
-
resp = await self._http_client.post(
|
|
152
|
-
url,
|
|
153
|
-
params=params,
|
|
154
|
-
data=data,
|
|
155
|
-
timeout=self._timeout,
|
|
156
|
-
cookies=cookies,
|
|
157
|
-
)
|
|
158
|
-
if resp.status_code == 200:
|
|
159
|
-
response_data = resp.content
|
|
160
|
-
|
|
161
|
-
return resp.status_code, response_data
|
|
162
|
-
|
|
163
136
|
async def perform_handshake1(self) -> Tuple[bytes, bytes, bytes]:
|
|
164
137
|
"""Perform handshake1."""
|
|
165
138
|
local_seed: bytes = secrets.token_bytes(16)
|
|
@@ -172,7 +145,7 @@ class KlapTransport(BaseTransport):
|
|
|
172
145
|
|
|
173
146
|
url = f"http://{self._host}/app/handshake1"
|
|
174
147
|
|
|
175
|
-
response_status, response_data = await self.
|
|
148
|
+
response_status, response_data = await self._http_client.post(url, data=payload)
|
|
176
149
|
|
|
177
150
|
if _LOGGER.isEnabledFor(logging.DEBUG):
|
|
178
151
|
_LOGGER.debug(
|
|
@@ -189,6 +162,7 @@ class KlapTransport(BaseTransport):
|
|
|
189
162
|
f"Device {self._host} responded with {response_status} to handshake1"
|
|
190
163
|
)
|
|
191
164
|
|
|
165
|
+
response_data = cast(bytes, response_data)
|
|
192
166
|
remote_seed: bytes = response_data[0:16]
|
|
193
167
|
server_hash = response_data[16:]
|
|
194
168
|
|
|
@@ -211,27 +185,27 @@ class KlapTransport(BaseTransport):
|
|
|
211
185
|
_LOGGER.debug("handshake1 hashes match with expected credentials")
|
|
212
186
|
return local_seed, remote_seed, self._local_auth_hash # type: ignore
|
|
213
187
|
|
|
214
|
-
# Now check against the default
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
kasa_setup_seed_auth_hash = self.handshake1_seed_auth_hash(
|
|
223
|
-
local_seed,
|
|
224
|
-
remote_seed,
|
|
225
|
-
self._kasa_setup_auth_hash, # type: ignore
|
|
226
|
-
)
|
|
188
|
+
# Now check against the default setup credentials
|
|
189
|
+
for key, value in DEFAULT_CREDENTIALS.items():
|
|
190
|
+
if key not in self._default_credentials_auth_hash:
|
|
191
|
+
default_credentials = get_default_credentials(value)
|
|
192
|
+
self._default_credentials_auth_hash[key] = self.generate_auth_hash(
|
|
193
|
+
default_credentials
|
|
194
|
+
)
|
|
227
195
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
self._host,
|
|
196
|
+
default_credentials_seed_auth_hash = self.handshake1_seed_auth_hash(
|
|
197
|
+
local_seed,
|
|
198
|
+
remote_seed,
|
|
199
|
+
self._default_credentials_auth_hash[key], # type: ignore
|
|
233
200
|
)
|
|
234
|
-
|
|
201
|
+
|
|
202
|
+
if default_credentials_seed_auth_hash == server_hash:
|
|
203
|
+
_LOGGER.debug(
|
|
204
|
+
"Server response doesn't match our expected hash on ip %s"
|
|
205
|
+
+ f" but an authentication with {key} default credentials matched",
|
|
206
|
+
self._host,
|
|
207
|
+
)
|
|
208
|
+
return local_seed, remote_seed, self._default_credentials_auth_hash[key] # type: ignore
|
|
235
209
|
|
|
236
210
|
# Finally check against blank credentials if not already blank
|
|
237
211
|
blank_creds = Credentials()
|
|
@@ -268,7 +242,11 @@ class KlapTransport(BaseTransport):
|
|
|
268
242
|
|
|
269
243
|
payload = self.handshake2_seed_auth_hash(local_seed, remote_seed, auth_hash)
|
|
270
244
|
|
|
271
|
-
response_status,
|
|
245
|
+
response_status, _ = await self._http_client.post(
|
|
246
|
+
url,
|
|
247
|
+
data=payload,
|
|
248
|
+
cookies_dict=self._session_cookie,
|
|
249
|
+
)
|
|
272
250
|
|
|
273
251
|
if _LOGGER.isEnabledFor(logging.DEBUG):
|
|
274
252
|
_LOGGER.debug(
|
|
@@ -298,13 +276,18 @@ class KlapTransport(BaseTransport):
|
|
|
298
276
|
self._session_cookie = None
|
|
299
277
|
|
|
300
278
|
local_seed, remote_seed, auth_hash = await self.perform_handshake1()
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
279
|
+
http_client = self._http_client
|
|
280
|
+
if cookie := http_client.get_cookie(self.SESSION_COOKIE_NAME): # type: ignore
|
|
281
|
+
self._session_cookie = {self.SESSION_COOKIE_NAME: cookie}
|
|
304
282
|
# The device returns a TIMEOUT cookie on handshake1 which
|
|
305
283
|
# it doesn't like to get back so we store the one we want
|
|
306
|
-
|
|
307
|
-
|
|
284
|
+
timeout = int(
|
|
285
|
+
http_client.get_cookie(self.TIMEOUT_COOKIE_NAME) or ONE_DAY_SECONDS
|
|
286
|
+
)
|
|
287
|
+
# There is a 24 hour timeout on the session cookie
|
|
288
|
+
# but the clock on the device is not always accurate
|
|
289
|
+
# so we set the expiry to 24 hours from now minus a buffer
|
|
290
|
+
self._session_expire_at = time.time() + timeout - SESSION_EXPIRE_BUFFER_SECONDS
|
|
308
291
|
self._encryption_session = await self.perform_handshake2(
|
|
309
292
|
local_seed, remote_seed, auth_hash
|
|
310
293
|
)
|
|
@@ -330,19 +313,20 @@ class KlapTransport(BaseTransport):
|
|
|
330
313
|
|
|
331
314
|
url = f"http://{self._host}/app/request"
|
|
332
315
|
|
|
333
|
-
response_status, response_data = await self.
|
|
316
|
+
response_status, response_data = await self._http_client.post(
|
|
334
317
|
url,
|
|
335
318
|
params={"seq": seq},
|
|
336
319
|
data=payload,
|
|
320
|
+
cookies_dict=self._session_cookie,
|
|
337
321
|
)
|
|
338
322
|
|
|
339
323
|
msg = (
|
|
340
|
-
f"
|
|
324
|
+
f"Host is {self._host}, "
|
|
341
325
|
+ f"Sequence is {seq}, "
|
|
342
326
|
+ f"Response status is {response_status}, Request was {request}"
|
|
343
327
|
)
|
|
344
328
|
if response_status != 200:
|
|
345
|
-
_LOGGER.error("Query failed after
|
|
329
|
+
_LOGGER.error("Query failed after successful authentication " + msg)
|
|
346
330
|
# If we failed with a security error, force a new handshake next time.
|
|
347
331
|
if response_status == 403:
|
|
348
332
|
self._handshake_done = False
|
|
@@ -373,12 +357,13 @@ class KlapTransport(BaseTransport):
|
|
|
373
357
|
return json_payload
|
|
374
358
|
|
|
375
359
|
async def close(self) -> None:
|
|
376
|
-
"""Close the
|
|
377
|
-
|
|
378
|
-
self.
|
|
360
|
+
"""Close the http client and reset internal state."""
|
|
361
|
+
await self.reset()
|
|
362
|
+
await self._http_client.close()
|
|
363
|
+
|
|
364
|
+
async def reset(self) -> None:
|
|
365
|
+
"""Reset internal handshake state."""
|
|
379
366
|
self._handshake_done = False
|
|
380
|
-
if client:
|
|
381
|
-
await client.aclose()
|
|
382
367
|
|
|
383
368
|
@staticmethod
|
|
384
369
|
def generate_auth_hash(creds: Credentials):
|
kasa/modules/emeter.py
CHANGED
|
@@ -63,7 +63,7 @@ class Emeter(Usage):
|
|
|
63
63
|
self,
|
|
64
64
|
data: List[Dict[str, Union[int, float]]],
|
|
65
65
|
entry_key: str,
|
|
66
|
-
kwh: bool=True,
|
|
66
|
+
kwh: bool = True,
|
|
67
67
|
key: Optional[int] = None,
|
|
68
68
|
) -> Dict[Union[int, float], Union[int, float]]:
|
|
69
69
|
"""Return emeter information keyed with the day/month.
|