zeroconf.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import logging
  2. import socket
  3. from zeroconf import (
  4. ServiceInfo,
  5. NonUniqueNameException,
  6. InterfaceChoice,
  7. IPVersion,
  8. Zeroconf,
  9. )
  10. logger = logging.getLogger(__name__)
  11. ZEROCONF_TYPE = "_frigate._tcp.local."
  12. # Taken from: http://stackoverflow.com/a/11735897
  13. def get_local_ip() -> str:
  14. """Try to determine the local IP address of the machine."""
  15. try:
  16. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  17. # Use Google Public DNS server to determine own IP
  18. sock.connect(("8.8.8.8", 80))
  19. return sock.getsockname()[0] # type: ignore
  20. except OSError:
  21. try:
  22. return socket.gethostbyname(socket.gethostname())
  23. except socket.gaierror:
  24. return "127.0.0.1"
  25. finally:
  26. sock.close()
  27. def broadcast_zeroconf(frigate_id):
  28. zeroconf = Zeroconf(interfaces=InterfaceChoice.Default, ip_version=IPVersion.V4Only)
  29. host_ip = get_local_ip()
  30. try:
  31. host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
  32. except OSError:
  33. host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)
  34. info = ServiceInfo(
  35. ZEROCONF_TYPE,
  36. name=f"{frigate_id}.{ZEROCONF_TYPE}",
  37. addresses=[host_ip_pton],
  38. port=5000,
  39. )
  40. logger.info("Starting Zeroconf broadcast")
  41. try:
  42. zeroconf.register_service(info)
  43. except NonUniqueNameException:
  44. logger.error(
  45. "Frigate instance with identical name present in the local network"
  46. )
  47. return zeroconf