python-kasa 0.6.2__py3-none-any.whl → 0.7.0.dev0__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 +88 -27
- kasa/aestransport.py +51 -34
- kasa/cli.py +326 -130
- kasa/device.py +406 -0
- kasa/device_factory.py +83 -44
- kasa/device_type.py +7 -3
- kasa/deviceconfig.py +16 -9
- kasa/discover.py +100 -81
- kasa/emeterstatus.py +12 -7
- kasa/exceptions.py +41 -26
- kasa/feature.py +201 -0
- kasa/httpclient.py +21 -14
- kasa/interfaces/__init__.py +16 -0
- kasa/interfaces/fan.py +20 -0
- kasa/interfaces/led.py +38 -0
- kasa/interfaces/light.py +133 -0
- kasa/interfaces/lighteffect.py +80 -0
- kasa/interfaces/lightpreset.py +76 -0
- kasa/iot/__init__.py +18 -0
- kasa/{effects.py → iot/effects.py} +4 -2
- kasa/{smartbulb.py → iot/iotbulb.py} +100 -147
- kasa/{smartdevice.py → iot/iotdevice.py} +157 -286
- kasa/{smartdimmer.py → iot/iotdimmer.py} +42 -33
- kasa/iot/iotlightstrip.py +71 -0
- kasa/{modules/module.py → iot/iotmodule.py} +22 -42
- kasa/iot/iotplug.py +94 -0
- kasa/{smartstrip.py → iot/iotstrip.py} +57 -75
- kasa/{modules → iot/modules}/__init__.py +10 -2
- kasa/{modules → iot/modules}/ambientlight.py +31 -3
- kasa/{modules → iot/modules}/antitheft.py +1 -0
- kasa/{modules → iot/modules}/cloud.py +25 -6
- kasa/{modules → iot/modules}/countdown.py +1 -0
- kasa/iot/modules/emeter.py +210 -0
- kasa/iot/modules/led.py +32 -0
- kasa/iot/modules/light.py +221 -0
- kasa/iot/modules/lighteffect.py +122 -0
- kasa/iot/modules/lightpreset.py +151 -0
- kasa/{modules → iot/modules}/motion.py +8 -8
- kasa/{modules → iot/modules}/rulemodule.py +11 -12
- kasa/{modules → iot/modules}/schedule.py +1 -0
- kasa/{modules → iot/modules}/time.py +5 -4
- kasa/{modules → iot/modules}/usage.py +10 -8
- kasa/iotprotocol.py +22 -20
- kasa/klaptransport.py +25 -15
- kasa/module.py +136 -0
- kasa/modulemapping.py +25 -0
- kasa/modulemapping.pyi +96 -0
- kasa/protocol.py +6 -4
- kasa/smart/__init__.py +6 -0
- kasa/smart/effects.py +429 -0
- kasa/smart/modules/__init__.py +57 -0
- kasa/smart/modules/alarm.py +142 -0
- kasa/smart/modules/autooff.py +96 -0
- kasa/smart/modules/batterysensor.py +54 -0
- kasa/smart/modules/brightness.py +66 -0
- kasa/smart/modules/childdevice.py +10 -0
- kasa/smart/modules/cloud.py +42 -0
- kasa/smart/modules/color.py +96 -0
- kasa/smart/modules/colortemperature.py +78 -0
- kasa/smart/modules/contactsensor.py +42 -0
- kasa/smart/modules/devicemodule.py +22 -0
- kasa/smart/modules/energy.py +101 -0
- kasa/smart/modules/fan.py +80 -0
- kasa/smart/modules/firmware.py +216 -0
- kasa/smart/modules/frostprotection.py +59 -0
- kasa/smart/modules/humiditysensor.py +55 -0
- kasa/smart/modules/led.py +49 -0
- kasa/smart/modules/light.py +139 -0
- kasa/smart/modules/lighteffect.py +115 -0
- kasa/smart/modules/lightpreset.py +142 -0
- kasa/smart/modules/lightstripeffect.py +135 -0
- kasa/smart/modules/lighttransition.py +183 -0
- kasa/smart/modules/reportmode.py +36 -0
- kasa/smart/modules/temperaturecontrol.py +177 -0
- kasa/smart/modules/temperaturesensor.py +77 -0
- kasa/smart/modules/time.py +57 -0
- kasa/smart/modules/waterleaksensor.py +66 -0
- kasa/smart/smartchilddevice.py +65 -0
- kasa/smart/smartdevice.py +653 -0
- kasa/smart/smartmodule.py +112 -0
- kasa/smartprotocol.py +107 -41
- kasa/tests/conftest.py +27 -551
- kasa/tests/device_fixtures.py +427 -0
- kasa/tests/discovery_fixtures.py +197 -0
- kasa/tests/{newfakes.py → fakeprotocol_iot.py} +61 -291
- kasa/tests/fakeprotocol_smart.py +318 -0
- kasa/tests/fixtureinfo.py +154 -0
- kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +221 -0
- kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +547 -0
- kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +391 -0
- kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +1557 -0
- kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +899 -0
- kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +479 -0
- kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +449 -0
- kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +173 -0
- kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +204 -0
- kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +566 -0
- kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.13.json +13 -23
- kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +6 -6
- kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +295 -0
- kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +423 -0
- kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
- kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
- kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
- kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
- kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
- kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
- kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
- kasa/tests/smart/__init__.py +0 -0
- kasa/tests/smart/features/__init__.py +0 -0
- kasa/tests/smart/features/test_brightness.py +55 -0
- kasa/tests/smart/features/test_colortemp.py +30 -0
- kasa/tests/smart/modules/__init__.py +0 -0
- kasa/tests/smart/modules/test_contact.py +28 -0
- kasa/tests/smart/modules/test_fan.py +79 -0
- kasa/tests/smart/modules/test_firmware.py +108 -0
- kasa/tests/smart/modules/test_humidity.py +28 -0
- kasa/tests/smart/modules/test_light_effect.py +41 -0
- kasa/tests/smart/modules/test_temperature.py +47 -0
- kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
- kasa/tests/smart/modules/test_waterleak.py +42 -0
- kasa/tests/test_aestransport.py +115 -25
- kasa/tests/test_bulb.py +169 -86
- kasa/tests/test_childdevice.py +84 -0
- kasa/tests/test_cli.py +452 -100
- kasa/tests/test_common_modules.py +216 -0
- kasa/tests/test_device.py +268 -0
- kasa/tests/test_device_factory.py +61 -41
- kasa/tests/test_device_type.py +1 -1
- kasa/tests/test_deviceconfig.py +2 -5
- kasa/tests/test_dimmer.py +33 -24
- kasa/tests/test_discovery.py +112 -69
- kasa/tests/test_emeter.py +39 -12
- kasa/tests/test_feature.py +205 -0
- kasa/tests/test_httpclient.py +9 -9
- kasa/tests/test_iotdevice.py +286 -0
- kasa/tests/test_klapprotocol.py +94 -41
- kasa/tests/test_lightstrip.py +24 -19
- kasa/tests/test_plug.py +51 -9
- kasa/tests/test_protocol.py +8 -12
- kasa/tests/test_readme_examples.py +86 -27
- kasa/tests/test_smartdevice.py +211 -247
- kasa/tests/test_smartprotocol.py +129 -26
- kasa/tests/test_strip.py +15 -6
- kasa/tests/test_usage.py +1 -3
- kasa/xortransport.py +15 -12
- {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -141
- python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
- {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +1 -1
- kasa/modules/emeter.py +0 -111
- kasa/smartlightstrip.py +0 -143
- kasa/smartplug.py +0 -91
- kasa/tapo/__init__.py +0 -7
- kasa/tapo/childdevice.py +0 -44
- kasa/tapo/tapobulb.py +0 -262
- kasa/tapo/tapodevice.py +0 -383
- kasa/tapo/tapoplug.py +0 -45
- kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
- kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
- kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
- kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
- kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
- kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
- kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
- kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
- python_kasa-0.6.2.dist-info/RECORD +0 -163
- {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
- {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
kasa/deviceconfig.py
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
|
-
"""Module for holding connection parameters.
|
|
1
|
+
"""Module for holding connection parameters.
|
|
2
|
+
|
|
3
|
+
Note that this module does not work with from __future__ import annotations
|
|
4
|
+
due to it's use of type returned by fields() which becomes a string with the import.
|
|
5
|
+
https://bugs.python.org/issue39442
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
# ruff: noqa: FA100
|
|
2
9
|
import logging
|
|
3
10
|
from dataclasses import asdict, dataclass, field, fields, is_dataclass
|
|
4
11
|
from enum import Enum
|
|
5
12
|
from typing import TYPE_CHECKING, Dict, Optional, Union
|
|
6
13
|
|
|
7
14
|
from .credentials import Credentials
|
|
8
|
-
from .exceptions import
|
|
15
|
+
from .exceptions import KasaException
|
|
9
16
|
|
|
10
17
|
if TYPE_CHECKING:
|
|
11
18
|
from aiohttp import ClientSession
|
|
@@ -31,6 +38,8 @@ class DeviceFamilyType(Enum):
|
|
|
31
38
|
SmartTapoPlug = "SMART.TAPOPLUG"
|
|
32
39
|
SmartTapoBulb = "SMART.TAPOBULB"
|
|
33
40
|
SmartTapoSwitch = "SMART.TAPOSWITCH"
|
|
41
|
+
SmartTapoHub = "SMART.TAPOHUB"
|
|
42
|
+
SmartKasaHub = "SMART.KASAHUB"
|
|
34
43
|
|
|
35
44
|
|
|
36
45
|
def _dataclass_from_dict(klass, in_val):
|
|
@@ -46,7 +55,7 @@ def _dataclass_from_dict(klass, in_val):
|
|
|
46
55
|
fieldtypes[dict_key], in_val[dict_key]
|
|
47
56
|
)
|
|
48
57
|
else:
|
|
49
|
-
raise
|
|
58
|
+
raise KasaException(
|
|
50
59
|
f"Cannot create dataclass from dict, unknown key: {dict_key}"
|
|
51
60
|
)
|
|
52
61
|
return klass(**val)
|
|
@@ -92,7 +101,7 @@ class ConnectionType:
|
|
|
92
101
|
login_version,
|
|
93
102
|
)
|
|
94
103
|
except (ValueError, TypeError) as ex:
|
|
95
|
-
raise
|
|
104
|
+
raise KasaException(
|
|
96
105
|
f"Invalid connection parameters for {device_family}."
|
|
97
106
|
+ f"{encryption_type}.{login_version}"
|
|
98
107
|
) from ex
|
|
@@ -113,9 +122,7 @@ class ConnectionType:
|
|
|
113
122
|
login_version, # type: ignore[arg-type]
|
|
114
123
|
)
|
|
115
124
|
|
|
116
|
-
raise
|
|
117
|
-
f"Invalid connection type data for {connection_type_dict}"
|
|
118
|
-
)
|
|
125
|
+
raise KasaException(f"Invalid connection type data for {connection_type_dict}")
|
|
119
126
|
|
|
120
127
|
def to_dict(self) -> Dict[str, Union[str, int]]:
|
|
121
128
|
"""Convert connection params to dict."""
|
|
@@ -143,7 +150,7 @@ class DeviceConfig:
|
|
|
143
150
|
credentials: Optional[Credentials] = None
|
|
144
151
|
#: Credentials hash for devices requiring authentication.
|
|
145
152
|
#: If credentials are also supplied they take precendence over credentials_hash.
|
|
146
|
-
#: Credentials hash can be retrieved from :attr:`
|
|
153
|
+
#: Credentials hash can be retrieved from :attr:`Device.credentials_hash`
|
|
147
154
|
credentials_hash: Optional[str] = None
|
|
148
155
|
#: The protocol specific type of connection. Defaults to the legacy type.
|
|
149
156
|
batch_size: Optional[int] = None
|
|
@@ -185,4 +192,4 @@ class DeviceConfig:
|
|
|
185
192
|
"""Return device config from dict."""
|
|
186
193
|
if isinstance(config_dict, dict):
|
|
187
194
|
return _dataclass_from_dict(DeviceConfig, config_dict)
|
|
188
|
-
raise
|
|
195
|
+
raise KasaException(f"Invalid device config data: {config_dict}")
|
kasa/discover.py
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
"""Discovery module for TP-Link Smart Home devices."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
2
5
|
import asyncio
|
|
3
6
|
import binascii
|
|
4
7
|
import ipaddress
|
|
5
8
|
import logging
|
|
6
9
|
import socket
|
|
7
|
-
from typing import Awaitable, Callable, Dict, Optional,
|
|
10
|
+
from typing import Awaitable, Callable, Dict, Optional, Type, cast
|
|
8
11
|
|
|
9
12
|
# When support for cpython older than 3.11 is dropped
|
|
10
13
|
# async_timeout can be replaced with asyncio.timeout
|
|
11
14
|
from async_timeout import timeout as asyncio_timeout
|
|
15
|
+
from pydantic.v1 import BaseModel, ValidationError
|
|
12
16
|
|
|
13
|
-
|
|
14
|
-
from pydantic.v1 import BaseModel, ValidationError # pragma: no cover
|
|
15
|
-
except ImportError:
|
|
16
|
-
from pydantic import BaseModel, ValidationError # pragma: no cover
|
|
17
|
-
|
|
17
|
+
from kasa import Device
|
|
18
18
|
from kasa.credentials import Credentials
|
|
19
19
|
from kasa.device_factory import (
|
|
20
20
|
get_device_class_from_family,
|
|
@@ -22,17 +22,22 @@ from kasa.device_factory import (
|
|
|
22
22
|
get_protocol,
|
|
23
23
|
)
|
|
24
24
|
from kasa.deviceconfig import ConnectionType, DeviceConfig, EncryptType
|
|
25
|
-
from kasa.exceptions import
|
|
25
|
+
from kasa.exceptions import (
|
|
26
|
+
KasaException,
|
|
27
|
+
TimeoutError,
|
|
28
|
+
UnsupportedDeviceError,
|
|
29
|
+
)
|
|
30
|
+
from kasa.iot.iotdevice import IotDevice
|
|
26
31
|
from kasa.json import dumps as json_dumps
|
|
27
32
|
from kasa.json import loads as json_loads
|
|
28
|
-
from kasa.smartdevice import SmartDevice, SmartDeviceException
|
|
29
33
|
from kasa.xortransport import XorEncryption
|
|
30
34
|
|
|
31
35
|
_LOGGER = logging.getLogger(__name__)
|
|
32
36
|
|
|
33
37
|
|
|
34
|
-
OnDiscoveredCallable = Callable[[
|
|
35
|
-
|
|
38
|
+
OnDiscoveredCallable = Callable[[Device], Awaitable[None]]
|
|
39
|
+
OnUnsupportedCallable = Callable[[UnsupportedDeviceError], Awaitable[None]]
|
|
40
|
+
DeviceDict = Dict[str, Device]
|
|
36
41
|
|
|
37
42
|
|
|
38
43
|
class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
@@ -41,23 +46,22 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
41
46
|
This is internal class, use :func:`Discover.discover`: instead.
|
|
42
47
|
"""
|
|
43
48
|
|
|
49
|
+
DISCOVERY_START_TIMEOUT = 1
|
|
50
|
+
|
|
44
51
|
discovered_devices: DeviceDict
|
|
45
52
|
|
|
46
53
|
def __init__(
|
|
47
54
|
self,
|
|
48
55
|
*,
|
|
49
|
-
on_discovered:
|
|
56
|
+
on_discovered: OnDiscoveredCallable | None = None,
|
|
50
57
|
target: str = "255.255.255.255",
|
|
51
58
|
discovery_packets: int = 3,
|
|
52
59
|
discovery_timeout: int = 5,
|
|
53
|
-
interface:
|
|
54
|
-
on_unsupported:
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
discovered_event: Optional[asyncio.Event] = None,
|
|
59
|
-
credentials: Optional[Credentials] = None,
|
|
60
|
-
timeout: Optional[int] = None,
|
|
60
|
+
interface: str | None = None,
|
|
61
|
+
on_unsupported: OnUnsupportedCallable | None = None,
|
|
62
|
+
port: int | None = None,
|
|
63
|
+
credentials: Credentials | None = None,
|
|
64
|
+
timeout: int | None = None,
|
|
61
65
|
) -> None:
|
|
62
66
|
self.transport = None
|
|
63
67
|
self.discovery_packets = discovery_packets
|
|
@@ -71,15 +75,35 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
71
75
|
self.target_2 = (target, Discover.DISCOVERY_PORT_2)
|
|
72
76
|
|
|
73
77
|
self.discovered_devices = {}
|
|
74
|
-
self.unsupported_device_exceptions:
|
|
75
|
-
self.invalid_device_exceptions:
|
|
78
|
+
self.unsupported_device_exceptions: dict = {}
|
|
79
|
+
self.invalid_device_exceptions: dict = {}
|
|
76
80
|
self.on_unsupported = on_unsupported
|
|
77
|
-
self.discovered_event = discovered_event
|
|
78
81
|
self.credentials = credentials
|
|
79
82
|
self.timeout = timeout
|
|
80
83
|
self.discovery_timeout = discovery_timeout
|
|
81
|
-
self.seen_hosts:
|
|
82
|
-
self.discover_task:
|
|
84
|
+
self.seen_hosts: set[str] = set()
|
|
85
|
+
self.discover_task: asyncio.Task | None = None
|
|
86
|
+
self.callback_tasks: list[asyncio.Task] = []
|
|
87
|
+
self.target_discovered: bool = False
|
|
88
|
+
self._started_event = asyncio.Event()
|
|
89
|
+
|
|
90
|
+
def _run_callback_task(self, coro):
|
|
91
|
+
task = asyncio.create_task(coro)
|
|
92
|
+
self.callback_tasks.append(task)
|
|
93
|
+
|
|
94
|
+
async def wait_for_discovery_to_complete(self):
|
|
95
|
+
"""Wait for the discovery task to complete."""
|
|
96
|
+
# Give some time for connection_made event to be received
|
|
97
|
+
async with asyncio_timeout(self.DISCOVERY_START_TIMEOUT):
|
|
98
|
+
await self._started_event.wait()
|
|
99
|
+
try:
|
|
100
|
+
await self.discover_task
|
|
101
|
+
except asyncio.CancelledError:
|
|
102
|
+
# if target_discovered then cancel was called internally
|
|
103
|
+
if not self.target_discovered:
|
|
104
|
+
raise
|
|
105
|
+
# Wait for any pending callbacks to complete
|
|
106
|
+
await asyncio.gather(*self.callback_tasks)
|
|
83
107
|
|
|
84
108
|
def connection_made(self, transport) -> None:
|
|
85
109
|
"""Set socket options for broadcasting."""
|
|
@@ -98,6 +122,7 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
98
122
|
)
|
|
99
123
|
|
|
100
124
|
self.discover_task = asyncio.create_task(self.do_discover())
|
|
125
|
+
self._started_event.set()
|
|
101
126
|
|
|
102
127
|
async def do_discover(self) -> None:
|
|
103
128
|
"""Send number of discovery datagrams."""
|
|
@@ -105,13 +130,12 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
105
130
|
_LOGGER.debug("[DISCOVERY] %s >> %s", self.target, Discover.DISCOVERY_QUERY)
|
|
106
131
|
encrypted_req = XorEncryption.encrypt(req)
|
|
107
132
|
sleep_between_packets = self.discovery_timeout / self.discovery_packets
|
|
108
|
-
for
|
|
133
|
+
for _ in range(self.discovery_packets):
|
|
109
134
|
if self.target in self.seen_hosts: # Stop sending for discover_single
|
|
110
135
|
break
|
|
111
136
|
self.transport.sendto(encrypted_req[4:], self.target_1) # type: ignore
|
|
112
137
|
self.transport.sendto(Discover.DISCOVERY_QUERY_2, self.target_2) # type: ignore
|
|
113
|
-
|
|
114
|
-
await asyncio.sleep(sleep_between_packets)
|
|
138
|
+
await asyncio.sleep(sleep_between_packets)
|
|
115
139
|
|
|
116
140
|
def datagram_received(self, data, addr) -> None:
|
|
117
141
|
"""Handle discovery responses."""
|
|
@@ -121,7 +145,7 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
121
145
|
return
|
|
122
146
|
self.seen_hosts.add(ip)
|
|
123
147
|
|
|
124
|
-
device = None
|
|
148
|
+
device: Device | None = None
|
|
125
149
|
|
|
126
150
|
config = DeviceConfig(host=ip, port_override=self.port)
|
|
127
151
|
if self.credentials:
|
|
@@ -136,14 +160,14 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
136
160
|
device = Discover._get_device_instance(data, config)
|
|
137
161
|
else:
|
|
138
162
|
return
|
|
139
|
-
except
|
|
163
|
+
except UnsupportedDeviceError as udex:
|
|
140
164
|
_LOGGER.debug("Unsupported device found at %s << %s", ip, udex)
|
|
141
165
|
self.unsupported_device_exceptions[ip] = udex
|
|
142
166
|
if self.on_unsupported is not None:
|
|
143
|
-
|
|
167
|
+
self._run_callback_task(self.on_unsupported(udex))
|
|
144
168
|
self._handle_discovered_event()
|
|
145
169
|
return
|
|
146
|
-
except
|
|
170
|
+
except KasaException as ex:
|
|
147
171
|
_LOGGER.debug(f"[DISCOVERY] Unable to find device type for {ip}: {ex}")
|
|
148
172
|
self.invalid_device_exceptions[ip] = ex
|
|
149
173
|
self._handle_discovered_event()
|
|
@@ -152,16 +176,16 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
|
|
|
152
176
|
self.discovered_devices[ip] = device
|
|
153
177
|
|
|
154
178
|
if self.on_discovered is not None:
|
|
155
|
-
|
|
179
|
+
self._run_callback_task(self.on_discovered(device))
|
|
156
180
|
|
|
157
181
|
self._handle_discovered_event()
|
|
158
182
|
|
|
159
183
|
def _handle_discovered_event(self):
|
|
160
|
-
"""If
|
|
161
|
-
if self.
|
|
184
|
+
"""If target is in seen_hosts cancel discover_task."""
|
|
185
|
+
if self.target in self.seen_hosts:
|
|
186
|
+
self.target_discovered = True
|
|
162
187
|
if self.discover_task:
|
|
163
188
|
self.discover_task.cancel()
|
|
164
|
-
self.discovered_event.set()
|
|
165
189
|
|
|
166
190
|
def error_received(self, ex):
|
|
167
191
|
"""Handle asyncio.Protocol errors."""
|
|
@@ -246,10 +270,10 @@ class Discover:
|
|
|
246
270
|
you can use *target* parameter to specify the network for discovery.
|
|
247
271
|
|
|
248
272
|
If given, `on_discovered` coroutine will get awaited with
|
|
249
|
-
a :class:`
|
|
273
|
+
a :class:`Device`-derived object as parameter.
|
|
250
274
|
|
|
251
275
|
The results of the discovery are returned as a dict of
|
|
252
|
-
:class:`
|
|
276
|
+
:class:`Device`-derived objects keyed with IP addresses.
|
|
253
277
|
The devices are already initialized and all but emeter-related properties
|
|
254
278
|
can be accessed directly.
|
|
255
279
|
|
|
@@ -284,7 +308,11 @@ class Discover:
|
|
|
284
308
|
|
|
285
309
|
try:
|
|
286
310
|
_LOGGER.debug("Waiting %s seconds for responses...", discovery_timeout)
|
|
287
|
-
await
|
|
311
|
+
await protocol.wait_for_discovery_to_complete()
|
|
312
|
+
except KasaException as ex:
|
|
313
|
+
for device in protocol.discovered_devices.values():
|
|
314
|
+
await device.protocol.close()
|
|
315
|
+
raise ex
|
|
288
316
|
finally:
|
|
289
317
|
transport.close()
|
|
290
318
|
|
|
@@ -297,14 +325,14 @@ class Discover:
|
|
|
297
325
|
host: str,
|
|
298
326
|
*,
|
|
299
327
|
discovery_timeout: int = 5,
|
|
300
|
-
port:
|
|
301
|
-
timeout:
|
|
302
|
-
credentials:
|
|
303
|
-
) ->
|
|
328
|
+
port: int | None = None,
|
|
329
|
+
timeout: int | None = None,
|
|
330
|
+
credentials: Credentials | None = None,
|
|
331
|
+
) -> Device:
|
|
304
332
|
"""Discover a single device by the given IP address.
|
|
305
333
|
|
|
306
334
|
It is generally preferred to avoid :func:`discover_single()` and
|
|
307
|
-
use :meth:`
|
|
335
|
+
use :meth:`Device.connect()` instead as it should perform better when
|
|
308
336
|
the WiFi network is congested or the device is not responding
|
|
309
337
|
to discovery requests.
|
|
310
338
|
|
|
@@ -317,7 +345,6 @@ class Discover:
|
|
|
317
345
|
:return: Object for querying/controlling found device.
|
|
318
346
|
"""
|
|
319
347
|
loop = asyncio.get_event_loop()
|
|
320
|
-
event = asyncio.Event()
|
|
321
348
|
|
|
322
349
|
try:
|
|
323
350
|
ipaddress.ip_address(host)
|
|
@@ -339,15 +366,12 @@ class Discover:
|
|
|
339
366
|
# https://docs.python.org/3/library/socket.html#socket.getaddrinfo
|
|
340
367
|
ip = adrrinfo[0][4][0]
|
|
341
368
|
except socket.gaierror as gex:
|
|
342
|
-
raise
|
|
343
|
-
f"Could not resolve hostname {host}"
|
|
344
|
-
) from gex
|
|
369
|
+
raise KasaException(f"Could not resolve hostname {host}") from gex
|
|
345
370
|
|
|
346
371
|
transport, protocol = await loop.create_datagram_endpoint(
|
|
347
372
|
lambda: _DiscoverProtocol(
|
|
348
373
|
target=ip,
|
|
349
374
|
port=port,
|
|
350
|
-
discovered_event=event,
|
|
351
375
|
credentials=credentials,
|
|
352
376
|
timeout=timeout,
|
|
353
377
|
discovery_timeout=discovery_timeout,
|
|
@@ -360,13 +384,7 @@ class Discover:
|
|
|
360
384
|
_LOGGER.debug(
|
|
361
385
|
"Waiting a total of %s seconds for responses...", discovery_timeout
|
|
362
386
|
)
|
|
363
|
-
|
|
364
|
-
async with asyncio_timeout(discovery_timeout):
|
|
365
|
-
await event.wait()
|
|
366
|
-
except asyncio.TimeoutError as ex:
|
|
367
|
-
raise TimeoutException(
|
|
368
|
-
f"Timed out getting discovery response for {host}"
|
|
369
|
-
) from ex
|
|
387
|
+
await protocol.wait_for_discovery_to_complete()
|
|
370
388
|
finally:
|
|
371
389
|
transport.close()
|
|
372
390
|
|
|
@@ -379,16 +397,16 @@ class Discover:
|
|
|
379
397
|
elif ip in protocol.invalid_device_exceptions:
|
|
380
398
|
raise protocol.invalid_device_exceptions[ip]
|
|
381
399
|
else:
|
|
382
|
-
raise
|
|
400
|
+
raise TimeoutError(f"Timed out getting discovery response for {host}")
|
|
383
401
|
|
|
384
402
|
@staticmethod
|
|
385
|
-
def _get_device_class(info: dict) ->
|
|
403
|
+
def _get_device_class(info: dict) -> type[Device]:
|
|
386
404
|
"""Find SmartDevice subclass for device described by passed data."""
|
|
387
405
|
if "result" in info:
|
|
388
406
|
discovery_result = DiscoveryResult(**info["result"])
|
|
389
407
|
dev_class = get_device_class_from_family(discovery_result.device_type)
|
|
390
408
|
if not dev_class:
|
|
391
|
-
raise
|
|
409
|
+
raise UnsupportedDeviceError(
|
|
392
410
|
"Unknown device type: %s" % discovery_result.device_type,
|
|
393
411
|
discovery_result=info,
|
|
394
412
|
)
|
|
@@ -397,18 +415,18 @@ class Discover:
|
|
|
397
415
|
return get_device_class_from_sys_info(info)
|
|
398
416
|
|
|
399
417
|
@staticmethod
|
|
400
|
-
def _get_device_instance_legacy(data: bytes, config: DeviceConfig) ->
|
|
418
|
+
def _get_device_instance_legacy(data: bytes, config: DeviceConfig) -> IotDevice:
|
|
401
419
|
"""Get SmartDevice from legacy 9999 response."""
|
|
402
420
|
try:
|
|
403
421
|
info = json_loads(XorEncryption.decrypt(data))
|
|
404
422
|
except Exception as ex:
|
|
405
|
-
raise
|
|
423
|
+
raise KasaException(
|
|
406
424
|
f"Unable to read response from device: {config.host}: {ex}"
|
|
407
425
|
) from ex
|
|
408
426
|
|
|
409
427
|
_LOGGER.debug("[DISCOVERY] %s << %s", config.host, info)
|
|
410
428
|
|
|
411
|
-
device_class = Discover._get_device_class(info)
|
|
429
|
+
device_class = cast(Type[IotDevice], Discover._get_device_class(info))
|
|
412
430
|
device = device_class(config.host, config=config)
|
|
413
431
|
sys_info = info["system"]["get_sysinfo"]
|
|
414
432
|
if device_type := sys_info.get("mic_type", sys_info.get("type")):
|
|
@@ -423,13 +441,13 @@ class Discover:
|
|
|
423
441
|
def _get_device_instance(
|
|
424
442
|
data: bytes,
|
|
425
443
|
config: DeviceConfig,
|
|
426
|
-
) ->
|
|
444
|
+
) -> Device:
|
|
427
445
|
"""Get SmartDevice from the new 20002 response."""
|
|
428
446
|
try:
|
|
429
447
|
info = json_loads(data[16:])
|
|
430
448
|
except Exception as ex:
|
|
431
449
|
_LOGGER.debug("Got invalid response from device %s: %s", config.host, data)
|
|
432
|
-
raise
|
|
450
|
+
raise KasaException(
|
|
433
451
|
f"Unable to read response from device: {config.host}: {ex}"
|
|
434
452
|
) from ex
|
|
435
453
|
try:
|
|
@@ -438,7 +456,7 @@ class Discover:
|
|
|
438
456
|
_LOGGER.debug(
|
|
439
457
|
"Unable to parse discovery from device %s: %s", config.host, info
|
|
440
458
|
)
|
|
441
|
-
raise
|
|
459
|
+
raise UnsupportedDeviceError(
|
|
442
460
|
f"Unable to parse discovery from device: {config.host}: {ex}"
|
|
443
461
|
) from ex
|
|
444
462
|
|
|
@@ -450,15 +468,15 @@ class Discover:
|
|
|
450
468
|
discovery_result.mgt_encrypt_schm.encrypt_type,
|
|
451
469
|
discovery_result.mgt_encrypt_schm.lv,
|
|
452
470
|
)
|
|
453
|
-
except
|
|
454
|
-
raise
|
|
471
|
+
except KasaException as ex:
|
|
472
|
+
raise UnsupportedDeviceError(
|
|
455
473
|
f"Unsupported device {config.host} of type {type_} "
|
|
456
474
|
+ f"with encrypt_type {discovery_result.mgt_encrypt_schm.encrypt_type}",
|
|
457
475
|
discovery_result=discovery_result.get_dict(),
|
|
458
476
|
) from ex
|
|
459
477
|
if (device_class := get_device_class_from_family(type_)) is None:
|
|
460
478
|
_LOGGER.warning("Got unsupported device type: %s", type_)
|
|
461
|
-
raise
|
|
479
|
+
raise UnsupportedDeviceError(
|
|
462
480
|
f"Unsupported device {config.host} of type {type_}: {info}",
|
|
463
481
|
discovery_result=discovery_result.get_dict(),
|
|
464
482
|
)
|
|
@@ -466,7 +484,7 @@ class Discover:
|
|
|
466
484
|
_LOGGER.warning(
|
|
467
485
|
"Got unsupported connection type: %s", config.connection_type.to_dict()
|
|
468
486
|
)
|
|
469
|
-
raise
|
|
487
|
+
raise UnsupportedDeviceError(
|
|
470
488
|
f"Unsupported encryption scheme {config.host} of "
|
|
471
489
|
+ f"type {config.connection_type.to_dict()}: {info}",
|
|
472
490
|
discovery_result=discovery_result.get_dict(),
|
|
@@ -481,16 +499,17 @@ class Discover:
|
|
|
481
499
|
return device
|
|
482
500
|
|
|
483
501
|
|
|
484
|
-
class
|
|
485
|
-
"""Base model for discovery result."""
|
|
502
|
+
class EncryptionScheme(BaseModel):
|
|
503
|
+
"""Base model for encryption scheme of discovery result."""
|
|
486
504
|
|
|
487
|
-
|
|
488
|
-
|
|
505
|
+
is_support_https: bool
|
|
506
|
+
encrypt_type: str
|
|
507
|
+
http_port: int
|
|
508
|
+
lv: Optional[int] = None # noqa: UP007
|
|
489
509
|
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
lv: Optional[int] = None
|
|
510
|
+
|
|
511
|
+
class DiscoveryResult(BaseModel):
|
|
512
|
+
"""Base model for discovery result."""
|
|
494
513
|
|
|
495
514
|
device_type: str
|
|
496
515
|
device_model: str
|
|
@@ -499,11 +518,11 @@ class DiscoveryResult(BaseModel):
|
|
|
499
518
|
mgt_encrypt_schm: EncryptionScheme
|
|
500
519
|
device_id: str
|
|
501
520
|
|
|
502
|
-
hw_ver: Optional[str] = None
|
|
503
|
-
owner: Optional[str] = None
|
|
504
|
-
is_support_iot_cloud: Optional[bool] = None
|
|
505
|
-
obd_src: Optional[str] = None
|
|
506
|
-
factory_default: Optional[bool] = None
|
|
521
|
+
hw_ver: Optional[str] = None # noqa: UP007
|
|
522
|
+
owner: Optional[str] = None # noqa: UP007
|
|
523
|
+
is_support_iot_cloud: Optional[bool] = None # noqa: UP007
|
|
524
|
+
obd_src: Optional[str] = None # noqa: UP007
|
|
525
|
+
factory_default: Optional[bool] = None # noqa: UP007
|
|
507
526
|
|
|
508
527
|
def get_dict(self) -> dict:
|
|
509
528
|
"""Return a dict for this discovery result.
|
kasa/emeterstatus.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"""Module for emeter container."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
2
5
|
import logging
|
|
3
|
-
from typing import Optional
|
|
4
6
|
|
|
5
7
|
_LOGGER = logging.getLogger(__name__)
|
|
6
8
|
|
|
@@ -16,7 +18,7 @@ class EmeterStatus(dict):
|
|
|
16
18
|
"""
|
|
17
19
|
|
|
18
20
|
@property
|
|
19
|
-
def voltage(self) ->
|
|
21
|
+
def voltage(self) -> float | None:
|
|
20
22
|
"""Return voltage in V."""
|
|
21
23
|
try:
|
|
22
24
|
return self["voltage"]
|
|
@@ -24,7 +26,7 @@ class EmeterStatus(dict):
|
|
|
24
26
|
return None
|
|
25
27
|
|
|
26
28
|
@property
|
|
27
|
-
def power(self) ->
|
|
29
|
+
def power(self) -> float | None:
|
|
28
30
|
"""Return power in W."""
|
|
29
31
|
try:
|
|
30
32
|
return self["power"]
|
|
@@ -32,7 +34,7 @@ class EmeterStatus(dict):
|
|
|
32
34
|
return None
|
|
33
35
|
|
|
34
36
|
@property
|
|
35
|
-
def current(self) ->
|
|
37
|
+
def current(self) -> float | None:
|
|
36
38
|
"""Return current in A."""
|
|
37
39
|
try:
|
|
38
40
|
return self["current"]
|
|
@@ -40,7 +42,7 @@ class EmeterStatus(dict):
|
|
|
40
42
|
return None
|
|
41
43
|
|
|
42
44
|
@property
|
|
43
|
-
def total(self) ->
|
|
45
|
+
def total(self) -> float | None:
|
|
44
46
|
"""Return total in kWh."""
|
|
45
47
|
try:
|
|
46
48
|
return self["total"]
|
|
@@ -79,8 +81,11 @@ class EmeterStatus(dict):
|
|
|
79
81
|
return super().__getitem__(item[: item.find("_")]) * 1000
|
|
80
82
|
else: # downscale
|
|
81
83
|
for i in super().keys(): # noqa: SIM118
|
|
82
|
-
if
|
|
83
|
-
|
|
84
|
+
if (
|
|
85
|
+
i.startswith(item)
|
|
86
|
+
and (value := self.__getitem__(i)) is not None
|
|
87
|
+
):
|
|
88
|
+
return value / 1000
|
|
84
89
|
|
|
85
90
|
_LOGGER.debug(f"Unable to find value for '{item}'")
|
|
86
91
|
return None
|
kasa/exceptions.py
CHANGED
|
@@ -1,50 +1,68 @@
|
|
|
1
1
|
"""python-kasa exceptions."""
|
|
2
|
-
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from asyncio import TimeoutError as _asyncioTimeoutError
|
|
3
6
|
from enum import IntEnum
|
|
4
|
-
from typing import Any
|
|
7
|
+
from typing import Any
|
|
5
8
|
|
|
6
9
|
|
|
7
|
-
class
|
|
8
|
-
"""Base exception for
|
|
10
|
+
class KasaException(Exception):
|
|
11
|
+
"""Base exception for library errors."""
|
|
9
12
|
|
|
10
|
-
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
11
|
-
self.error_code: Optional["SmartErrorCode"] = kwargs.get("error_code", None)
|
|
12
|
-
super().__init__(*args)
|
|
13
13
|
|
|
14
|
+
class TimeoutError(KasaException, _asyncioTimeoutError):
|
|
15
|
+
"""Timeout exception for device errors."""
|
|
14
16
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
def __repr__(self):
|
|
18
|
+
return KasaException.__repr__(self)
|
|
17
19
|
|
|
18
|
-
def
|
|
19
|
-
|
|
20
|
-
super().__init__(*args, **kwargs)
|
|
20
|
+
def __str__(self):
|
|
21
|
+
return KasaException.__str__(self)
|
|
21
22
|
|
|
22
23
|
|
|
23
|
-
class
|
|
24
|
-
"""
|
|
24
|
+
class _ConnectionError(KasaException):
|
|
25
|
+
"""Connection exception for device errors."""
|
|
25
26
|
|
|
26
27
|
|
|
27
|
-
class
|
|
28
|
-
"""
|
|
28
|
+
class UnsupportedDeviceError(KasaException):
|
|
29
|
+
"""Exception for trying to connect to unsupported devices."""
|
|
29
30
|
|
|
31
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
32
|
+
self.discovery_result = kwargs.get("discovery_result")
|
|
33
|
+
super().__init__(*args)
|
|
30
34
|
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
|
|
36
|
+
class DeviceError(KasaException):
|
|
37
|
+
"""Base exception for device errors."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
40
|
+
self.error_code: SmartErrorCode | None = kwargs.get("error_code", None)
|
|
41
|
+
super().__init__(*args)
|
|
33
42
|
|
|
34
43
|
def __repr__(self):
|
|
35
|
-
|
|
44
|
+
err_code = self.error_code.__repr__() if self.error_code else ""
|
|
45
|
+
return f"{self.__class__.__name__}({err_code})"
|
|
36
46
|
|
|
37
47
|
def __str__(self):
|
|
38
|
-
|
|
48
|
+
err_code = f" (error_code={self.error_code.name})" if self.error_code else ""
|
|
49
|
+
return super().__str__() + err_code
|
|
39
50
|
|
|
40
51
|
|
|
41
|
-
class
|
|
42
|
-
"""
|
|
52
|
+
class AuthenticationError(DeviceError):
|
|
53
|
+
"""Base exception for device authentication errors."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class _RetryableError(DeviceError):
|
|
57
|
+
"""Retryable exception for device errors."""
|
|
43
58
|
|
|
44
59
|
|
|
45
60
|
class SmartErrorCode(IntEnum):
|
|
46
61
|
"""Enum for SMART Error Codes."""
|
|
47
62
|
|
|
63
|
+
def __str__(self):
|
|
64
|
+
return f"{self.name}({self.value})"
|
|
65
|
+
|
|
48
66
|
SUCCESS = 0
|
|
49
67
|
|
|
50
68
|
# Transport Errors
|
|
@@ -106,6 +124,7 @@ SMART_RETRYABLE_ERRORS = [
|
|
|
106
124
|
SmartErrorCode.TRANSPORT_NOT_AVAILABLE_ERROR,
|
|
107
125
|
SmartErrorCode.HTTP_TRANSPORT_FAILED_ERROR,
|
|
108
126
|
SmartErrorCode.UNSPECIFIC_ERROR,
|
|
127
|
+
SmartErrorCode.SESSION_TIMEOUT_ERROR,
|
|
109
128
|
]
|
|
110
129
|
|
|
111
130
|
SMART_AUTHENTICATION_ERRORS = [
|
|
@@ -115,7 +134,3 @@ SMART_AUTHENTICATION_ERRORS = [
|
|
|
115
134
|
SmartErrorCode.HAND_SHAKE_FAILED_ERROR,
|
|
116
135
|
SmartErrorCode.TRANSPORT_UNKNOWN_CREDENTIALS_ERROR,
|
|
117
136
|
]
|
|
118
|
-
|
|
119
|
-
SMART_TIMEOUT_ERRORS = [
|
|
120
|
-
SmartErrorCode.SESSION_TIMEOUT_ERROR,
|
|
121
|
-
]
|