Python zeroconf.Zeroconf() Examples

The following are 30 code examples of zeroconf.Zeroconf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module zeroconf , or try the search function .
Example #1
Source File: BlinkerLinuxWS.py    From blinker-py with MIT License 7 votes vote down vote up
def mDNSinit(type, name):
    deviceType = '_' + type
    desc = {'deviceName': name}
    # desc = {}

    info = ServiceInfo(deviceType + "._tcp.local.",
                       name + "." + deviceType +"._tcp.local.",
                       socket.inet_aton(deviceIP), wsPort, 0, 0,
                       desc, name + ".local.")

    zeroconf = Zeroconf()
    zeroconf.register_service(info)

    # if isDebugAll() is True:
    BLINKER_LOG_ALL('deviceIP: ', deviceIP)
    BLINKER_LOG_ALL('mdns name: ', name)

    BLINKER_LOG('mDNS responder init!') 
Example #2
Source File: Bybop_Discovery.py    From bybop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, deviceId):
        """
        Create and start a researcher for devices on network.

        Arguments:
        - deviceId : List of deviceIds (strings) to search.
        """
        self._zeroconf = Zeroconf()
        self._browser = []
        self._services = {}
        self._lock = threading.RLock()
        self._cond = threading.Condition(self._lock)
        for did in deviceId:
            self._browser.append(ServiceBrowser(self._zeroconf, '_arsdk-' +
                                                str(did) + '._udp.local.',
                                                self)) 
Example #3
Source File: mdns.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def run(self, ttl=None):
        if self.host:
            self.zeroconf = zeroconf.Zeroconf(interfaces=[self.host])
        else:
            self.zeroconf = zeroconf.Zeroconf()
        zeroconf.ServiceBrowser(self.zeroconf, self.domain, MDNSHandler(self))

        if ttl:
            GObject.timeout_add(ttl * 1000, self.shutdown)

        self.__running = True
        self.__mainloop = GObject.MainLoop()
        context = self.__mainloop.get_context()
        try:
            while self.__running:
                if context.pending():
                    context.iteration(True)
                else:
                    time.sleep(0.01)
        except KeyboardInterrupt:
            pass
        self.zeroconf.close()
        logger.info('MDNSListener.run()') 
Example #4
Source File: alexa_auth.py    From AlexaDevice with MIT License 6 votes vote down vote up
def start():
	global localHTTP, zeroconf, info, httpthread
	ip = get_local_address()
	logging.info("Local IP is " + ip)

	desc = {'version': '0.1'}
	info = ServiceInfo("_http._tcp.local.",
			"Alexa Device._http._tcp.local.",
			socket.inet_aton(ip), alexa_params.LOCAL_PORT, 0, 0,
			desc, alexa_params.LOCAL_HOST + ".")
	zeroconf = Zeroconf()
	zeroconf.registerService(info)
	logging.info("Local mDNS is started, domain is " + alexa_params.LOCAL_HOST)
	localHTTP = HTTPServer(("", alexa_params.LOCAL_PORT), alexa_http_config.AlexaConfig)
	httpthread = threading.Thread(target=localHTTP.serve_forever)
	httpthread.start()
	logging.info("Local HTTP is " + alexa_params.BASE_URL)
	alexa_control.start() 
Example #5
Source File: mdns.py    From Sonoff_Devices_DIY_Tools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
        zeroconf = Zeroconf()
        listener = MyListener()
        browser = ServiceBrowser(zeroconf, "_ewelink._tcp.local.",listener= listener)
        while True:
                if listener.all_sub_num>0:
                    dict=listener.all_info_dict.copy()
                    for x in dict.keys():
                        info=dict[x]
                        info=zeroconf.get_service_info(info.type,x)
                        if info!= None:
                            data=info.properties
                            cur_str=x[8:18]+"  "+parseAddress(info.address)+"  "+str(info.port)+"  "   +str(data)
                            print(cur_str)
                if len(listener.all_del_sub)>0:
                        for x in listener.all_del_sub:
                            cur_str=x[8:18]+"\nDEL"
                            print(cur_str)
                time.sleep(0.5) 
