How to use zeroconf - 10 common examples

To help you get started, we’ve selected a few zeroconf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github home-assistant / home-assistant / tests / components / zeroconf / test_init.py View on Github external
def service_update_mock(zeroconf, service, handlers):
    """Call service update handler."""
    handlers[0](
        zeroconf, service, "{}.{}".format("name", service), ServiceStateChange.Added
    )
github bitcraft / tailor / tailor / test_zc.py View on Github external
def on_service_state_change(zeroconf, service_type, name, state_change):
    print("Service %s of type %s state changed: %s" % (
        name, service_type, state_change))

    if state_change is ServiceStateChange.Added:
        info = zeroconf.get_service_info(service_type, name)
        if info:
            print("  Address: %s:%d" % (
                socket.inet_ntoa(info.address), info.port))
            print("  Weight: %d, priority: %d" % (info.weight, info.priority))
            print("  Server: %s" % (info.server,))
            if info.properties:
                print("  Properties are:")
                for key, value in info.properties.items():
                    print("    %s: %s" % (key, value))
            else:
                print("  No properties")
        else:
            print("  No info")
        print('\n')
github xoseperez / espurna / code / ota.py View on Github external
def discover_devices(args):
    # Look for services and try to immediatly print the device when it is discovered
    # (unless --sort  is specified, then we will wait until discovery finishes
    listener = Listener(print_when_discovered=not args.sort)

    try:
        browser = zeroconf.ServiceBrowser(
            zeroconf.Zeroconf(), "_arduino._tcp.local.", listener
        )
    except (
        zeroconf.BadTypeInNameException,
        NotImplementedError,
        OSError,
        socket.error,
        zeroconf.NonUniqueNameException,
    ) as exc:
        print("! error when creating service discovery browser: {}".format(exc))
        sys.exit(1)

    try:
        time.sleep(args.timeout)
    except KeyboardInterrupt:
        sys.exit(1)
github ChainsAutomation / chains / lib / chains / services / publish / __init__.py View on Github external
def onInit(self):
        log.info('Zeroconf publish init')
        self.ip_addr = self._get_ip()
        self.hostname = socket.gethostname()
        self.services = []
        self.desc = {'Description': 'Chains Home Automation service on rabbitmq'}
        self.amqp_info = ServiceInfo("_amqp._tcp.local.",
                                     "Chains Master AMQP %s._amqp._tcp.local." % self.hostname,
                                     socket.inet_aton(self.ip_addr), 5672, 0, 0,
                                     self.desc, "%s.local." % self.hostname)
        self.service.append(self.amqp_info)
        self.zeroconf = Zeroconf()
github tivoguy / TiVoToGo.bundle / Contents / Code / __init__.py View on Github external
class ZCListener:
        def __init__(self, names):
            self.names = names

        def removeService(self, server, type, name):
            self.names.remove(name)

        def addService(self, server, type, name):
            self.names.append(name)

    REMOTE = '_tivo-videos._tcp.local.'
    tivo_names = []

    # Get the names of TiVos offering network remote control
    try:
        serv = zeroconf.Zeroconf()
        browser = zeroconf.ServiceBrowser(serv, REMOTE, ZCListener(tivo_names))
    except Exception, e:
        Log("Error staring Zero Conf: %s" % e)
        return oc

    # Give them a second to respond
    sleep(0.7)

    # For proxied TiVos, remove the original and any black listed tivos
    browseblacklist = (Prefs['browseblacklist'] or "").split(",")
    for t in tivo_names[:]:
        if t.split(".")[0] in browseblacklist:
            tivo_names.remove(t)
            continue
        if t.startswith('Proxy('):
            try:
github rmst / yoke / yoke / service.py View on Github external
0, 0, 0, # 3 unused LONGs
                *self.axes, # 8 LONGs for axes and 7 unused LONGs
                self.buttons & 0xffffffff, # 1 LONG for buttons
                0, 0, 0, 0, # 4 DWORDs for hats
                (self.buttons >> 32) & 0xffffffff,
                (self.buttons >> 64) & 0xffffffff,
                (self.buttons >> 96) & 0xffffffff # 3 LONGs for buttons
            ))
            
            # This allows a very simple emit() definition:
            self.buttons = 0
        def close(self):
            self.device.close()


