Python zeroconf.ServiceBrowser() Examples

The following are 26 code examples of zeroconf.ServiceBrowser(). 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: 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 #2
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 #3
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 #4
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 #5
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 #6
Source File: _zconf.py    From cloudprint_logocert with Apache License 2.0 6 votes vote down vote up
def _find_zeroconf_threads():
  """Find all living threads that were started by zeroconf.

  Returns:
    List of thread objects started by zeroconf that are currently alive
    according to threading.enumerate().
  """
  def is_zeroconf_thread(thread):
    zeroconf_thread_objs = [
        zeroconf.Engine,
        zeroconf.Reaper,
        zeroconf.ServiceBrowser
    ]
    for obj in zeroconf_thread_objs:
      if isinstance(thread, obj):
        return True
    return False
  zeroconf_threads = filter(is_zeroconf_thread, threading.enumerate())
  return zeroconf_threads


# pylint: disable=dangerous-default-value
# The default case, [] is explicitly handled, and common. 
Example #7
Source File: Bybop_Discovery.py    From bybop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_service(self, zeroconf, type, name):
        """ Internal function for zeroconf.ServiceBrowser. """
        info = zeroconf.get_service_info(type, name)
        if info is not None:
            self._services[name] = info
            self._signal_change()
        else:
            print('Found a service witout info : ' + name + '. Stopping !')
            self.stop() 
Example #8
Source File: Bybop_Discovery.py    From bybop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def remove_service(self, zeroconf, type, name):
        """ Internal function for zeroconf.ServiceBrowser. """
        if name in self._services:
            del self._services[name]
            self._signal_change() 
Example #9
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 #10
Source File: client.py    From opendrop with GNU General Public License v3.0 5 votes vote down vote up
def start(self, callback_add=None, callback_remove=None):
        """
        Start the AirDropBrowser to discover other AirDrop devices
        """
        if self.browser is not None:
            return  # already started
        self.callback_add = callback_add
        self.callback_remove = callback_remove
        self.browser = ServiceBrowser(self.zeroconf, '_airdrop._tcp.local.', self) 
Example #11
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 #12
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 #13
Source File: xiaomi-devices-passive.py    From HomePWN with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        listener = Listener()
        try:
            timeout = int(self.args["timeout"])
        except:
            timeout = 5
        print(f"Searching Xiaomi devices. Timeout: {timeout} seconds")
        browser = zeroconf.ServiceBrowser(zeroconf.Zeroconf(), "_miio._udp.local.", listener)
        sleep(timeout)
        browser.cancel()
        print("") 
Example #14
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 #15
Source File: device_scanner.py    From ethoscope with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        # Use self as the listener class because I have add_service and remove_service methods
        self.browser = ServiceBrowser(self._zeroconf, self._service_type, self) 
Example #16
Source File: device_scanner.py    From ethoscope with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        # Use self as the listener class because I have add_service and remove_service methods
        self.browser = ServiceBrowser(self._zeroconf, self._service_type, self) 
Example #17
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 #18
Source File: workers.py    From airrohr-firmware-flasher with MIT License 5 votes vote down vote up
def target(self):
        """This thread scans for Bonjour/mDNS devices and emits
        deviceDiscovered signal with its name, address and info object"""
        self.zc = zeroconf.Zeroconf()
        self.browser = zeroconf.ServiceBrowser(
            self.zc, "_http._tcp.local.", handlers=[self.on_state_change])
        while True:
            time.sleep(0.5) 
Example #19
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. 
Example #20
Source File: ZeroConfClient.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self) -> None:
        self._zero_conf = None  # type: Optional[Zeroconf]
        self._zero_conf_browser = None  # type: Optional[ServiceBrowser]
        self._service_changed_request_queue = None  # type: Optional[Queue]
        self._service_changed_request_event = None  # type: Optional[Event]
        self._service_changed_request_thread = None  # type: Optional[Thread] 
Example #21
Source File: mdnsLocator.py    From fermentrack with MIT License 5 votes vote down vote up
def locate_brewpi_services():
    zeroconf_obj = zeroconf.Zeroconf()
    listener = zeroconfListener()
    browser = zeroconf.ServiceBrowser(zeroconf_obj, "_brewpi._tcp.local.", listener)

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

    return listener.brewpi_services 