Example #6
Source File: _zconf.py    From cloudprint_logocert with Apache License 2.0 6 votes vote down vote up
def __init__(self, logger, wifi_interfaces=[]):
    """Initialization requires a logger.

    Args:
      logger: initialized logger object.
      if_addr: string, interface address for Zeroconf, None means
               all interfaces.
    """
    self.logger = logger
    self.l = _Listener(logger)
    if not wifi_interfaces:
      self.z = Zeroconf()
    else:
      self.z = Zeroconf(wifi_interfaces)
    self.sb = ServiceBrowser(zc=self.z, type_='_privet._tcp.local.',
                             listener=self.l) 
Example #7
Source File: _zconf.py    From cloudprint_logocert with Apache License 2.0 6 votes vote down vote up
def wait_for_service_add(t_seconds, target_service, listener):
  """Wait for a service to be added.

      Args:
        t_seconds: Time to listen for mDNS records, in seconds.
                   Floating point ok.
        service: string, The service to wait for
        listener: _Listener object, the listener to wait on
      Returns:
        If Add event observed, return the Zeroconf information class; otherwise,
        return None
    """
  t_end = time.time() + t_seconds
  while time.time() < t_end:
    services = listener.services()
    for service in services:
      if target_service in service.properties['ty']:
        return service
    time.sleep(1)
  return None 
Example #8
Source File: _zconf.py    From cloudprint_logocert with Apache License 2.0 6 votes vote down vote up
def add_service(self, zeroconf_obj, service_type, name):
    """Callback called by ServiceBrowser when a new mDNS service is discovered.

    Sometimes there is a delay in zeroconf between the add_service callback
    being triggered and the service actually being returned in a call to
    zeroconf_obj.get_service_info().  Because of this there are a few retries.
    Args:
      zeroconf_obj: The Zeroconf class instance.
      service_type: The string name of the service, such
        as '_privet._tcp.local.'.
      name: The name of the service on mDNS.
    """
    self.logger.info('Service added: "%s"', name)
    self.lock.acquire()
    info = zeroconf_obj.get_service_info(service_type, name, timeout=10000)
    retries = 5
    while info is None and retries > 0:
      self.logger.error('zeroconf_obj.get_service_info returned None, forces '
                        'retry.')
      time.sleep(0.1)
      retries -= 1
      info = zeroconf_obj.get_service_info(service_type, name, timeout=10000)
    if info is not None:
      self._added_service_infos.append(copy.deepcopy(info))
    self.lock.release() 
Example #9
Source File: sigmatcp.py    From hifiberry-dsp with MIT License 6 votes vote down vote up
def announce_zeroconf(self):
        desc = {'name': 'SigmaTCP',
                'vendor': 'HiFiBerry',
                'version': hifiberrydsp.__version__}
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except Exception:
            logging.error("can't get IP for hostname %s, "
                          "not initialising Zeroconf",
                          hostname)
            return

        self.zeroconf_info = ServiceInfo(ZEROCONF_TYPE,
                                         "{}.{}".format(
                                             hostname, ZEROCONF_TYPE),
                                         socket.inet_aton(ip),
                                         DEFAULT_PORT, 0, 0, desc)
        self.zeroconf = Zeroconf()
        self.zeroconf.register_service(self.zeroconf_info) 
Example #10
Source File: device_scanner.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def add_service(self, zeroconf, type, name):
        """
        Method required to be a Zeroconf listener. Called by Zeroconf when a "_device._tcp" service
        is registered on the network. Don't call directly.
        
        sample values:
        type = '_device._tcp.local.'
        name = 'DEVICE000._device._tcp.local.'
        """

        
        try:
            info = zeroconf.get_service_info(type, name)

            if info:
                #ip = socket.inet_ntoa(info.address)
                ip = socket.inet_ntoa(info.addresses[0])
                self.add( ip, name )
        
        except Exception as error:
            logging.error("Exception trying to add zeroconf service '"+name+"' of type '"+type+"': "+str(error)) 
