python-kasa 0.7.0.dev1__py3-none-any.whl → 0.7.0.dev2__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 (42) hide show
  1. kasa/__init__.py +16 -9
  2. kasa/aestransport.py +0 -3
  3. kasa/cli.py +12 -10
  4. kasa/device.py +26 -3
  5. kasa/deviceconfig.py +45 -20
  6. kasa/discover.py +106 -46
  7. kasa/feature.py +2 -1
  8. kasa/httpclient.py +24 -0
  9. kasa/iot/iotdevice.py +1 -1
  10. kasa/iot/iotlightstrip.py +3 -2
  11. kasa/iot/iotplug.py +1 -1
  12. kasa/iot/iotstrip.py +1 -1
  13. kasa/iot/modules/lightpreset.py +6 -1
  14. kasa/smart/modules/autooff.py +13 -8
  15. kasa/smartprotocol.py +3 -1
  16. kasa/tests/device_fixtures.py +10 -1
  17. kasa/tests/discovery_fixtures.py +82 -29
  18. kasa/tests/fakeprotocol_iot.py +30 -7
  19. kasa/tests/fixtures/HS110(EU)_1.0_1.2.5.json +1 -1
  20. kasa/tests/fixtures/HS110(US)_1.0_1.2.6.json +37 -0
  21. kasa/tests/fixtures/HS220(US)_1.0_1.5.7.json +1 -1
  22. kasa/tests/fixtures/HS220(US)_2.0_1.0.3.json +1 -1
  23. kasa/tests/fixtures/HS300(US)_1.0_1.0.21.json +89 -0
  24. kasa/tests/fixtures/KL120(US)_1.0_1.8.11.json +85 -0
  25. kasa/tests/fixtures/KL430(US)_1.0_1.0.10.json +51 -12
  26. kasa/tests/fixtures/KP303(UK)_1.0_1.0.3.json +1 -1
  27. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +1 -1
  28. kasa/tests/fixtures/smart/P115(EU)_1.0_1.2.3.json +386 -0
  29. kasa/tests/fixtures/smart/S505D(US)_1.0_1.1.0.json +262 -0
  30. kasa/tests/smart/modules/test_autooff.py +103 -0
  31. kasa/tests/test_aestransport.py +78 -2
  32. kasa/tests/test_bulb.py +9 -4
  33. kasa/tests/test_device.py +28 -6
  34. kasa/tests/test_device_factory.py +8 -8
  35. kasa/tests/test_discovery.py +61 -4
  36. kasa/tests/test_readme_examples.py +37 -22
  37. kasa/tests/test_smartprotocol.py +3 -2
  38. {python_kasa-0.7.0.dev1.dist-info → python_kasa-0.7.0.dev2.dist-info}/METADATA +4 -4
  39. {python_kasa-0.7.0.dev1.dist-info → python_kasa-0.7.0.dev2.dist-info}/RECORD +42 -36
  40. {python_kasa-0.7.0.dev1.dist-info → python_kasa-0.7.0.dev2.dist-info}/LICENSE +0 -0
  41. {python_kasa-0.7.0.dev1.dist-info → python_kasa-0.7.0.dev2.dist-info}/WHEEL +0 -0
  42. {python_kasa-0.7.0.dev1.dist-info → python_kasa-0.7.0.dev2.dist-info}/entry_points.txt +0 -0
kasa/__init__.py CHANGED
@@ -20,10 +20,10 @@ from kasa.credentials import Credentials
20
20
  from kasa.device import Device
21
21
  from kasa.device_type import DeviceType
22
22
  from kasa.deviceconfig import (
23
- ConnectionType,
24
23
  DeviceConfig,
25
- DeviceFamilyType,
26
- EncryptType,
24
+ DeviceConnectionParameters,
25
+ DeviceEncryptionType,
26
+ DeviceFamily,
27
27
  )
28
28
  from kasa.discover import Discover
29
29
  from kasa.emeterstatus import EmeterStatus