zeroconf = Zeroconf()


# Webserver to serve files to android client
from http.server import HTTPServer, SimpleHTTPRequestHandler
from threading import Thread
import socketserver
import os, urllib, posixpath

# TODO: These three lines allow using the syntax with socketserver with
# old versions of Python like in Debian.
# Please delete once socketserver.py is updated in every major Linux distro.
if not "__enter__" in dir(socketserver.BaseServer):
    socketserver.BaseServer.__enter__ = lambda self: self
    socketserver.BaseServer.__exit__ = lambda self, *args: self.server_close()

class HTTPRequestHandler(SimpleHTTPRequestHandler):
github Ultimaker / Cura / plugins / UM3NetworkPrinting / NetworkPrinterOutputDevicePlugin.py View on Github external
def startDiscovery(self):
        self.stop()
        if self._browser:
            self._browser.cancel()
            self._browser = None
            self._old_printers = [printer_name for printer_name in self._printers]
            self._printers = {}
            self.printerListChanged.emit()
        # After network switching, one must make a new instance of Zeroconf
        # On windows, the instance creation is very fast (unnoticable). Other platforms?
        self._zero_conf = Zeroconf()
        self._browser = ServiceBrowser(self._zero_conf, u'_ultimaker._tcp.local.', [self._appendServiceChangedRequest])

        # Look for manual instances from preference
        for address in self._manual_instances:
            if address:
                self.addManualPrinter(address)
github Ultimaker / Cura / plugins / UM3NetworkPrinting / NetworkPrinterOutputDevicePlugin.py View on Github external
if not info.address:
                Logger.log("d", "Trying to get address of %s", name)
                info = zeroconf.get_service_info(service_type, name)

            if info:
                type_of_device = info.properties.get(b"type", None)
                if type_of_device:
                    if type_of_device == b"printer":
                        address = '.'.join(map(lambda n: str(n), info.address))
                        self.addPrinterSignal.emit(str(name), address, info.properties)
                    else:
                        Logger.log("w", "The type of the found device is '%s', not 'printer'! Ignoring.." % type_of_device )
            else:
                Logger.log("w", "Could not get information about %s" % name)

        elif state_change == ServiceStateChange.Removed:
            Logger.log("d", "Bonjour service removed: %s" % name)
            self.removePrinterSignal.emit(str(name))
github probonopd / WirelessPrinting / WirelessPrintOutputDevicePlugin.py View on Github external
# Request more data if info is not complete
            if not info.address or not info.port:
                Logger.log("d", "Trying to get address of %s", name)
                info = zeroconf.get_service_info(service_type, key)

                if not info:
                    Logger.log("w", "Could not get information about %s" % name)
                    return

            if info.address and info.port:
                address = '.'.join(map(lambda n: str(n), info.address))
                self.addInstanceSignal.emit(name, address, info.port, info.properties)
            else:
                Logger.log("d", "Discovered instance named %s but received no address", name)

        elif state_change == ServiceStateChange.Removed:
            self.removeInstanceSignal.emit(str(name))
github Pack3tL0ss / ConsolePi / venv / lib / python3.5 / site-packages / consolepi / mdns_browse.py View on Github external
def on_service_state_change(self,
        zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange) -> None:
        mdns_data = None
        log = self.log
        if state_change is ServiceStateChange.Added:
            info = zeroconf.get_service_info(service_type, name)
            if info:
                if info.server.split('.')[0] != HOSTNAME:
                    if __name__ == '__main__':
                        print("Server: %s Added" % (info.server.split('.')[0],))
                    else:
                        log.info('ConsolePi: {} Discovered via mdns'.format(info.server.split('.')[0]))
                    if info.properties:
                        properties = info.properties
                        hostname = properties[b'hostname'].decode("utf-8")
                        user = properties[b'user'].decode("utf-8")
                        interfaces = json.loads(properties[b'interfaces'].decode("utf-8"))
                        adapters = json.loads(properties[b'adapters'].decode("utf-8"))
                        mdns_data = {hostname: {'interfaces': interfaces, 'adapters': adapters, 'user': user}}
                        if __name__ == '__main__':
                            for key, value in info.properties.items():