8000 Further update post review · python-kasa/python-kasa@d931ed4 · GitHub
[go: up one dir, main page]

Skip to content

Commit d931ed4

Browse files
committed
Further update post review
1 parent ce7a89b commit d931ed4

21 files changed

+130
-95
lines changed

kasa/aestransport.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ class AesTransport(BaseTransport):
4747
protocol, sometimes used by newer firmware versions on kasa devices.
4848
"""
4949

50-
DEFAULT_PORT = 80
50+
DEFAULT_PORT: int = 80
5151
SESSION_COOKIE_NAME = "TP_SESSIONID"
5252
COMMON_HEADERS = {
5353
"Content-Type": "application/json",
@@ -61,7 +61,6 @@ def __init__(
6161
config: DeviceConfig,
6262
) -> None:
6363
super().__init__(config=config)
64-
self._port = config.port or self.DEFAULT_PORT
6564

6665
self._default_http_client: Optional[httpx.AsyncClient] = None
6766

@@ -76,6 +75,11 @@ def __init__(
7675

7776
_LOGGER.debug("Created AES transport for %s", self._host)
7877

78+
@property
79+
def default_port(self):
80+
"""Default port for the transport."""
81+
return self.DEFAULT_PORT
82+
7983
@property
8084
def _http_client(self) -> httpx.AsyncClient:
8185
if self._config.http_client:

kasa/cli.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ def wrapper(message=None, *args, **kwargs):
6565

6666
ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in EncryptType]
6767

68-
TPLINK_DEVICE_TYPES = [
69-
tplink_device_type.value for tplink_device_type in DeviceFamilyType
68+
DEVICE_FAMILY_TYPES = [
69+
device_family_type.value for device_family_type in DeviceFamilyType
7070
]
7171

7272
click.anyio_backend = "asyncio"
@@ -166,7 +166,7 @@ def _device_to_serializable(val: SmartDevice):
166166
"--device-family",
167167
envvar="KASA_DEVICE_FAMILY",
168168
default=None,
169-
type=click.Choice(TPLINK_DEVICE_TYPES, case_sensitive=False),
169+
type=click.Choice(DEVICE_FAMILY_TYPES, case_sensitive=False),
170170
)< F438 /span>
171171
@click.option(
172172
"--timeout",

kasa/device_factory.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,22 +54,15 @@ def _perf_log(has_params, perf_type):
5454
info = await protocol.query(GET_SYSINFO_QUERY)
5555
_perf_log(True, "get_sysinfo")
5656
device_class = get_device_class_from_sys_info(info)
57-
device = device_class(config.host, port=config.port, timeout=config.timeout)
57+
device = device_class(config.host, protocol=protocol)
5858
device.update_from_discover_info(info)
59-
device.protocol = protocol
6059
await device.update()
6160
_perf_log(True, "update")
6261
return device
6362
elif device_class := get_device_class_from_family(
6463
config.connection_type.device_family.value
6564
):
66-
device = device_class(
67-
config.host,
68-
port=config.port,
69-
timeout=config.timeout,
70-
credentials=config.credentials,
71-
)
72-
device.protocol = protocol
65+
device = device_class(host=config.host, protocol=protocol)
7366
await device.update()
7467
_perf_log(True, "update")
7568
return device

kasa/deviceconfig.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ class DeviceConfig:
116116

117117
host: str
118118
timeout: Optional[int] = DEFAULT_TIMEOUT
119-
port: Optional[int] = None
119+
port_override: Optional[int] = None
120120
credentials: Credentials = field(
121121
default_factory=lambda: Credentials(username="", password="")
122122
)

kasa/discover.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def datagram_received(self, data, addr) -> None:
118118

119119
device = None
120120

121-
config = DeviceConfig(host=ip, port=self.port)
121+
config = DeviceConfig(host=ip, port_override=self.port)
122122
if self.credentials:
123123
config.credentials = self.credentials
124124
if self.timeout:
@@ -385,7 +385,7 @@ def _get_device_instance_legacy(data: bytes, config: DeviceConfig) -> SmartDevic
385385
_LOGGER.debug("[DISCOVERY] %s << %s", config.host, info)
386386

387387
device_class = Discover._get_device_class(info)
388-
device = device_class(config.host, port=config.port)
388+
device = device_class(config.host, config=config)
389389
sys_info = info["system"]["get_sysinfo"]
390390
if (device_type := sys_info.get("mic_type")) or (
391391
device_type := sys_info.get("type")
@@ -449,10 +449,7 @@ def _get_device_instance(
449449
)
450450

451451
_LOGGER.debug("[DISCOVERY] %s << %s", config.host, info)
452-
device = device_class(
453-
config.host, port=config.port, credentials=config.credentials
454-
)
455-
device.protocol = protocol
452+
device = device_class(config.host, protocol=protocol)
456453

457454
di = discovery_result.get_dict()
458455
di["model"] = discovery_result.device_model

kasa/klaptransport.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class KlapTransport(BaseTransport):
8383
protocol, used by newer firmware versions.
8484
"""
8585

