10000 Make device initialisation easier by reducing required imports by sdb9696 · Pull Request #936 · python-kasa/python-kasa · GitHub
[go: up one dir, main page]

Skip to content

Make device initialisation easier by reducing required imports #936

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions devtools/dump_devinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,11 +231,11 @@ async def cli(
if host is not None:
if discovery_info:
click.echo("Host and discovery info given, trying connect on %s." % host)
from kasa import ConnectionType, DeviceConfig
from kasa import DeviceConfig, DeviceConnectionParameters

di = json.loads(discovery_info)
dr = DiscoveryResult(**di)
connection_type = ConnectionType.from_values(
connection_type = DeviceConnectionParameters.from_values(
dr.device_type,
dr.mgt_encrypt_schm.encrypt_type,
dr.mgt_encrypt_schm.lv,
Expand Down
2 changes: 2 additions & 0 deletions docs/source/guides.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ This page contains guides of how to perform common actions using the library.

```{eval-rst}
.. automodule:: kasa.discover
:noindex:
```

## Connect without discovery

```{eval-rst}
.. automodule:: kasa.deviceconfig
:noindex:
```

## Get Energy Consumption and Usage Statistics
Expand Down
52 changes: 48 additions & 4 deletions docs/source/reference.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,63 @@
# API Reference

```{currentmodule} kasa
```

## Discover


```{module} kasa.discover
```

```{eval-rst}
.. autoclass:: kasa.Discover
:members:
```

## Device

```{module} kasa.device
```

```{eval-rst}
.. autoclass:: Device
:members:
:undoc-members:
```


## Device Config

```{module} kasa.credentials
```

```{eval-rst}
.. autoclass:: Credentials
:members:
:undoc-members:
```

```{module} kasa.deviceconfig
```

```{eval-rst}
.. autoclass:: DeviceConfig
:members:
:undoc-members:
```


```{eval-rst}
.. autoclass:: kasa.DeviceFamily
:members:
:undoc-members:
```

```{eval-rst}
.. autoclass:: kasa.DeviceConnection
:members:
:undoc-members:
```

```{eval-rst}
.. autoclass:: kasa.Device
.. autoclass:: kasa.DeviceEncryption
:members:
:undoc-members:
```
Expand Down
6 changes: 3 additions & 3 deletions docs/tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@

Most newer devices require your TP-Link cloud username and password, but this can be omitted for older devices.

>>> from kasa import Device, Discover, Credentials
>>> from kasa import Discover

:func:`~kasa.Discover.discover` returns a dict[str,Device] of devices on your network:

>>> devices = await Discover.discover(credentials=Credentials("user@example.com", "great_password"))
>>> devices = await Discover.discover(username="user@example.com", password="great_password")
>>> for dev in devices.values():
>>> await dev.update()
>>> print(dev.host)
Expand All @@ -27,7 +27,7 @@

:meth:`~kasa.Discover.discover_single` returns a single device by hostname:

>>> dev = await Discover.discover_single("127.0.0.3", credentials=Credentials("user@example.com", "great_password"))
>>> dev = await Discover.discover_single("127.0.0.3", username="user@example.com", password="great_password")
>>> await dev.update()
>>> dev.alias
Living Room Bulb
Expand Down
25 changes: 16 additions & 9 deletions kasa/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
from kasa.device import Device
from kasa.device_type import DeviceType
from kasa.deviceconfig import (
ConnectionType,
DeviceConfig,
DeviceFamilyType,
EncryptType,
DeviceConnectionParameters,
DeviceEncryptionType,
DeviceFamily,
)
from kasa.discover import Discover
from kasa.emeterstatus import EmeterStatus
Expand Down Expand Up @@ -71,9 +71,9 @@
"TimeoutError",
"Credentials",
"DeviceConfig",
"ConnectionType",
"EncryptType",
"DeviceFamilyType",
"DeviceConnectionParameters",
"DeviceEncryptionType",
"DeviceFamily",
]

from . import iot
Expand All @@ -89,11 +89,14 @@
"SmartDimmer": iot.IotDimmer,
"SmartBulbPreset": IotLightPreset,
}
deprecated_exceptions = {
deprecated_classes = {
"SmartDeviceException": KasaException,
"UnsupportedDeviceException": UnsupportedDeviceError,
"AuthenticationException": AuthenticationError,
"TimeoutException": TimeoutError,
"ConnectionType": DeviceConnectionParameters,
"EncryptType": DeviceEncryptionType,
"DeviceFamilyType": DeviceFamily,
}


Expand All @@ -112,8 +115,8 @@ def __getattr__(name):
stacklevel=1,
)
return new_class
if name in deprecated_exceptions:
new_class = deprecated_exceptions[name]
if name in deprecated_classes:
new_class = deprecated_classes[name]
msg = f"{name} is deprecated, use {new_class.__name__} instead"
warn(msg, DeprecationWarning, stacklevel=1)
return new_class
Expand All @@ -133,6 +136,10 @@ def __getattr__(name):
UnsupportedDeviceException = UnsupportedDeviceError
AuthenticationException = AuthenticationError
TimeoutException = TimeoutError
ConnectionType = DeviceConnectionParameters
EncryptType = DeviceEncryptionType
DeviceFamilyType = DeviceFamily

# Instanstiate all classes so the type checkers catch abstract issues
from . import smart

Expand Down
18 changes: 8 additions & 10 deletions kasa/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@

from kasa import (
AuthenticationError,
ConnectionType,
Credentials,
Device,
DeviceConfig,
DeviceFamilyType,
DeviceConnectionParameters,
DeviceEncryptionType,
DeviceFamily,
Discover,
EncryptType,
Feature,
KasaException,
Module,
Expand Down Expand Up @@ -87,11 +87,9 @@ def wrapper(message=None, *args, **kwargs):
"smart.bulb": SmartDevice,
}

ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in EncryptType]
ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in DeviceEncryptionType]