@@ -71,9 +71,9 @@ __all__ = [
71
71
  "TimeoutError",
72
72
  "Credentials",
73
73
  "DeviceConfig",
74
- "ConnectionType",
75
- "EncryptType",
76
- "DeviceFamilyType",
74
+ "DeviceConnectionParameters",
75
+ "DeviceEncryptionType",
76
+ "DeviceFamily",
77
77
  ]
78
78
 
79
79
  from . import iot
@@ -89,11 +89,14 @@ deprecated_smart_devices = {
89
89
  "SmartDimmer": iot.IotDimmer,
90
90
  "SmartBulbPreset": IotLightPreset,
91
91
  }
92
- deprecated_exceptions = {
92
+ deprecated_classes = {
93
93
  "SmartDeviceException": KasaException,
94
94
  "UnsupportedDeviceException": UnsupportedDeviceError,
95
95
  "AuthenticationException": AuthenticationError,
96
96
  "TimeoutException": TimeoutError,
97
+ "ConnectionType": DeviceConnectionParameters,
98
+ "EncryptType": DeviceEncryptionType,
99
+ "DeviceFamilyType": DeviceFamily,
97
100
  }
98
101
 
99
102
 
@@ -112,8 +115,8 @@ def __getattr__(name):
112
115
  stacklevel=1,
113
116
  )
114
117
  return new_class
115
- if name in deprecated_exceptions:
116
- new_class = deprecated_exceptions[name]
118
+ if name in deprecated_classes:
119
+ new_class = deprecated_classes[name]
117
120
  msg = f"{name} is deprecated, use {new_class.__name__} instead"
118
121
  warn(msg, DeprecationWarning, stacklevel=1)
119
122
  return new_class
@@ -133,6 +136,10 @@ if TYPE_CHECKING:
133
136
  UnsupportedDeviceException = UnsupportedDeviceError
134
137
  AuthenticationException = AuthenticationError
135
138
  TimeoutException = TimeoutError
139
+ ConnectionType = DeviceConnectionParameters
140
+ EncryptType = DeviceEncryptionType
141
+ DeviceFamilyType = DeviceFamily
142
+
136
143
  # Instanstiate all classes so the type checkers catch abstract issues
137
144
  from . import smart
138
145
 
kasa/aestransport.py CHANGED
@@ -6,7 +6,6 @@ under compatible GNU GPL3 license.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
- import asyncio
10
9
  import base64
11
10
  import hashlib
12
11
  import logging
@@ -74,7 +73,6 @@ class AesTransport(BaseTransport):
74
73
  }
75
74
  CONTENT_LENGTH = "Content-Length"
76
75
  KEY_PAIR_CONTENT_LENGTH = 314
77
- BACKOFF_SECONDS_AFTER_LOGIN_ERROR = 1
78
76
 