86-
DEFAULT_PORT = 80
86+
DEFAULT_PORT: int = 80
8787
DISCOVERY_QUERY = {"system": {"get_sysinfo": None}}
8888

8989
KASA_SETUP_EMAIL = "kasa@tp-link.net"
@@ -96,7 +96,7 @@ def __init__(
9696
config: DeviceConfig,
9797
) -> None:
9898
super().__init__(config=config)
99-
self._port = config.port or self.DEFAULT_PORT
99+
100100
self._default_http_client: Optional[httpx.AsyncClient] = None
101101
self._local_seed: Optional[bytes] = None
102102
self._local_auth_hash = self.generate_auth_hash(self._credentials)
@@ -114,6 +114,11 @@ def __init__(
114114

115115
_LOGGER.debug("Created KLAP transport for %s", self._host)
116116

117+
@property
118+
def default_port(self):
119+
"""Default port for the transport."""
120+
return self.DEFAULT_PORT
121+
117122
@property
118123
def _http_client(self) -> httpx.AsyncClient:
119124
if self._config.http_client:

kasa/protocol.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,15 @@ def __init__(
5454
"""Create a protocol object."""
5555
self._config = config
5656
self._host = config.host
57-
self._port = config.port # Set by derived classes
57+
self._port = config.port_override or self.default_port
5858
self._credentials = config.credentials
5959
self._timeout = config.timeout
6060

61+
@property
62+
@abstractmethod
63+
def default_port(self) -> int:
64+
"""The default port for the transport."""
65+
6166
@abstractmethod
6267
async def send(self, request: str) -> Dict:
6368
"""Send a message to the device and return a response."""
@@ -105,11 +110,15 @@ class _XorTransport(BaseTransport):
105110
class.
106111
"""
107112

108-
DEFAULT_PORT = 9999
113+
DEFAULT_PORT: int = 9999
109114

110115
def __init__(self, *, config: DeviceConfig) -> None:
111116
super().__init__(config=config)
112-
self._port = config.port or self.DEFAULT_PORT
117+
118+
@property
119+
def default_port(self):
120+
"""Default port for the transport."""
121+
return self.DEFAULT_PORT
113122

114123
async def send(self, request: str) -> Dict:
115124
"""Send a message to the device and return a response."""

kasa/smartbulb.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
except ImportError:
1010
from pydantic import BaseModel, Field, root_validator
1111

12-
from .credentials import Credentials
12+
from .deviceconfig import DeviceConfig
1313
from .modules import Antitheft, Cloud, Countdown, Emeter, Schedule, Time, Usage
14+
from .protocol import TPLinkProtocol
1415
from .smartdevice import DeviceType, SmartDevice, SmartDeviceException, requires_update
1516

1617

@@ -220,11 +221,10 @@ def __init__(
220221
self,
221222
host: str,
222223
*,
223-
port: Optional[int] = None,
224-
credentials: Optional[Credentials] = None,
225-
timeout: Optional[int] = None,
224+
config: Optional[DeviceConfig] = None,
225+
protocol: Optional[TPLinkProtocol] = None,
226226
) -> None:
227-
super().__init__(host=host, port=port, credentials=credentials, timeout=timeout)
227+
super().__init__(host=host, config=config, protocol=protocol)
228228
self._device_type = DeviceType.Bulb
229229
self.add_module("schedule", Schedule(self, "smartlife.iot.common.schedule"))
230230
self.add_module("usage", Usage(self, "smartlife.iot.common.schedule"))

kasa/smartdevice.py

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -192,21 +192,18 @@ def __init__(
192192
self,
193193
host: str,
194194
*,
195-
port: Optional[int] = None,
196-
credentials: Optional[Credentials] = None,
197-
timeout: Optional[int] = None,
195+
config: Optional[DeviceConfig] = None,
196+
protocol: Optional[TPLinkProtocol] = None,
198197
) -> None:
199198
"""Create a new SmartDevice instance.
200199
201200
:param str host: host name or ip address on which the device listens
202201
"""
203-
self.host = host
204-
self.port = port
205-
config = DeviceConfig(host=host, port=port, timeout=timeout)
206-
self.protocol: TPLinkProtocol = TPLinkSmartHomeProtocol(
207-
transport=_XorTransport(config=config),
202+
if config and protocol:
203+
protocol._transport._config = config
204+
self.protocol: TPLinkProtocol = protocol or TPLinkSmartHomeProtocol(
205+
transport=_XorTransport(config=config or DeviceConfig(host=host)),
208206
)
209-
self.credentials = credentials
210207
_LOGGER.debug("Initializing %s of type %s", self.host, type(self))
211208
self._device_type = DeviceType.Unknown
212209
# TODO: typing Any is just as using Optional[Dict] would require separate
@@ -221,6 +218,30 @@ def __init__(
221218

222219
self.children: List["SmartDevice"] = []
223220

221+
@property
222+
def host(self) -> str:
223+
"""The device host."""
224+
return self.protocol._transport._host
225+
226+
@host.setter
227+
def host(self, value):
228+
"""Set the device host.
229+
230+
Generally used by discovery to set the hostname after ip discovery.
231+
"""
232+
self.protocol._transport._host = value
233+
self.protocol._transport._config.host = value
234+
235+
@property
236+
def port(self) -> int:
237+
"""The device port."""
238+
return self.protocol._transport._port
239+
240+
@property
241+
def credentials(self) -> Optional[Credentials]:
242+
"""The device credentials."""
243+
return self.protocol._transport._credentials
244+
224245
def add_module(self, name: str, module: Module):
225246
"""Register a module."""
226247
if name in self.modules:

kasa/smartdimmer.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
from enum import Enum
33
from typing import Any, Dict, Optional
44

5-
from kasa.credentials import Credentials
5+
from kasa.deviceconfig import DeviceConfig
66
from kasa.modules import AmbientLight, Motion
7+
from kasa.protocol import TPLinkProtocol
78
from kasa.smartdevice import DeviceType, SmartDeviceException, requires_update
89
from kasa.smartplug import SmartPlug
910

@@ -68,11 +69,10 @@ def __init__(
6869
self,
6970
host: str,
7071
*,
71-
port: Optional[int] = None,
72-
credentials: Optional[Credentials] = None,
73-
timeout: Optional[int] = None,
72+
config: Optional[DeviceConfig] = None,
73+
protocol: Optional[TPLinkProtocol] = None,
7474
) -> None:
75-
super().__init__(host, port=port, credentials=credentials, timeout=timeout)
75+
super().__init__(host=host, config=config, protocol=protocol)
7676
self._device_type = DeviceType.Dimmer
7777
# TODO: need to be verified if it's okay to call these on HS220 w/o these
7878
# TODO: need to be figured out what's the best approach to detect support

0 commit comments

Comments
 (0)
0