Example #11
Source File: server.py    From opendrop with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, config):
        self.config = config

        # Use IPv6
        self.serveraddress = ('::', self.config.port)
        self.ServerClass = HTTPServerV6
        self.ServerClass.allow_reuse_address = False

        self.ip_addr = AirDropUtil.get_ip_for_interface(self.config.interface, ipv6=True)
        if self.ip_addr is None:
            if self.config.interface == 'awdl0':
                raise RuntimeError('Interface {} does not have an IPv6 address. '
                                   'Make sure that `owl` is running.'.format(self.config.interface))
            else:
                raise RuntimeError('Interface {} does not have an IPv6 address'.format(self.config.interface))

        self.Handler = AirDropServerHandler
        self.Handler.config = self.config

        self.zeroconf = Zeroconf(interfaces=[str(self.ip_addr)],
                                 ip_version=IPVersion.V6Only,
                                 apple_p2p=platform.system() == 'Darwin')

        self.http_server = self._init_server()
        self.service_info = self._init_service() 
Example #12
Source File: client.py    From opendrop with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, config):
        self.ip_addr = AirDropUtil.get_ip_for_interface(config.interface, ipv6=True)
        if self.ip_addr is None:
            if config.interface == 'awdl0':
                raise RuntimeError('Interface {} does not have an IPv6 address. '
                                   'Make sure that `owl` is running.'.format(config.interface))
            else:
                raise RuntimeError('Interface {} does not have an IPv6 address'.format(config.interface))

        self.zeroconf = Zeroconf(interfaces=[str(self.ip_addr)],
                                 ip_version=IPVersion.V6Only,
                                 apple_p2p=platform.system() == 'Darwin')

        self.callback_add = None
        self.callback_remove = None
        self.browser = None 
Example #13
Source File: mdnsLocator.py    From fermentrack with MIT License 6 votes vote down vote up
def locate_tiltbridge_services():
    zeroconf_obj = zeroconf.Zeroconf()
    listener = ZeroconfListener()
    browser = zeroconf.ServiceBrowser(zeroconf_obj, "_tiltbridge._tcp.local.", listener)

    sleep(3)  # We have to give zeroconf services time to respond
    zeroconf_obj.close()

    return listener.tiltbridge_services 
Example #14
Source File: discovery.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def start_discovery(callback=None):
    """
    Start discovering chromecasts on the network.

    This method will start discovering chromecasts on a separate thread. When
    a chromecast is discovered, the callback will be called with the
    discovered chromecast's zeroconf name. This is the dictionary key to find
    the chromecast metadata in listener.services.

    This method returns the CastListener object and the zeroconf ServiceBrowser
    object. The CastListener object will contain information for the discovered
    chromecasts. To stop discovery, call the stop_discovery method with the
    ServiceBrowser object.
    """
    listener = CastListener(callback)
    return listener, \
        ServiceBrowser(Zeroconf(), "_googlecast._tcp.local.", listener) 
Example #15
Source File: ServicePublisher.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
def _RegisterService(self, name, ip, port):
        # name: fully qualified service name
        self.service_name = '%s.%s' % (name, service_type)
        self.name = name
        self.port = port

        if ip == "0.0.0.0":
            print("MDNS brodcasted on all interfaces")
            interfaces = zeroconf.InterfaceChoice.All
            ip = self.gethostaddr()
        else:
            interfaces = [ip]

        self.server = zeroconf.Zeroconf(interfaces=interfaces)

        print("MDNS brodcasted service address :" + ip)
        self.ip_32b = socket.inet_aton(ip)

        self.server.register_service(
            zeroconf.ServiceInfo(service_type,
                                 self.service_name,
                                 self.ip_32b,
                                 self.port,
                                 properties=self.serviceproperties))
        self.retrytimer = None 
Example #16
Source File: zeroconf.py    From pyvizio with MIT License 5 votes vote down vote up
def discover(service_type: str, timeout: int = DEFAULT_TIMEOUT) -> List[ZeroconfDevice]:
    """Return all discovered zeroconf services of a given service type over given timeout period."""
    services = []

    def append_service(info: ServiceInfo) -> None:
        """Append discovered zeroconf service to service list."""
        name = info.name[: -(len(info.type) + 1)]
        ip = info.parsed_addresses(IPVersion.V4Only)[0]
        port = info.port
        model = info.properties.get(b"name", "").decode("utf-8")
        id = info.properties.get(b"id")

        # handle id decode for various discovered use cases
        if isinstance(id, bytes):
            try:
                int(id, 16)
            except Exception:
                id = id.hex()
        else:
            id = None

        service = ZeroconfDevice(name, ip, port, model, id)
        services.append(service)

    zeroconf = Zeroconf()
    ServiceBrowser(zeroconf, service_type, ZeroconfListener(append_service))
    time.sleep(timeout)
    zeroconf.close()

    return services 