DEVICE_FAMILY_TYPES = [
device_family_type.value for device_family_type in DeviceFamilyType
]
DEVICE_FAMILY_TYPES = [device_family_type.value for device_family_type in DeviceFamily]

# Block list of commands which require no update
SKIP_UPDATE_COMMANDS = ["wifi", "raw-command", "command"]
Expand Down Expand Up @@ -374,9 +372,9 @@ def _nop_echo(*args, **kwargs):
if type is not None:
dev = TYPE_TO_CLASS[type](host)
elif device_family and encrypt_type:
ctype = ConnectionType(
DeviceFamilyType(device_family),
EncryptType(encrypt_type),
ctype = DeviceConnectionParameters(
DeviceFamily(device_family),
DeviceEncryptionType(encrypt_type),
login_version,
)
config = DeviceConfig(
Expand Down
29 changes: 26 additions & 3 deletions kasa/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@
from typing import TYPE_CHECKING, Any, Mapping, Sequence
from warnings import warn

from .credentials import Credentials
from typing_extensions import TypeAlias

from .credentials import Credentials as _Credentials
from .device_type import DeviceType
from .deviceconfig import DeviceConfig
from .deviceconfig import (
DeviceConfig,
DeviceConnectionParameters,
DeviceEncryptionType,
DeviceFamily,
)
from .emeterstatus import EmeterStatus
from .exceptions import KasaException
from .feature import Feature
Expand Down Expand Up @@ -51,6 +58,22 @@ class Device(ABC):
or :func:`Discover.discover_single()`.
"""

# All types required to create devices directly via connect are aliased here
# to avoid consumers having to do multiple imports.

#: The type of device
Type: TypeAlias = DeviceType
#: The credentials for authentication
Credentials: TypeAlias = _Credentials
#: Configuration for connecting to the device
Config: TypeAlias = DeviceConfig
#: The family of the device, e.g. SMART.KASASWITCH.
Family: TypeAlias = DeviceFamily
#: The encryption for the device, e.g. Klap or Aes
EncryptionType: TypeAlias = DeviceEncryptionType
#: The connection type for the device.
ConnectionParameters: TypeAlias = DeviceConnectionParameters

def __init__(
self,
host: str,
Expand Down Expand Up @@ -166,7 +189,7 @@ def port(self) -> int:
return self.protocol._transport._port

@property
def credentials(self) -> Credentials | None:
def credentials(self) -> _Credentials | None:
"""The device credentials."""
return self.protocol._transport._credentials

Expand Down
40 changes: 20 additions & 20 deletions kasa/deviceconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

Discovery returns a list of discovered devices:

>>> from kasa import Discover, Credentials, Device, DeviceConfig
>>> from kasa import Discover, Device
>>> device = await Discover.discover_single(
>>> "127.0.0.3",
>>> credentials=Credentials("myusername", "mypassword"),
>>> discovery_timeout=10
>>> username="user@example.com",
>>> password="great_password",
>>> )
>>> print(device.alias) # Alias is None because update() has not been called
None
Expand All @@ -21,7 +21,7 @@
: {'device_family': 'SMART.TAPOBULB', 'encryption_type': 'KLAP', 'login_version': 2},\
'uses_http': True}

>>> later_device = await Device.connect(config=DeviceConfig.from_dict(config_dict))
>>> later_device = await Device.connect(config=Device.Config.from_dict(config_dict))
>>> print(later_device.alias) # Alias is available as connect() calls update()
Living Room Bulb

Expand All @@ -45,15 +45,15 @@
_LOGGER = logging.getLogger(__name__)


class EncryptType(Enum):
class DeviceEncryptionType(Enum):
"""Encrypt type enum."""

Klap = "KLAP"
Aes = "AES"
Xor = "XOR"


class DeviceFamilyType(Enum):
class DeviceFamily(Enum):
"""Encrypt type enum."""

IotSmartPlugSwitch = "IOT.SMARTPLUGSWITCH"
Expand Down Expand Up @@ -105,24 +105,24 @@


@dataclass
class ConnectionType:
class DeviceConnectionParameters:
"""Class to hold the the parameters determining connection type."""

device_family: DeviceFamilyType
encryption_type: EncryptType
device_family: DeviceFamily
encryption_type: DeviceEncryptionType
login_version: Optional[int] = None

@staticmethod
def from_values(
device_family: str,
encryption_type: str,
login_version: Optional[int] = None,
) -> "ConnectionType":
) -> "DeviceConnectionParameters":
"""Return connection parameters from string values."""
try:
return ConnectionType(
DeviceFamilyType(device_family),
EncryptType(encryption_type),
return DeviceConnectionParameters(
DeviceFamily(device_family),
DeviceEncryptionType(encryption_type),
login_version,
)
except (ValueError, TypeError) as ex:
Expand All @@ -132,7 +132,7 @@
) from ex

@staticmethod
def from_dict(connection_type_dict: Dict[str, str]) -> "ConnectionType":
def from_dict(connection_type_dict: Dict[str, str]) -> "DeviceConnectionParameters":
"""Return connection parameters from dict."""
if (
isinstance(connection_type_dict, dict)
Expand All @@ -141,7 +141,7 @@
):
if login_version := connection_type_dict.get("login_version"):
login_version = int(login_version) # type: ignore[assignment]
return ConnectionType.from_values(
return DeviceConnectionParameters.from_values(
device_family,
encryption_type,
login_version, # type: ignore[arg-type]
Expand Down Expand Up @@ -180,9 +180,9 @@
#: The protocol specific type of connection. Defaults to the legacy type.
batch_size: Optional[int] = None
#: The batch size for protoools supporting multiple request batches.
connection_type: ConnectionType = field(
default_factory=lambda: ConnectionType(
DeviceFamilyType.IotSmartPlugSwitch, EncryptType.Xor, 1
connection_type: DeviceConnectionParameters = field(
default_factory=lambda: DeviceConnectionParameters(
DeviceFamily.IotSmartPlugSwitch, DeviceEncryptionType.Xor, 1
)
)
#: True if the device uses http. Consumers should retrieve rather than set this
Expand All @@ -195,8 +195,8 @@

def __post_init__(self):
if self.connection_type is None:
self.connection_type = ConnectionType(
DeviceFamilyType.IotSmartPlugSwitch, EncryptType.Xor
self.connection_type = DeviceConnectionParameters(

Check warning on line 198 in kasa/deviceconfig.py

View check run for this annotation

Codecov / codecov/patch

kasa/deviceconfig.py#L198

Added line #L198 was not covered by tests
DeviceFamily.IotSmartPlugSwitch, DeviceEncryptionType.Xor
)

def to_dict(
Expand Down
Loading
Loading
0