11"""Add support for discovering mDNS services."""
22from typing import List # noqa: F401
33
4- import zeroconf
4+ from zeroconf import Zeroconf , ServiceBrowser , ServiceInfo , DNSRecord
5+
6+
7+ class FastServiceBrowser (ServiceBrowser ):
8+ """ServiceBrowser that does not process record updates."""
9+
10+ def update_record (self , zc : Zeroconf , now : float , record : DNSRecord ) -> None :
11+ """Ignore record updates as we only care about the cache anyways."""
12+ return
513
614
715class MDNS :
816 """Base class to discover mDNS services."""
917
10- def __init__ (self ):
18+ def __init__ (self , zeroconf_instance = None ):
1119 """Initialize the discovery."""
12- self .zeroconf = None
13- self .services = [] # type: List[zeroconf.ServiceInfo]
14- self ._browsers = [] # type: List[zeroconf.ServiceBrowser]
20+ self .zeroconf = zeroconf_instance
21+ self ._created_zeroconf = False
22+ self .services = [] # type: List[ServiceInfo]
23+ self ._browser = None # type: ServiceBrowser
1524
1625 def register_service (self , service ):
1726 """Register a mDNS service."""
@@ -20,24 +29,31 @@ def register_service(self, service):
2029 def start (self ):
2130 """Start discovery."""
2231 try :
23- self .zeroconf = zeroconf .Zeroconf ()
32+ if not self .zeroconf :
33+ self .zeroconf = Zeroconf ()
34+ self ._created_zeroconf = True
35+
36+ def _service_update (* args , ** kwargs ):
37+ return
2438
25- for service in self .services :
26- self ._browsers .append (zeroconf .ServiceBrowser (
27- self .zeroconf , service .typ , service ))
39+ types = [service .typ for service in self .services ]
40+ self ._browser = FastServiceBrowser (
41+ self .zeroconf , types , handlers = [_service_update ]
42+ )
2843 except Exception : # pylint: disable=broad-except
2944 self .stop ()
3045 raise
3146
3247 def stop (self ):
3348 """Stop discovering."""
34- while self ._browsers :
35- self ._browsers .pop ().cancel ()
49+ if self ._browser :
50+ self ._browser .cancel ()
51+ self ._browser = None
3652
3753 for service in self .services :
3854 service .reset ()
3955
40- if self .zeroconf :
56+ if self ._created_zeroconf :
4157 self .zeroconf .close ()
4258 self .zeroconf = None
4359
0 commit comments