python-kasa 0.6.2.1__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.
Files changed (164) hide show
  1. kasa/__init__.py +88 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +406 -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 +133 -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} +100 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +157 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +42 -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 +221 -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 +139 -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 +115 -85
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +216 -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 +33 -24
  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.dev0.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev0.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.dev0.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.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 SmartDeviceException
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 SmartDeviceException(
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 SmartDeviceException(
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 SmartDeviceException(
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:`SmartDevice.credentials_hash`
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 SmartDeviceException(f"Invalid device config data: {config_dict}")
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, Set, Type, cast
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
- try:
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 TimeoutException, UnsupportedDeviceException
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[[SmartDevice], Awaitable[None]]
35
- DeviceDict = Dict[str, SmartDevice]
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: Optional[OnDiscoveredCallable] = None,
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: Optional[str] = None,
54
- on_unsupported: Optional[
55
- Callable[[UnsupportedDeviceException], Awaitable[None]]
56
- ] = None,
57
- port: Optional[int] = None,
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: Dict = {}
75
- self.invalid_device_exceptions: Dict = {}
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: Set[str] = set()
82
- self.discover_task: Optional[asyncio.Task] = None
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 i in range(self.discovery_packets):
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
- if i < self.discovery_packets - 1:
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 UnsupportedDeviceException as udex:
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
- asyncio.ensure_future(self.on_unsupported(udex))
167
+ self._run_callback_task(self.on_unsupported(udex))
144
168
  self._handle_discovered_event()
145
169
  return
146
- except SmartDeviceException as ex:
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
- asyncio.ensure_future(self.on_discovered(device))
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 discovered_event is available set it and cancel discover_task."""
161
- if self.discovered_event is not None:
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:`SmartDevice`-derived object as parameter.
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:`SmartDevice`-derived objects keyed with IP addresses.
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 asyncio.sleep(discovery_timeout)
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: Optional[int] = None,
301
- timeout: Optional[int] = None,
302
- credentials: Optional[Credentials] = None,
303
- ) -> SmartDevice:
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:`SmartDevice.connect()` instead as it should perform better when
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 SmartDeviceException(
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 SmartDeviceException(f"Unable to get discovery response for {host}")
400
+ raise TimeoutError(f"Timed out getting discovery response for {host}")
383
401
 
384
402
  @staticmethod
385
- def _get_device_class(info: dict) -> Type[SmartDevice]:
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 UnsupportedDeviceException(
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) -> SmartDevice:
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 SmartDeviceException(
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
- ) -> SmartDevice:
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 SmartDeviceException(
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 UnsupportedDeviceException(
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 SmartDeviceException as ex:
454
- raise UnsupportedDeviceException(
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 UnsupportedDeviceException(
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 UnsupportedDeviceException(
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 DiscoveryResult(BaseModel):
485
- """Base model for discovery result."""
502
+ class EncryptionScheme(BaseModel):
503
+ """Base model for encryption scheme of discovery result."""
486
504
 
487
- class EncryptionScheme(BaseModel):
488
- """Base model for encryption scheme of discovery result."""
505
+ is_support_https: bool
506
+ encrypt_type: str
507
+ http_port: int
508
+ lv: Optional[int] = None # noqa: UP007
489
509
 
490
- is_support_https: bool
491
- encrypt_type: str
492
- http_port: int
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) -> Optional[float]:
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) -> Optional[float]:
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) -> Optional[float]:
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) -> Optional[float]:
45
+ def total(self) -> float | None:
44
46
  """Return total in kWh."""
45
47
  try:
46
48
  return self["total"]
kasa/exceptions.py CHANGED
@@ -1,50 +1,68 @@
1
1
  """python-kasa exceptions."""
2
- from asyncio import TimeoutError
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, Optional
7
+ from typing import Any
5
8
 
6
9
 
7
- class SmartDeviceException(Exception):
8
- """Base exception for device errors."""
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
- class UnsupportedDeviceException(SmartDeviceException):
16
- """Exception for trying to connect to unsupported devices."""
17
+ def __repr__(self):
18
+ return KasaException.__repr__(self)
17
19
 
18
- def __init__(self, *args: Any, **kwargs: Any) -> None:
19
- self.discovery_result = kwargs.get("discovery_result")
20
- super().__init__(*args, **kwargs)
20
+ def __str__(self):
21
+ return KasaException.__str__(self)
21
22
 
22
23
 
23
- class AuthenticationException(SmartDeviceException):
24
- """Base exception for device authentication errors."""
24
+ class _ConnectionError(KasaException):
25
+ """Connection exception for device errors."""
25
26
 
26
27
 
27
- class RetryableException(SmartDeviceException):
28
- """Retryable exception for device errors."""
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
- class TimeoutException(SmartDeviceException, TimeoutError):
32
- """Timeout exception for device errors."""
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
- return SmartDeviceException.__repr__(self)
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
- return SmartDeviceException.__str__(self)
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 ConnectionException(SmartDeviceException):
42
- """Connection exception for device errors."""
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
- ]