Example #22
Source File: _zconf.py    From cloudprint_logocert with Apache License 2.0 4 votes vote down vote up
def Wait_for_privet_mdns_service(t_seconds, service, logger,
                                 wifi_interfaces=[]):
  """Listens for t_seconds and returns an information object for each service.

  This is the primary interface to discover mDNS services.  It blocks for
  t_seconds while listening, and returns a list of information objects, one
  for each service discovered.
  Args:
    t_seconds: Time to listen for mDNS records, in seconds.  Floating point ok.
    service: The service to wait for, if found, return early
    is_add: If True, wait for service to be added
            If False, wait for service to be removed
    wifi_interfaces: The interfaces to listen on as strings, if empty listen on
      all interfaces.  For example: ['192.168.1.2'].
  Returns:
    If Add event observed, return the Zeroconf information class;
    otherwise, return None
  """
  l = _Listener(logger)
  if not wifi_interfaces:
    z = Zeroconf()
  else:
    z = Zeroconf(wifi_interfaces)

  sb = ServiceBrowser(zc=z, type_='_privet._tcp.local.', listener=l)
  service_info = wait_for_service_add(t_seconds, service, l)
  sb.cancel()

  # Only method available to kill all threads pylint: disable=protected-access
  z._GLOBAL_DONE = True
  zeroconf_threads = _find_zeroconf_threads()

  # Wait up to 30 seconds for zeroconf to terminate its threads
  t_end = time.time() + 30
  while len(zeroconf_threads) > 1 and time.time() < t_end:
    time.sleep(0.01)
    zeroconf_threads = _find_zeroconf_threads()
  z.close()

  if len(zeroconf_threads) > 1:
    logger.info('Zeroconf failed to terminate its threads in 30 seconds.')
  else:
    logger.info('All listeners have been stopped.')
  return service_info
# pylint: enable=dangerous-default-value 
Example #23
Source File: discovery.py    From chromecast-mqtt-connector with Mozilla Public License 2.0 4 votes vote down vote up
def run(self):
        zeroconf = Zeroconf()
        browser = ServiceBrowser(zeroconf, GOOGLE_CAST_IDENTIFIER, self)

        try:
            with self.run_condition:
                self.run_condition.wait()

            self.logger.debug("end of run-body (discovery)")

        finally:
            browser.cancel()
            zeroconf.close() 
Example #24
Source File: wifiConnection.py    From pyparrot with MIT License 4 votes vote down vote up
def connect(self, num_retries):
        """
        Connects to the drone

        :param num_retries: maximum number of retries

        :return: True if the connection succeeded and False otherwise
        """

        if (self.ip_address is None) and ("Mambo" not in self.drone_type):
            print("Setting up mDNS listener since this is not a Mambo")
            #parrot's latest mambo firmware (3.0.26 broke all of the mDNS services so this is (temporarily) commented
            #out but it is backwards compatible and will work with the hard-coded addresses for now.
            zeroconf = Zeroconf()
            listener = mDNSListener(self)

            print("Making a browser for %s" % self.mdns_address)

            browser = ServiceBrowser(zeroconf, self.mdns_address , listener)

            # basically have to sleep until the info comes through on the listener
            num_tries = 0
            while (num_tries < num_retries and not self.is_connected):
                time.sleep(1)
                num_tries += 1

            # if we didn't hear the listener, return False
            if (not self.is_connected):
                color_print("connection failed: did you remember to connect your machine to the Drone's wifi network?", "ERROR")
                return False
            else:
                browser.cancel()

        # perform the handshake and get the UDP info
        handshake = self._handshake(num_retries)
        if (handshake):
            self._create_udp_connection()
            self.listener_thread = threading.Thread(target=self._listen_socket)
            self.listener_thread.start()

            color_print("Success in setting up the wifi network to the drone!", "SUCCESS")
            return True
        else:
            color_print("Error: TCP handshake failed.", "ERROR")
            return False 
Example #25
Source File: mdnsLocator.py    From fermentrack with MIT License 4 votes vote down vote up
def locate_brewpi_services():
    zeroconf_obj = zeroconf.Zeroconf()
    listener = zeroconfListener()
    browser = zeroconf.ServiceBrowser(zeroconf_obj, "_brewpi._tcp.local.", listener)

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

    return listener.brewpi_services 
Example #26
Source File: airplay.py    From HomeAssistant_Components with Apache License 2.0 4 votes vote down vote up
def discover_MediaPlayer(self, timeout=10, fast=False):
        """
        find airPlay devices
        """

        # this will be our list of devices
        devices = []

        # zeroconf will call this method when a device is found
        def on_service_state_change(zeroconf, service_type, name, state_change):
            if state_change is ServiceStateChange.Added:
                info = zeroconf.get_service_info(service_type, name)
                if info is None:
                    return
                try:
                    name, _ = name.split('.', 1)
                except ValueError:
                    pass

                address = socket.inet_ntoa(info.address)

                devices.append(
                    {
                        "name":name,
                        "address":address,
                        "port":info.port
                    }
                )
            elif state_change is ServiceStateChange.Removed :
                pass

        # search for AirPlay devices
        try:
            zeroconf = Zeroconf()
            browser = ServiceBrowser(zeroconf, "_airplay._tcp.local.", handlers=[on_service_state_change])  # NOQA
        except NameError:
            warnings.warn(
                'AirPlay.find() requires the zeroconf package but it could not be imported. '
                'Install it if you wish to use this method. https://pypi.python.org/pypi/zeroconf',
                stacklevel=2
            )
            return None
        time.sleep(5)
        zeroconf.close()
        return devices