-
-
Notifications
You must be signed in to change notification settings - Fork 238
Add support for pairing devices with hubs #859
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
+412
−15
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
07857af
Add support for pairing devices
rytilahti 1f240a3
Add 'Pair' action
rytilahti d8b067f
Add tests and refactor
rytilahti 017271e
Rebase on top of current master
rytilahti ebbfa32
Re-add fakeprotocol implementations and fix tests
rytilahti 18e8a2c
Simplify pairing process, support pairing multiple devices at once, a…
rytilahti 300639c
Add get_scan_child_device_list with two detected devices to h100 fixture
rytilahti c34aa71
Apply suggestions from code review
rytilahti 837b68f
Some improvements based on code review
rytilahti 71a81d5
devices_smart->hubs_smart
rytilahti cf1ad89
Add unpair to child devices
rytilahti aeb4705
Check for prereqs in group + minor cleanups
rytilahti 6a0d3be
Log end user relevant logs into info logger
rytilahti fc48009
Merge remote-tracking branch 'upstream/master' into feat/hub_pairing
rytilahti a4ffdcd
Update tests/fakeprotocol_smart.py
rytilahti 1188acb
Fix tests
rytilahti bef3f65
Move hub tests into its own package and implement unpair
rytilahti ab04ab8
Cleanup a bit
rytilahti c5c09e2
Fix tests and remove explicit unpair method from child device
sdb9696 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| """Hub-specific commands.""" | ||
|
|
||
| import asyncio | ||
|
|
||
| import asyncclick as click | ||
|
|
||
| from kasa import DeviceType, Module, SmartDevice | ||
| from kasa.smart import SmartChildDevice | ||
|
|
||
| from .common import ( | ||
| echo, | ||
| error, | ||
| pass_dev, | ||
| ) | ||
|
|
||
|
|
||
| def pretty_category(cat: str): | ||
| """Return pretty category for paired devices.""" | ||
| return SmartChildDevice.CHILD_DEVICE_TYPE_MAP.get(cat) | ||
|
|
||
|
|
||
| @click.group() | ||
| @pass_dev | ||
| async def hub(dev: SmartDevice): | ||
| """Commands controlling hub child device pairing.""" | ||
| if dev.device_type is not DeviceType.Hub: | ||
| error(f"{dev} is not a hub.") | ||
|
|
||
| if dev.modules.get(Module.ChildSetup) is None: | ||
| error(f"{dev} does not have child setup module.") | ||
|
|
||
|
|
||
| @hub.command(name="list") | ||
| @pass_dev | ||
| async def hub_list(dev: SmartDevice): | ||
| """List hub paired child devices.""" | ||
| for c in dev.children: | ||
| echo(f"{c.device_id}: {c}") | ||
|
|
||
|
|
||
| @hub.command(name="supported") | ||
| @pass_dev | ||
| async def hub_supported(dev: SmartDevice): | ||
| """List supported hub child device categories.""" | ||
| cs = dev.modules[Module.ChildSetup] | ||
|
|
||
| cats = [cat["category"] for cat in await cs.get_supported_device_categories()] | ||
| for cat in cats: | ||
| echo(f"Supports: {cat}") | ||
|
|
||
|
|
||
| @hub.command(name="pair") | ||
| @click.option("--timeout", default=10) | ||
| @pass_dev | ||
| async def hub_pair(dev: SmartDevice, timeout: int): | ||
| """Pair all pairable device. | ||
|
|
||
| This will pair any child devices currently in pairing mode. | ||
| """ | ||
| cs = dev.modules[Module.ChildSetup] | ||
|
|
||
| echo(f"Finding new devices for {timeout} seconds...") | ||
|
|
||
| pair_res = await cs.pair(timeout=timeout) | ||
| if not pair_res: | ||
| echo("No devices found.") | ||
|
|
||
| for child in pair_res: | ||
| echo( | ||
| f'Paired {child["name"]} ({child["device_model"]}, ' | ||
| f'{pretty_category(child["category"])}) with id {child["device_id"]}' | ||
| ) | ||
|
|
||
|
|
||
| @hub.command(name="unpair") | ||
| @click.argument("device_id") | ||
| @pass_dev | ||
| async def hub_unpair(dev, device_id: str): | ||
| """Unpair given device.""" | ||
| cs = dev.modules[Module.ChildSetup] | ||
|
|
||
| # Accessing private here, as the property exposes only values | ||
| if device_id not in dev._children: | ||
| error(f"{dev} does not have children with identifier {device_id}") | ||
|
|
||
| res = await cs.unpair(device_id=device_id) | ||
| # Give the device some time to update its internal state, just in case. | ||
| await asyncio.sleep(1) | ||
| await dev.update() | ||
|
|
||
| if device_id not in dev._children: | ||
| echo(f"Unpaired {device_id}") | ||
| else: | ||
| error(f"Failed to unpair {device_id}") | ||
|
|
||
| return res |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| """Implementation for child device setup. | ||
|
|
||
| This module allows pairing and disconnecting child devices. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
|
|
||
| from ...feature import Feature | ||
| from ..smartmodule import SmartModule | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ChildSetup(SmartModule): | ||
| """Implementation for child device setup.""" | ||
|
|
||
| REQUIRED_COMPONENT = "child_quick_setup" | ||
| QUERY_GETTER_NAME = "get_support_child_device_category" | ||
|
|
||
| def _initialize_features(self) -> None: | ||
| """Initialize features.""" | ||
| self._add_feature( | ||
| Feature( | ||
| self._device, | ||
| id="pair", | ||
| name="Pair", | ||
| container=self, | ||
| attribute_setter="pair", | ||
| category=Feature.Category.Config, | ||
| type=Feature.Type.Action, | ||
| ) | ||
| ) | ||
|
|
||
| async def get_supported_device_categories(self) -> list[dict]: | ||
| """Get supported device categories.""" | ||
| categories = await self.call("get_support_child_device_category") | ||
| return categories["get_support_child_device_category"]["device_category_list"] | ||
|
|
||
| async def pair(self, *, timeout: int = 10) -> list[dict]: | ||
| """Scan for new devices and pair after discovering first new device.""" | ||
| await self.call("begin_scanning_child_device") | ||
|
|
||
| _LOGGER.info("Waiting %s seconds for discovering new devices", timeout) | ||
| await asyncio.sleep(timeout) | ||
| detected = await self._get_detected_devices() | ||
|
|
||
| if not detected["child_device_list"]: | ||
| _LOGGER.info("No devices found.") | ||
| return [] | ||
|
|
||
| _LOGGER.info( | ||
| "Discovery done, found %s devices: %s", | ||
| len(detected["child_device_list"]), | ||
| detected, | ||
| ) | ||
|
|
||
| await self._add_devices(detected) | ||
|
|
||
| return detected["child_device_list"] | ||
|
|
||
| async def unpair(self, device_id: str) -> dict: | ||
| """Remove device from the hub.""" | ||
| _LOGGER.debug("Going to unpair %s from %s", device_id, self) | ||
|
|
||
| payload = {"child_device_list": [{"device_id": device_id}]} | ||
| return await self.call("remove_child_device_list", payload) | ||
|
|
||
| async def _add_devices(self, devices: dict) -> dict: | ||
| """Add devices based on get_detected_device response. | ||
|
|
||
| Pass the output from :ref:_get_detected_devices: as a parameter. | ||
| """ | ||
| res = await self.call("add_child_device_list", devices) | ||
| return res | ||
|
|
||
| async def _get_detected_devices(self) -> dict: | ||
| """Return list of devices detected during scanning.""" | ||
| param = {"scan_list": await self.get_supported_device_categories()} | ||
| res = await self.call("get_scan_child_device_list", param) | ||
| _LOGGER.debug("Scan status: %s", res) | ||
| return res["get_scan_child_device_list"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import pytest | ||
| from pytest_mock import MockerFixture | ||
|
|
||
| from kasa import DeviceType, Module | ||
| from kasa.cli.hub import hub | ||
|
|
||
| from ..device_fixtures import HUBS_SMART, hubs_smart, parametrize, plug_iot | ||
|
|
||
|
|
||
| @hubs_smart | ||
| async def test_hub_pair(dev, mocker: MockerFixture, runner, caplog): | ||
| """Test that pair calls the expected methods.""" | ||
| cs = dev.modules.get(Module.ChildSetup) | ||
| # Patch if the device supports the module | ||
| if cs is not None: | ||
| mock_pair = mocker.patch.object(cs, "pair") | ||
|
|
||
| res = await runner.invoke(hub, ["pair"], obj=dev, catch_exceptions=False) | ||
| if cs is None: | ||
| assert "is not a hub" in res.output | ||
| return | ||
|
|
||
| mock_pair.assert_awaited() | ||
| assert "Finding new devices for 10 seconds" in res.output | ||
| assert res.exit_code == 0 | ||
|
|
||
|
|
||
| @parametrize("hubs smart", model_filter=HUBS_SMART, protocol_filter={"SMART"}) | ||
| async def test_hub_unpair(dev, mocker: MockerFixture, runner): | ||
| """Test that unpair calls the expected method.""" | ||
| if not dev.children: | ||
| pytest.skip("Cannot test without child devices") | ||
|
|
||
| id_ = next(iter(dev.children)).device_id | ||
|
|
||
| cs = dev.modules.get(Module.ChildSetup) | ||
| mock_unpair = mocker.spy(cs, "unpair") | ||
|
|
||
| res = await runner.invoke(hub, ["unpair", id_], obj=dev, catch_exceptions=False) | ||
|
|
||
| mock_unpair.assert_awaited() | ||
| assert f"Unpaired {id_}" in res.output | ||
| assert res.exit_code == 0 | ||
|
|
||
|
|
||
| @plug_iot | ||
| async def test_non_hub(dev, mocker: MockerFixture, runner): | ||
| """Test that hub commands return an error if executed on a non-hub.""" | ||
| assert dev.device_type is not DeviceType.Hub | ||
| res = await runner.invoke( | ||
| hub, ["unpair", "dummy_id"], obj=dev, catch_exceptions=False | ||
| ) | ||
| assert "is not a hub" in res.output |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.