Example #17
Source File: mdns.py    From HomePWN with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        listener = Listener()
        print("Searching. Press q to stop")
        browser = zeroconf.ServiceBrowser(
            zeroconf.Zeroconf(), self.args["service"], listener)
        key = ""
        while key.lower() != "q":
            key = readchar.readchar()
        browser.cancel()
        print("") 
Example #18
Source File: mdns.py    From Sonoff_Devices_DIY_Tools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, parent=None, **func_task):
        super(mDNS_BrowserThread, self).__init__(parent)
        self.ID_list = []
        self.zeroconf = Zeroconf()
        self.listener = MyListener() 
Example #19
Source File: server.py    From webthing-python with Mozilla Public License 2.0 5 votes vote down vote up
def start(self):
        """Start listening for incoming connections."""
        args = [
            '_webthing._tcp.local.',
            '{}._webthing._tcp.local.'.format(self.name),
        ]
        kwargs = {
            'port': self.port,
            'properties': {
                'path': '/',
            },
            'server': '{}.local.'.format(socket.gethostname()),
        }

        if self.app.is_tls:
            kwargs['properties']['tls'] = '1'

        if sys.version_info.major == 3:
            kwargs['addresses'] = [socket.inet_aton(get_ip())]
        else:
            kwargs['address'] = socket.inet_aton(get_ip())

        self.service_info = ServiceInfo(*args, **kwargs)
        self.zeroconf = Zeroconf()
        self.zeroconf.register_service(self.service_info)

        self.server.listen(self.port)
        tornado.ioloop.IOLoop.current().start() 
Example #20
Source File: DiscoveryPanel.py    From OpenPLC_Editor with GNU General Public License v3.0 5 votes vote down vote up
def RefreshList(self):
        self.ServicesList.DeleteAllItems()
        if self.Browser is not None:
            self.Browser.cancel()
        if self.ZeroConfInstance is not None:
            self.ZeroConfInstance.close()
        self.ZeroConfInstance = Zeroconf()
        self.Browser = ServiceBrowser(self.ZeroConfInstance, service_type, self) 
Example #21
Source File: zeroconf.py    From pyvizio with MIT License 5 votes vote down vote up
def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None:
        """Callback function when zeroconf service is discovered."""
        self._func(zeroconf.get_service_info(type, name)) 
Example #22
Source File: advertise.py    From touchosc2midi with MIT License 5 votes vote down vote up
def __init__(self, ip=None):
        """
        :ip: if string `ip` given, register on given IP
             (if None: default route's IP).
        """
        self.zeroconf = Zeroconf()
        self.info = build_service_info(ip=ip or default_route_interface()) 
Example #23
Source File: mdns.py    From ironic-lib with Apache License 2.0 5 votes vote down vote up
def get_endpoint(service_type):
    """Get an endpoint and its properties from mDNS.

    If the requested endpoint is already in the built-in server cache, and
    its TTL is not exceeded, the cached value is returned.

    :param service_type: OpenStack service type.
    :returns: tuple (endpoint URL, properties as a dict).
    :raises: :exc:`.ServiceLookupFailure` if the service cannot be found.
    """
    with Zeroconf() as zc:
        return zc.get_endpoint(service_type) 
Example #24
Source File: transport.py    From zigate with MIT License 5 votes vote down vote up
def discover_host():
    """
    Automatically discover WiFi ZiGate using zeroconf
    only compatible with WiFi firmware 2.x
    """
    from zeroconf import ServiceBrowser, Zeroconf
    host = None

    def on_service_state_change(zeroconf, service_type, name, state_change):
        pass

    zeroconf = Zeroconf()
    browser = ServiceBrowser(zeroconf, "_zigate._tcp.local.",
                             handlers=[on_service_state_change])
    i = 0
    while not host:
        time.sleep(0.1)
        if browser.services:
            service = list(browser.services.values())[0]
            info = zeroconf.get_service_info(service.name, service.alias)
            host = socket.inet_ntoa(info.address)
        i += 1
        if i > 50:
            break
    zeroconf.close()
    return host 
Example #25
Source File: dsptoolkit.py    From hifiberry-dsp with MIT License 5 votes vote down vote up
def cmd_servers(self):
        if zeroconf_enabled:
            zeroconf = Zeroconf()
            listener = ZeroConfListener()
            ServiceBrowser(zeroconf, ZEROCONF_TYPE, listener)
            print("Looking for devices")
            time.sleep(5)
            zeroconf.close()
            for name, info in listener.devices.items():
                print("{}: {}".format(name, info))
        else:
            print("Zeroconf library not available") 
Example #26
Source File: sigmatcp.py    From hifiberry-dsp with MIT License 5 votes vote down vote up
def run(self):
        if (self.restore):
            try:
                logging.info("restoring saved data memory")
                SigmaTCPHandler.restore_data_memory()
                SigmaTCPHandler.finish_update()
            except IOError:
                logging.info("no saved data found")

        logging.info("announcing via zeroconf")
        try:
            self.announce_zeroconf()
        except Exception as e:
            logging.debug("exception while initialising Zeroconf")
            logging.exception(e)

        logging.debug("done")
        
        logging.info(this.command_after_startup)
        notifier_thread = Thread(target = startup_notify)
        notifier_thread.start()
        
        try:
            if not(self.abort):
                logging.info("starting TCP server")
                self.server.serve_forever()
        except KeyboardInterrupt:
            logging.info("aborting ")
            self.server.server_close()

        if SigmaTCPHandler.alsasync is not None:
            SigmaTCPHandler.alsasync.finish()

        if SigmaTCPHandler.lgsoundsync is not None:
            SigmaTCPHandler.lgsoundsync.finish()

        logging.info("removing from zeroconf")
        self.shutdown_zeroconf()

        logging.info("saving DSP data memory")
        SigmaTCPHandler.save_data_memory() 
Example #27
Source File: smart_module.py    From hapi with GNU General Public License v3.0 5 votes vote down vote up
def find_broker(self, zeroconf):
        """Browser for our (MQTT) services using Zeroconf."""
        browser = ServiceBrowser(zeroconf, "_mqtt._tcp.local.", handlers=[self.find_service]) 
Example #28
Source File: mdns.py    From ironic-lib with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        """Initialize and start the mDNS server."""
        interfaces = (CONF.mdns.interfaces if CONF.mdns.interfaces
                      else zeroconf.InterfaceChoice.All)
        # If interfaces are set, let zeroconf auto-detect the version
        ip_version = None if CONF.mdns.interfaces else zeroconf.IPVersion.All
        self._zc = zeroconf.Zeroconf(interfaces=interfaces,
                                     ip_version=ip_version)
        self._registered = [] 
Example #29
Source File: discovery.py    From openairplay with MIT License 5 votes vote down vote up
def start():
    ZC = zeroconf.Zeroconf()
    listener = AirplayListener()
    browser = zeroconf.ServiceBrowser(ZC, "_airplay._tcp.local.", listener)
    started = True
    if DEBUG:
        print("Listener started.")

# To stop it: 
Example #30
Source File: ZeroConfClient.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def start(self) -> None:
        """The ZeroConf service changed requests are handled in a separate thread so we don't block the UI.

        We can also re-schedule the requests when they fail to get detailed service info.
        Any new or re-reschedule requests will be appended to the request queue and the thread will process them.
        """

        self._service_changed_request_queue = Queue()
        self._service_changed_request_event = Event()
        try:
            self._zero_conf = Zeroconf()
        # CURA-6855 catch WinErrors
        except OSError:
            Logger.logException("e", "Failed to create zeroconf instance.")
            return

        self._service_changed_request_thread = Thread(target = self._handleOnServiceChangedRequests, daemon = True, name = "ZeroConfServiceChangedThread")
        self._service_changed_request_thread.start()
        self._zero_conf_browser = ServiceBrowser(self._zero_conf, self.ZERO_CONF_NAME, [self._queueService])

    # Cleanup ZeroConf resources.