diff --git a/libsoundtouch/__init__.py b/libsoundtouch/__init__.py index b9051ab..c3f1f36 100644 --- a/libsoundtouch/__init__.py +++ b/libsoundtouch/__init__.py @@ -24,10 +24,11 @@ def soundtouch_device(host, port=8090): return s_device -def discover_devices(timeout=5): +def discover_devices(timeout=5, zeroconf=None): """Discover devices on the local network. :param timeout: Max time to wait in seconds. Default 5 + :param zeroconf: Global singleton zeroconf instance. Default None """ devices = [] # Using Queue as a timeout timer @@ -38,12 +39,17 @@ def add_device_function(name, host, port): _LOGGER.info("%s discovered (host: %s, port: %i)", name, host, port) devices.append(soundtouch_device(host, port)) - zeroconf = Zeroconf() + if zeroconf is None: + zeroconf = Zeroconf() + listener = SoundtouchDeviceListener(add_device_function) _LOGGER.debug("Starting discovery...") - ServiceBrowser(zeroconf, "_soundtouch._tcp.local.", listener) + browser = ServiceBrowser(zeroconf, "_soundtouch._tcp.local.", listener) try: add_devices_queue.get(timeout=timeout) except Empty: _LOGGER.debug("End of discovery...") + finally: + browser.cancel() + return devices