diff --git a/aioesphomeapi/host_resolver.py b/aioesphomeapi/host_resolver.py index 679caf6..dacd8ab 100644 --- a/aioesphomeapi/host_resolver.py +++ b/aioesphomeapi/host_resolver.py @@ -58,6 +58,7 @@ async def _async_zeroconf_get_service_info( timeout: float, ) -> AsyncServiceInfo: # Use or create zeroconf instance, ensure it's an AsyncZeroconf + had_instance = zeroconf_manager.has_instance try: zc = zeroconf_manager.get_async_zeroconf().zeroconf except Exception as exc: @@ -73,7 +74,8 @@ async def _async_zeroconf_get_service_info( f"Error resolving mDNS {service_name} via mDNS: {exc}" ) from exc finally: - await zeroconf_manager.async_close() + if not had_instance: + await zeroconf_manager.async_close() return info diff --git a/aioesphomeapi/zeroconf.py b/aioesphomeapi/zeroconf.py index 48f19fc..caf902d 100644 --- a/aioesphomeapi/zeroconf.py +++ b/aioesphomeapi/zeroconf.py @@ -26,6 +26,11 @@ class ZeroconfManager: if zeroconf is not None: self.set_instance(zeroconf) + @property + def has_instance(self) -> bool: + """Return True if a Zeroconf instance is set.""" + return self._aiozc is not None + def set_instance(self, zc: AsyncZeroconf | Zeroconf) -> None: """Set the AsyncZeroconf instance.""" if self._aiozc: