You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.2 KiB

4 years ago
  1. """Add support for discovering mDNS services."""
  2. import zeroconf
  3. class MDNS:
  4. """Base class to discover mDNS services."""
  5. def __init__(self):
  6. """Initialize the discovery."""
  7. self.zeroconf = None
  8. self.services = []
  9. self._browsers = []
  10. def register_service(self, service):
  11. """Register a mDNS service."""
  12. self.services.append(service)
  13. def start(self):
  14. """Start discovery."""
  15. try:
  16. self.zeroconf = zeroconf.Zeroconf()
  17. for service in self.services:
  18. self._browsers.append(zeroconf.ServiceBrowser(
  19. self.zeroconf, service.typ, service))
  20. except Exception: # pylint: disable=broad-except
  21. self.stop()
  22. raise
  23. def stop(self):
  24. """Stop discovering."""
  25. while self._browsers:
  26. self._browsers.pop().cancel()
  27. for service in self.services:
  28. service.reset()
  29. if self.zeroconf:
  30. self.zeroconf.close()
  31. self.zeroconf = None
  32. @property
  33. def entries(self):
  34. """Return all entries in the cache."""
  35. return self.zeroconf.cache.entries()