Skip to content

Commit 0f702c6

Browse files
authored
Update async_service_info_request example to ensure it runs in the right event loop (#749)
1 parent 0dbcabf commit 0f702c6

1 file changed

Lines changed: 31 additions & 17 deletions

File tree

examples/async_service_info_request.py

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import argparse
1010
import asyncio
1111
import logging
12-
from typing import cast
12+
from typing import Any, Optional, cast
1313

1414

1515
from zeroconf import IPVersion, ServiceBrowser, ServiceStateChange, Zeroconf
@@ -48,6 +48,33 @@ async def async_watch_services(aiozc: AsyncZeroconf) -> None:
4848
print('\n')
4949

5050

51+
class AsyncRunner:
52+
def __init__(self, args: Any) -> None:
53+
self.args = args
54+
self.threaded_browser: Optional[ServiceBrowser] = None
55+
self.aiozc: Optional[AsyncZeroconf] = None
56+
57+
async def async_run(self) -> None:
58+
self.aiozc = AsyncZeroconf(ip_version=ip_version)
59+
assert self.aiozc is not None
60+
61+
def on_service_state_change(
62+
zeroconf: Zeroconf, service_type: str, state_change: ServiceStateChange, name: str
63+
) -> None:
64+
"""Dummy handler."""
65+
66+
self.threaded_browser = ServiceBrowser(
67+
self.aiozc.zeroconf, [HAP_TYPE], handlers=[on_service_state_change]
68+
)
69+
await async_watch_services(self.aiozc)
70+
71+
async def async_close(self) -> None:
72+
assert self.aiozc is not None
73+
assert self.threaded_browser is not None
74+
self.threaded_browser.cancel()
75+
await self.aiozc.async_close()
76+
77+
5178
if __name__ == '__main__':
5279
logging.basicConfig(level=logging.DEBUG)
5380

@@ -67,23 +94,10 @@ async def async_watch_services(aiozc: AsyncZeroconf) -> None:
6794
else:
6895
ip_version = IPVersion.V4Only
6996

70-
aiozc = AsyncZeroconf(ip_version=ip_version)
71-
72-
def on_service_state_change(
73-
zeroconf: Zeroconf, service_type: str, state_change: ServiceStateChange, name: str
74-
) -> None:
75-
"""Dummy handler."""
76-
7797
print(f"Services with {HAP_TYPE} will be shown every 5s, press Ctrl-C to exit...")
78-
# ServiceBrowser currently is only offered in sync context.
79-
# ServiceInfo has an AsyncServiceInfo counterpart that can be used
80-
# to fetch service info in parallel
81-
browser = ServiceBrowser(aiozc.zeroconf, [HAP_TYPE], handlers=[on_service_state_change])
8298
loop = asyncio.get_event_loop()
99+
runner = AsyncRunner(args)
83100
try:
84-
loop.run_until_complete(async_watch_services(aiozc))
101+
loop.run_until_complete(runner.async_run())
85102
except KeyboardInterrupt:
86-
pass
87-
finally:
88-
browser.cancel()
89-
loop.run_until_complete(aiozc.async_close())
103+
loop.run_until_complete(runner.async_close())

0 commit comments

Comments
 (0)