-
Notifications
You must be signed in to change notification settings - Fork 28
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
Add zeroconf discovery support #369
Merged
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
20678f1
Get version control for updates
pawlizio fe00b24
Merge branch 'master' of https://github.com/Julius2342/pyvlx
pawlizio 2a13c88
Add discovery service
pawlizio ea3fc6d
Add missing docstring.
pawlizio f919b16
Restore version
pawlizio 588ca14
Add missing docstring
pawlizio a81e119
Add blank line
pawlizio 7d6d123
Add white line
pawlizio 39852d3
fix isort
pawlizio 00a4391
Update requirements
pawlizio b789e9b
Update discovery.oy
pawlizio 2ddeb0c
Update python_support
pawlizio 9936fa0
Revert "Update python_support"
pawlizio 37ab3ec
Update discovery.py
pawlizio 9e8fd24
Update coverage
pawlizio be976f6
Fix flake8
pawlizio dbfc71e
Cancel support for python 3.10
pawlizio 006c65d
Update docstring
pawlizio b771450
Fix isort
pawlizio d21b995
Avoid CancellationError
pawlizio 8a0668e
Remove trailing whitespace
pawlizio 0a8afaa
isort fix
pawlizio e4e12be
Add zeroconf to install_requires
pawlizio 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 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 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 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,87 @@ | ||
"""Module to discover Velux KLF200 devices on the network.""" | ||
import asyncio | ||
from asyncio import Event, Future, Task | ||
from dataclasses import dataclass | ||
from typing import Any, Optional | ||
|
||
from zeroconf import IPVersion | ||
from zeroconf.asyncio import ( | ||
AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf) | ||
|
||
SERVICE_STARTS_WITH: str = "VELUX_KLF_LAN" | ||
SERVICE_TYPE: str = "_http._tcp.local." | ||
|
||
|
||
@dataclass | ||
class VeluxHost(): | ||
"""Class to store Velux KLF200 host information.""" | ||
|
||
hostname: str | ||
ip_address: str | ||
|
||
|
||
class VeluxDiscovery(): | ||
"""Class to discover Velux KLF200 devices on the network.""" | ||
|
||
def __init__(self, zeroconf: AsyncZeroconf,) -> None: | ||
"""Initialize VeluxDiscovery object.""" | ||
self.zc: AsyncZeroconf = zeroconf | ||
self.hosts: list[VeluxHost | None] = [] | ||
self.infos: list[AsyncServiceInfo | None] = [] | ||
|
||
async def _async_discover_hosts(self, min_wait_time: float, expected_hosts: int | None) -> None: | ||
"""Listen for zeroconf ServiceInfo.""" | ||
self.hosts.clear() | ||
service_names: list[str] = [] | ||
tasks: list[Task] = [] | ||
got_host: Event = Event() | ||
|
||
def add_info_and_host(fut: Future) -> None: | ||
info: AsyncServiceInfo = fut.result() | ||
self.infos.append(info) | ||
host = VeluxHost( | ||
hostname=info.name.replace("._http._tcp.local.", ""), | ||
ip_address=info.parsed_addresses(version=IPVersion.V4Only)[0], | ||
) | ||
self.hosts.append(host) | ||
got_host.set() | ||
|
||
def handler(name: str, **kwargs: Any) -> None: # pylint: disable=W0613:unused-argument | ||
if name.startswith(SERVICE_STARTS_WITH): | ||
if name not in service_names: | ||
service_names.append(name) | ||
task = asyncio.create_task(self.zc.async_get_service_info(type_=SERVICE_TYPE, name=name)) | ||
task.add_done_callback(add_info_and_host) | ||
tasks.append(task) | ||
|
||
browser: AsyncServiceBrowser = AsyncServiceBrowser(self.zc.zeroconf, SERVICE_TYPE, handlers=[handler]) | ||
if expected_hosts: | ||
while len(self.hosts) < expected_hosts: | ||
await got_host.wait() | ||
got_host.clear() | ||
while not self.hosts: | ||
await asyncio.sleep(min_wait_time) | ||
await browser.async_cancel() | ||
await asyncio.gather(*tasks) | ||
|
||
async def async_discover_hosts( | ||
self, | ||
timeout: float = 10, | ||
min_wait_time: float = 3, | ||
expected_hosts: Optional[int] = None | ||
) -> bool: | ||
"""Return true if Velux KLF200 devices found on the network. | ||
|
||
This function creates a zeroconf AsyncServiceBrowser and | ||
waits min_wait_time (seconds) for ServiceInfos from hosts. | ||
Some devices may take some time to respond (i.e. if they currently have a high CPU load). | ||
If one or more Hosts are found, the function cancels the ServiceBrowser and returns true. | ||
If expected_hosts is set, the function ignores min_wait_time and returns true once expected_hosts are found. | ||
If timeout (seconds) is exceeded, the function returns false. | ||
""" | ||
try: | ||
async with asyncio.timeout(timeout): | ||
await self._async_discover_hosts(min_wait_time, expected_hosts) | ||
except TimeoutError: | ||
return False | ||
return True |
This file contains 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 |
---|---|---|
@@ -1 +1,2 @@ | ||
pyyaml==6.0.1 | ||
zeroconf==0.131.0 |
This file contains 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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
^^