79
77
  def __init__(
80
78
  self,
@@ -216,7 +214,6 @@ class AesTransport(BaseTransport):
216
214
  self._default_credentials = get_default_credentials(
217
215
  DEFAULT_CREDENTIALS["TAPO"]
218
216
  )
219
- await asyncio.sleep(self.BACKOFF_SECONDS_AFTER_LOGIN_ERROR)
220
217
  await self.perform_handshake()
221
218
  await self.try_login(self._get_login_params(self._default_credentials))
222
219
  _LOGGER.debug(
kasa/cli.py CHANGED
@@ -18,13 +18,13 @@ from pydantic.v1 import ValidationError
18
18
 
19
19
  from kasa import (
20
20
  AuthenticationError,
21
- ConnectionType,
22
21
  Credentials,
23
22
  Device,
24
23
  DeviceConfig,
25
- DeviceFamilyType,
24
+ DeviceConnectionParameters,
25
+ DeviceEncryptionType,
26
+ DeviceFamily,
26
27
  Discover,
27
- EncryptType,
28
28
  Feature,
29
29
  KasaException,
30
30
  Module,
@@ -87,11 +87,9 @@ TYPE_TO_CLASS = {
87
87
  "smart.bulb": SmartDevice,
88
88
  }
89
89
 
90
- ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in EncryptType]
90
+ ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in DeviceEncryptionType]
91
91
 
92
- DEVICE_FAMILY_TYPES = [
93
- device_family_type.value for device_family_type in DeviceFamilyType
94
- ]
92
+ DEVICE_FAMILY_TYPES = [device_family_type.value for device_family_type in DeviceFamily]
95
93
 
96
94
  # Block list of commands which require no update
97
95
  SKIP_UPDATE_COMMANDS = ["wifi", "raw-command", "command"]
@@ -111,6 +109,10 @@ def CatchAllExceptions(cls):
111
109
  def _handle_exception(debug, exc):
112
110
  if isinstance(exc, click.ClickException):
113
111
  raise
112
+ # Handle exit request from click.
113
+ if isinstance(exc, click.exceptions.Exit):
114
+ sys.exit(exc.exit_code)
115
+
114
116
  echo(f"Raised error: {exc}")
115
117
  if debug:
116
118
  raise
@@ -370,9 +372,9 @@ async def cli(
370
372
  if type is not None:
371
373
  dev = TYPE_TO_CLASS[type](host)
372
374
  elif device_family and encrypt_type:
373
- ctype = ConnectionType(
374
- DeviceFamilyType(device_family),
375
- EncryptType(encrypt_type),
375
+ ctype = DeviceConnectionParameters(
376
+ DeviceFamily(device_family),
377
+ DeviceEncryptionType(encrypt_type),
376
378
  login_version,
377
379
  )
378
380
  config = DeviceConfig(
kasa/device.py CHANGED
@@ -9,9 +9,16 @@ from datetime import datetime
9
9
  from typing import TYPE_CHECKING, Any, Mapping, Sequence
10
10
  from warnings import warn
11
11
 
12
- from .credentials import Credentials
12
+ from typing_extensions import TypeAlias
13
+
14
+ from .credentials import Credentials as _Credentials
13
15
  from .device_type import DeviceType
14
- from .deviceconfig import DeviceConfig
16
+ from .deviceconfig import (
17
+ DeviceConfig,
18
+ DeviceConnectionParameters,
19
+ DeviceEncryptionType,
20
+ DeviceFamily,
21
+ )
15
22
  from .emeterstatus import EmeterStatus
16
23
  from .exceptions import KasaException
17
24
  from .feature import Feature
@@ -51,6 +58,22 @@ class Device(ABC):
51
58
  or :func:`Discover.discover_single()`.
52
59
  """
53
60
 
61
+ # All types required to create devices directly via connect are aliased here
62
+ # to avoid consumers having to do multiple imports.
63
+
64
+ #: The type of device
65
+ Type: TypeAlias = DeviceType
66
+ #: The credentials for authentication
67
+ Credentials: TypeAlias = _Credentials
68
+ #: Configuration for connecting to the device
69
+ Config: TypeAlias = DeviceConfig
70
+ #: The family of the device, e.g. SMART.KASASWITCH.
71
+ Family: TypeAlias = DeviceFamily
72
+ #: The encryption for the device, e.g. Klap or Aes
73
+ EncryptionType: TypeAlias = DeviceEncryptionType
74
+ #: The connection type for the device.
75
+ ConnectionParameters: TypeAlias = DeviceConnectionParameters
76
+
54
77
  def __init__(
55
78
  self,
56
79
  host: str,
@@ -166,7 +189,7 @@ class Device(ABC):
166
189
  return self.protocol._transport._port
167
190
 
168
191
  @property
169
- def credentials(self) -> Credentials | None:
192
+ def credentials(self) -> _Credentials | None:
170
193
  """The device credentials."""
171
194
  return self.protocol._transport._credentials
172
195
 
kasa/deviceconfig.py CHANGED
@@ -1,10 +1,35 @@
1
- """Module for holding connection parameters.
1
+ """Configuration for connecting directly to a device without discovery.
2
+
3
+ If you are connecting to a newer KASA or TAPO device you can get the device
4
+ via discovery or connect directly with :class:`DeviceConfig`.
5
+
6
+ Discovery returns a list of discovered devices:
7
+
8
+ >>> from kasa import Discover, Device
9
+ >>> device = await Discover.discover_single(
10
+ >>> "127.0.0.3",
11
+ >>> username="user@example.com",
12
+ >>> password="great_password",
13
+ >>> )
14
+ >>> print(device.alias) # Alias is None because update() has not been called
15
+ None
16
+
17
+ >>> config_dict = device.config.to_dict()
18
+ >>> # DeviceConfig.to_dict() can be used to store for later
19
+ >>> print(config_dict)
20
+ {'host': '127.0.0.3', 'timeout': 5, 'credentials': Credentials(), 'connection_type'\
21
+ : {'device_family': 'SMART.TAPOBULB', 'encryption_type': 'KLAP', 'login_version': 2},\
22
+ 'uses_http': True}
23
+
24
+ >>> later_device = await Device.connect(config=Device.Config.from_dict(config_dict))
25
+ >>> print(later_device.alias) # Alias is available as connect() calls update()
26
+ Living Room Bulb
2
27
 
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
28
  """
7
29
 
30
+ # Note that this module does not work with from __future__ import annotations
31
+ # due to it's use of type returned by fields() which becomes a string with the import.
32
+ # https://bugs.python.org/issue39442
8
33
  # ruff: noqa: FA100
9
34
  import logging
10
35
  from dataclasses import asdict, dataclass, field, fields, is_dataclass
@@ -20,7 +45,7 @@ if TYPE_CHECKING:
20
45
  _LOGGER = logging.getLogger(__name__)
21
46
 
22
47
 
23
- class EncryptType(Enum):
48
+ class DeviceEncryptionType(Enum):
24
49
  """Encrypt type enum."""
25
50
 
26
51
  Klap = "KLAP"
@@ -28,7 +53,7 @@ class EncryptType(Enum):
28
53
  Xor = "XOR"
29
54
 
30
55
 
31
- class DeviceFamilyType(Enum):
56
+ class DeviceFamily(Enum):
32
57
  """Encrypt type enum."""
33
58
 
34
59
  IotSmartPlugSwitch = "IOT.SMARTPLUGSWITCH"
@@ -80,11 +105,11 @@ def _dataclass_to_dict(in_val):
80
105
 
81
106
 
82
107
  @dataclass
83
- class ConnectionType:
108
+ class DeviceConnectionParameters:
84
109
  """Class to hold the the parameters determining connection type."""
85
110
 
86
- device_family: DeviceFamilyType
87
- encryption_type: EncryptType
111
+ device_family: DeviceFamily
112
+ encryption_type: DeviceEncryptionType
88
113
  login_version: Optional[int] = None
89
114
 
90
115
  @staticmethod
@@ -92,12 +117,12 @@ class ConnectionType:
92
117
  device_family: str,
93
118
  encryption_type: str,
94
119
  login_version: Optional[int] = None,
95
- ) -> "ConnectionType":
120
+ ) -> "DeviceConnectionParameters":
96
121
  """Return connection parameters from string values."""
97
122
  try:
98
- return ConnectionType(
99
- DeviceFamilyType(device_family),
100
- EncryptType(encryption_type),
123
+ return DeviceConnectionParameters(
124
+ DeviceFamily(device_family),
125
+ DeviceEncryptionType(encryption_type),
101
126
  login_version,
102
127
  )
103
128
  except (ValueError, TypeError) as ex:
@@ -107,7 +132,7 @@ class ConnectionType:
107
132
  ) from ex
108
133
 
109
134
  @staticmethod
110
- def from_dict(connection_type_dict: Dict[str, str]) -> "ConnectionType":
135
+ def from_dict(connection_type_dict: Dict[str, str]) -> "DeviceConnectionParameters":
111
136
  """Return connection parameters from dict."""
112
137
  if (
113
138
  isinstance(connection_type_dict, dict)
@@ -116,7 +141,7 @@ class ConnectionType:
116
141
  ):
117
142
  if login_version := connection_type_dict.get("login_version"):
118
143
  login_version = int(login_version) # type: ignore[assignment]
119
- return ConnectionType.from_values(
144
+ return DeviceConnectionParameters.from_values(
120
145
  device_family,
121
146
  encryption_type,
122
147
  login_version, # type: ignore[arg-type]
@@ -155,9 +180,9 @@ class DeviceConfig:
155
180
  #: The protocol specific type of connection. Defaults to the legacy type.
156
181
  batch_size: Optional[int] = None
157
182
  #: The batch size for protoools supporting multiple request batches.
158
- connection_type: ConnectionType = field(
159
- default_factory=lambda: ConnectionType(
160
- DeviceFamilyType.IotSmartPlugSwitch, EncryptType.Xor, 1
183
+ connection_type: DeviceConnectionParameters = field(
184
+ default_factory=lambda: DeviceConnectionParameters(
185
+ DeviceFamily.IotSmartPlugSwitch, DeviceEncryptionType.Xor, 1
161
186
  )
162
187
  )
163
188
  #: True if the device uses http. Consumers should retrieve rather than set this
@@ -170,8 +195,8 @@ class DeviceConfig:
170
195
 
171
196
  def __post_init__(self):
172
197
  if self.connection_type is None:
173
- self.connection_type = ConnectionType(
174
- DeviceFamilyType.IotSmartPlugSwitch, EncryptType.Xor
198
+ self.connection_type = DeviceConnectionParameters(
199
+ DeviceFamily.IotSmartPlugSwitch, DeviceEncryptionType.Xor
175
200
  )
176
201
 
177
202
  def to_dict(
kasa/discover.py CHANGED
@@ -1,4 +1,83 @@
1
- """Discovery module for TP-Link Smart Home devices."""
1
+ """Discover TPLink Smart Home devices.
2
+
3
+ The main entry point for this library is :func:`Discover.discover()`,
4
+ which returns a dictionary of the found devices. The key is the IP address
5
+ of the device and the value contains ready-to-use, SmartDevice-derived
6
+ device object.
7
+
8
+ :func:`discover_single()` can be used to initialize a single device given its
9
+ IP address. If the :class:`DeviceConfig` of the device is already known,
10
+ you can initialize the corresponding device class directly without discovery.
11
+
12
+ The protocol uses UDP broadcast datagrams on port 9999 and 20002 for discovery.
13
+ Legacy devices support discovery on port 9999 and newer devices on 20002.
14
+
15
+ Newer devices that respond on port 20002 will most likely require TP-Link cloud
16
+ credentials to be passed if queries or updates are to be performed on the returned
17
+ devices.
18
+
19
+ Discovery returns a dict of {ip: discovered devices}:
20
+
21
+ >>> from kasa import Discover, Credentials
22
+ >>>
23
+ >>> found_devices = await Discover.discover()
24
+ >>> [dev.model for dev in found_devices.values()]
25
+ ['KP303(UK)', 'HS110(EU)', 'L530E', 'KL430(US)', 'HS220(US)']
26
+
27
+ You can pass username and password for devices requiring authentication
28
+
29
+ >>> devices = await Discover.discover(
30
+ >>> username="user@example.com",
31
+ >>> password="great_password",
32
+ >>> )
33
+ >>> print(len(devices))
34
+ 5
35
+
36
+ You can also pass a :class:`kasa.Credentials`
37
+
38
+ >>> creds = Credentials("user@example.com", "great_password")
39
+ >>> devices = await Discover.discover(credentials=creds)
40
+ >>> print(len(devices))
41
+ 5
42
+
43
+ Discovery can also be targeted to a specific broadcast address instead of
44
+ the default 255.255.255.255:
45
+
46
+ >>> found_devices = await Discover.discover(target="127.0.0.255", credentials=creds)
47
+ >>> print(len(found_devices))
48
+ 5
49
+
50
+ Basic information is available on the device from the discovery broadcast response
51
+ but it is important to call device.update() after discovery if you want to access
52
+ all the attributes without getting errors or None.
53
+
54
+ >>> dev = found_devices["127.0.0.3"]
55
+ >>> dev.alias
56
+ None
57
+ >>> await dev.update()
58
+ >>> dev.alias
59
+ 'Living Room Bulb'
60
+
61
+ It is also possible to pass a coroutine to be executed for each found device:
62
+
63
+ >>> async def print_dev_info(dev):
64
+ >>> await dev.update()
65
+ >>> print(f"Discovered {dev.alias} (model: {dev.model})")
66
+ >>>
67
+ >>> devices = await Discover.discover(on_discovered=print_dev_info, credentials=creds)
68
+ Discovered Bedroom Power Strip (model: KP303(UK))
69
+ Discovered Bedroom Lamp Plug (model: HS110(EU))
70
+ Discovered Living Room Bulb (model: L530)
71
+ Discovered Bedroom Lightstrip (model: KL430(US))
72
+ Discovered Living Room Dimmer Switch (model: HS220(US))
73
+
74
+ Discovering a single device returns a kasa.Device object.
75
+
76
+ >>> device = await Discover.discover_single("127.0.0.1", credentials=creds)
77
+ >>> device.model
78
+ 'KP303(UK)'
79
+
80
+ """
2
81
 
3
82
  from __future__ import annotations
4
83
 
@@ -21,7 +100,11 @@ from kasa.device_factory import (
21
100
  get_device_class_from_sys_info,
22
101
  get_protocol,
23
102
  )
24
- from kasa.deviceconfig import ConnectionType, DeviceConfig, EncryptType
103
+ from kasa.deviceconfig import (
104
+ DeviceConfig,
105
+ DeviceConnectionParameters,
106
+ DeviceEncryptionType,
107
+ )
25
108
  from kasa.exceptions import (
26
109
  KasaException,
27
110
  TimeoutError,
@@ -198,45 +281,7 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
198
281
 
199
282
 
200
283
  class Discover:
201
- """Discover TPLink Smart Home devices.
202
-
203
- The main entry point for this library is :func:`Discover.discover()`,
204
- which returns a dictionary of the found devices. The key is the IP address
205
- of the device and the value contains ready-to-use, SmartDevice-derived
206
- device object.
207
-
208
- :func:`discover_single()` can be used to initialize a single device given its
209
- IP address. If the :class:`DeviceConfig` of the device is already known,
210
- you can initialize the corresponding device class directly without discovery.
211
-
212
- The protocol uses UDP broadcast datagrams on port 9999 and 20002 for discovery.
213
- Legacy devices support discovery on port 9999 and newer devices on 20002.
214
-
215
- Newer devices that respond on port 20002 will most likely require TP-Link cloud
216
- credentials to be passed if queries or updates are to be performed on the returned
217
- devices.
218
-
219
- Examples:
220
- Discovery returns a list of discovered devices:
221
-
222
- >>> import asyncio
223
- >>> found_devices = asyncio.run(Discover.discover())
224
- >>> [dev.alias for dev in found_devices]
225
- ['TP-LINK_Power Strip_CF69']
226
-
227
- Discovery can also be targeted to a specific broadcast address instead of
228
- the default 255.255.255.255:
229
-
230
- >>> asyncio.run(Discover.discover(target="192.168.8.255"))
231
-
232
- It is also possible to pass a coroutine to be executed for each found device:
233
-
234
- >>> async def print_alias(dev):
235
- >>> print(f"Discovered {dev.alias}")
236
- >>> devices = asyncio.run(Discover.discover(on_discovered=print_alias))
237
-
238
-
239
- """
284
+ """Class for discovering devices."""
240
285
 
241
286
  DISCOVERY_PORT = 9999
242
287
 
@@ -257,6 +302,8 @@ class Discover:
257
302
  interface=None,
258
303
  on_unsupported=None,
259
304
  credentials=None,
305
+ username: str | None = None,
306
+ password: str | None = None,
260
307
  port=None,
261
308
  timeout=None,
262
309
  ) -> DeviceDict:
@@ -284,11 +331,16 @@ class Discover:
284
331
  :param discovery_packets: Number of discovery packets to broadcast
285
332
  :param interface: Bind to specific interface
286
333
  :param on_unsupported: Optional callback when unsupported devices are discovered
287
- :param credentials: Credentials for devices requiring authentication
334
+ :param credentials: Credentials for devices that require authentication.
335
+ username and password are ignored if provided.
336
+ :param username: Username for devices that require authentication
337
+ :param password: Password for devices that require authentication
288
338
  :param port: Override the discovery port for devices listening on 9999
289
339
  :param timeout: Query timeout in seconds for devices returned by discovery
290
340
  :return: dictionary with discovered devices
291
341
  """
342
+ if not credentials and username and password:
343
+ credentials = Credentials(username, password)
292
344
  loop = asyncio.get_event_loop()
293
345
  transport, protocol = await loop.create_datagram_endpoint(
294
346
  lambda: _DiscoverProtocol(
@@ -328,6 +380,8 @@ class Discover:
328
380
  port: int | None = None,
329
381
  timeout: int | None = None,
330
382
  credentials: Credentials | None = None,
383
+ username: str | None = None,
384
+ password: str | None = None,
331
385
  ) -> Device:
332
386
  """Discover a single device by the given IP address.
333
387
 
@@ -340,10 +394,15 @@ class Discover:
340
394
  :param discovery_timeout: Timeout in seconds for discovery
341
395
  :param port: Optionally set a different port for legacy devices using port 9999
342
396
  :param timeout: Timeout in seconds device for devices queries
343
- :param credentials: Credentials for devices that require authentication
397
+ :param credentials: Credentials for devices that require authentication.
398
+ username and password are ignored if provided.
399
+ :param username: Username for devices that require authentication
400
+ :param password: Password for devices that require authentication
344
401
  :rtype: SmartDevice
345
402
  :return: Object for querying/controlling found device.
346
403
  """
404
+ if not credentials and username and password:
405
+ credentials = Credentials(username, password)
347
406
  loop = asyncio.get_event_loop()
348
407
 
349
408
  try:
@@ -430,8 +489,9 @@ class Discover:
430
489
  device = device_class(config.host, config=config)
431
490
  sys_info = info["system"]["get_sysinfo"]
432
491
  if device_type := sys_info.get("mic_type", sys_info.get("type")):
433
- config.connection_type = ConnectionType.from_values(
434
- device_family=device_type, encryption_type=EncryptType.Xor.value
492
+ config.connection_type = DeviceConnectionParameters.from_values(
493
+ device_family=device_type,
494
+ encryption_type=DeviceEncryptionType.Xor.value,
435
495
  )
436
496
  device.protocol = get_protocol(config) # type: ignore[assignment]
437
497
  device.update_from_discover_info(info)
@@ -463,7 +523,7 @@ class Discover:
463
523
  type_ = discovery_result.device_type
464
524
 
465
525
  try:
466
- config.connection_type = ConnectionType.from_values(
526
+ config.connection_type = DeviceConnectionParameters.from_values(
467
527
  type_,
468
528
  discovery_result.mgt_encrypt_schm.encrypt_type,
469
529
  discovery_result.mgt_encrypt_schm.lv,
kasa/feature.py CHANGED
@@ -30,7 +30,8 @@ class Feature:
30
30
  #: Action triggers some action on device
31
31
  Action = auto()
32
32
  #: Number defines a numeric setting
33
- #: See :ref:`range_getter`, :ref:`minimum_value`, and :ref:`maximum_value`
33
+ #: See :attr:`range_getter`, :attr:`Feature.minimum_value`,
34
+ #: and :attr:`maximum_value`
34
35
  Number = auto()
35
36
  #: Choice defines a setting with pre-defined values
36
37
  Choice = auto()
kasa/httpclient.py CHANGED
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import asyncio
6
6
  import logging
7
+ import time
7
8
  from typing import Any, Dict
8
9
 
9
10
  import aiohttp
@@ -28,12 +29,20 @@ def get_cookie_jar() -> aiohttp.CookieJar:
28
29
  class HttpClient:
29
30
  """HttpClient Class."""
30
31
 
32
+ # Some devices (only P100 so far) close the http connection after each request
33
+ # and aiohttp doesn't seem to handle it. If a Client OS error is received the
34
+ # http client will start ensuring that sequential requests have a wait delay.
35
+ WAIT_BETWEEN_REQUESTS_ON_OSERROR = 0.25
36
+
31
37
  def __init__(self, config: DeviceConfig) -> None:
32
38
  self._config = config
33
39
  self._client_session: aiohttp.ClientSession = None
34
40
  self._jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False)
35
41
  self._last_url = URL(f"http://{self._config.host}/")
36
42
 
43
+ self._wait_between_requests = 0.0
44
+ self._last_request_time = 0.0
45
+
37
46
  @property
38
47
  def client(self) -> aiohttp.ClientSession:
39
48
  """Return the underlying http client."""
@@ -60,6 +69,14 @@ class HttpClient:
60
69
 
61
70
  If the request is provided via the json parameter json will be returned.
62
71
  """
72
+ # Once we know a device needs a wait between sequential queries always wait
73
+ # first rather than keep erroring then waiting.
74
+ if self._wait_between_requests:
75
+ now = time.time()
76
+ gap = now - self._last_request_time
77
+ if gap < self._wait_between_requests:
78
+ await asyncio.sleep(self._wait_between_requests - gap)
79
+
63
80
  _LOGGER.debug("Posting to %s", url)
64
81
  response_data = None
65
82
  self._last_url = url
@@ -89,6 +106,9 @@ class HttpClient:
89
106
  response_data = json_loads(response_data.decode())
90
107
 
91
108
  except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError) as ex:
109
+ if isinstance(ex, aiohttp.ClientOSError):
110
+ self._wait_between_requests = self.WAIT_BETWEEN_REQUESTS_ON_OSERROR
111
+ self._last_request_time = time.time()
92
112
  raise _ConnectionError(
93
113
  f"Device connection error: {self._config.host}: {ex}", ex
94
114
  ) from ex
@@ -103,6 +123,10 @@ class HttpClient:
103
123
  f"Unable to query the device: {self._config.host}: {ex}", ex
104
124
  ) from ex
105
125
 
126
+ # For performance only request system time if waiting is enabled
127
+ if self._wait_between_requests:
128
+ self._last_request_time = time.time()
129
+
106
130
  return resp.status, response_data
107
131
 
108
132
  def get_cookie(self, cookie_name: str) -> str | None:
kasa/iot/iotdevice.py CHANGED
@@ -105,7 +105,7 @@ class IotDevice(Device):
105
105
  All devices provide several informational properties:
106
106
 
107
107
  >>> dev.alias
108
- Kitchen
108
+ Bedroom Lamp Plug
109
109
  >>> dev.model
110
110
  HS110(EU)
111
111
  >>> dev.rssi
kasa/iot/iotlightstrip.py CHANGED
@@ -23,7 +23,7 @@ class IotLightStrip(IotBulb):
23
23
  >>> strip = IotLightStrip("127.0.0.1")
24
24
  >>> asyncio.run(strip.update())
25
25
  >>> print(strip.alias)
26
- KL430 pantry lightstrip
26
+ Bedroom Lightstrip
27
27
 
28
28
  Getting the length of the strip:
29
29
 
@@ -33,7 +33,8 @@ class IotLightStrip(IotBulb):
33
33
  Currently active effect:
34
34
 
35
35
  >>> strip.effect
36
- {'brightness': 50, 'custom': 0, 'enable': 0, 'id': '', 'name': ''}
36
+ {'brightness': 100, 'custom': 0, 'enable': 0,
37
+ 'id': 'bCTItKETDFfrKANolgldxfgOakaarARs', 'name': 'Flicker'}
37
38
 
38
39
  .. note::
39
40
  The device supports some features that are not currently implemented,
kasa/iot/iotplug.py CHANGED
@@ -32,7 +32,7 @@ class IotPlug(IotDevice):
32
32
  >>> plug = IotPlug("127.0.0.1")
33
33
  >>> asyncio.run(plug.update())
34
34
  >>> plug.alias
35
- Kitchen
35
+ Bedroom Lamp Plug
36
36
 
37
37
  Setting the LED state:
38
38
 
kasa/iot/iotstrip.py CHANGED
@@ -55,7 +55,7 @@ class IotStrip(IotDevice):
55
55
  >>> strip = IotStrip("127.0.0.1")
56
56
  >>> asyncio.run(strip.update())
57
57
  >>> strip.alias
58
- TP-LINK_Power Strip_CF69
58
+ Bedroom Power Strip
59
59
 
60
60
  All methods act on the whole strip:
61
61