Skip to content

Instantly share code, notes, and snippets.

@jamal
Last active June 23, 2023 20:50
Show Gist options
  • Save jamal/ae04ebfd0f75a48d6c272863808a7e95 to your computer and use it in GitHub Desktop.
Save jamal/ae04ebfd0f75a48d6c272863808a7e95 to your computer and use it in GitHub Desktop.
Discover mDNS records for Home Assistant and print the Avahi service config
# This is based on the solution by Michel5 provided here https://community.home-assistant.io/t/solved-how-to-configure-avahi-daemon-on-docker-host/356422
from zeroconf import ServiceBrowser, Zeroconf
class MyListener:
def remove_service(self, zeroconf, type, name):
print("Service %s removed" % (name,))
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
print("Service %s discovered:" % (name))
print("<service-group>")
print("\t<name>%s</name>" % (name))
print("\t<service>")
print("\t\t<port>%d</port>" % (info.port))
for key in info.properties:
print("\t\t<txt-record>%s=%s</txt-record>" % (key.decode(), info.properties[key].decode()))
print("\t</service>")
print("</service-group>")
print("")
zeroconf = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf, "_hap._tcp.local.", listener)
try:
input("Press enter to exit...\n\n")
finally:
zeroconf.close()
@jamal
Copy link
Author

jamal commented Jun 23, 2023

HomeKit uses mDNS to discover and connect to devices, which is a problem when Home Assistant is run within a Docker container that is not given host networking. Instead, I have configured Avahi running on the host to broadcast the mDNS records for each of these services.

This is based on the solution provided here: https://community.home-assistant.io/t/solved-how-to-configure-avahi-daemon-on-docker-host/356422

Steps to get this working:

  1. Configure a HomeKit bridge in Home Assistant and specify advertise_ip to the host IP.
  2. Run this Python script within the Home Assistant container, a <service-group> will be printed for each discovered service. This doesn't filter for HomeKit records, so it will print any mDNS record being broadcast. If multiple HomeKit devices are defined, each will be printed.
  3. Create a .service file for each record to be broadcasted by Avahi (this is usually stored in /etc/avahi/services.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment