Esempio n. 1
0
    def validate(self, context):
        """
        Component validated
        """
        # Get the framework UID
        self._fw_uid = context.get_property(pelix.constants.FRAMEWORK_UID)

        # Get the host address
        self._address = socket.inet_aton(
            socket.gethostbyname(socket.gethostname()))

        # Prepare Zeroconf
        self._zeroconf = zeroconf.Zeroconf()

        # Register the dispatcher servlet as a service
        self.__register_servlet()

        # Listen to our types
        self._browsers.append(
            zeroconf.ServiceBrowser(self._zeroconf,
                                    ZeroconfDiscovery.DNS_DISPATCHER_TYPE,
                                    self))
        self._browsers.append(
            zeroconf.ServiceBrowser(self._zeroconf, self._rs_type, self))

        _logger.debug("Zeroconf discovery validated")
Esempio n. 2
0
 def __init__(self):
     self.found = []
     if VERBOSE: print('Start mDNS browser for _iotsa._tcp.local.')
     self.zeroconf = zeroconf.Zeroconf()
     self.browsers = []
     self.browsers.append(zeroconf.ServiceBrowser(self.zeroconf, "_iotsa._tcp.local.", self))
     self.browsers.append(zeroconf.ServiceBrowser(self.zeroconf, "_iotsa._http._tcp.local.", self))
     self.browsers.append(zeroconf.ServiceBrowser(self.zeroconf, "_iotsa._https._tcp.local.", self))
     self.browsers.append(zeroconf.ServiceBrowser(self.zeroconf, "_iotsa._coap._tcp.local.", self))
Esempio n. 3
0
def _locate_ha() -> Optional[str]:

    _zeroconf = zeroconf.Zeroconf()
    listener = _ZeroconfListener()
    zeroconf.ServiceBrowser(_zeroconf, "_home-assistant._tcp.local.", listener)
    try:
        import time

        retries = 0
        while not listener.services and retries < 5:
            _LOGGING.info(
                "Trying to locate Home Assistant on local network...")
            time.sleep(0.5)
            retries = retries + 1
    finally:
        _zeroconf.close()

    if listener.services:
        if len(listener.services) > 1:
            _LOGGING.warning(
                "Found multiple Home Assistants at %s",
                ", ".join(listener.services),
            )
            _LOGGING.warning("Use --server to explicitly specify one.")
            return None

        _, service = listener.services.popitem()
        base_url = service.properties[b'base_url'].decode('utf-8')
        _LOGGING.info("Found and using %s as server", base_url)
        return cast(str, base_url)

    _LOGGING.warning(
        "Found no Home Assistant on local network. Using defaults.")
    return None
Esempio n. 4
0
def look_for(service_name, timeout=None, get_many=True, type_="_http._tcp.local."):
    services = []
    Added = zeroconf.ServiceStateChange.Added # stupid but necessary

    # semaphore used for synchronization
    # listen for just first one, or for many until timeout
    handler_done = multiprocessing.Event()

    def on_service_state_change(zeroconf, service_type, name, state_change):
        nonlocal services, handler_done
        if state_change is Added:
            info = zeroconf.get_service_info(service_type, name)
            if name.startswith(service_name):
                address = socket.inet_ntoa(info.address)
                port = info.port
                if get_many or len(services)==0:
                    services.append([name, address, port])
                if not get_many:
                    handler_done.set()

    # register a listner for zeroconf events
    zc = zeroconf.Zeroconf()
    zeroconf.ServiceBrowser(zc, type_=type_, handlers=[on_service_state_change])

    # wait until the listener found what we are looking for
    handler_done.wait(timeout)
    zc.close()
    return services
Esempio n. 5
0
def device_scan(hosts, action, do_all, dry_run, silent_run, mode, exclude,
                version, variant, stock_release_info, homekit_release_info):
    logger.debug(f"\n{WHITE}device_scan{NC}")
    logger.debug(f"devices: {hosts}")
    logger.debug(f"action: {action}")
    logger.debug(f"do_all: {do_all}")
    logger.debug(f"dry_run: {dry_run}")
    logger.debug(f"silent_run: {silent_run}")
    logger.debug(f"mode: {mode}")
    logger.debug(f"exclude: {exclude}")
    logger.debug(f"version: {version}")
    logger.debug(f"variant: {variant}")

    if not do_all:
        device_list = []
        logger.info(f"{WHITE}Probing Shelly device for info...\n{NC}")
        for host in hosts:
            info = get_info(host)
            if info is not None:
                device_list.append(info)
    else:
        logger.info(f"{WHITE}Scanning for Shelly devices...\n{NC}")
        zc = zeroconf.Zeroconf()
        listener = MyListener()
        browser = zeroconf.ServiceBrowser(zc, '_http._tcp.local.', listener)
        time.sleep(10)
        zc.close()
        device_list = listener.device_list
    sorted_device_list = sorted(device_list, key=lambda k: k['host'])
    logger.trace(f"device_test: {sorted_device_list}")
    # logger.debug(f"\nproperties: {listener.p_list}")
    for device in sorted_device_list:
        parse_info(device, action, dry_run, silent_run, mode, exclude, version,
                   variant, stock_release_info, homekit_release_info)
Esempio n. 6
0
    def announce(self, infohash, peerid):
        discovery_logger.info("announcing: %s", infohash)

        # old
        #service_name = "_BitTorrent-%s._tcp.local." % infohash
        #service_type = service_name

        service_name = "%s._%s" % (peerid, infohash)
        service_type = "_bittorrent._tcp.local."

        browser = zeroconf.ServiceBrowser(self.server, service_type, None,
                                          self)

        service = zeroconf.ServiceInfo(
            service_type,
            "%s.%s" % (service_name, service_type),
            address=None,  # to be filled in later
            port=self.port,
            weight=0,
            priority=0,
            properties={})
        service.browser = browser
        service.registered = False
        self.services.append(service)

        df = get_deferred_host_ip()
        df.addCallback(self._announce2, service)
        return service
Esempio n. 7
0
def start_discovery(add_callback=None, remove_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(add_callback, remove_callback)
    service_browser = False
    try:
        service_browser = zeroconf.ServiceBrowser(
            zeroconf.Zeroconf(), "_googlecast._tcp.local.", listener
        )
    except (
        zeroconf.BadTypeInNameException,
        NotImplementedError,
        OSError,
        socket.error,
        zeroconf.NonUniqueNameException,
    ):
        pass

    return listener, service_browser
Esempio n. 8
0
    def start(self):
        """ Starts discovery. """
        self.zeroconf = zeroconf.Zeroconf()

        for service in self.services:
            self._browsers.append(
                zeroconf.ServiceBrowser(self.zeroconf, service.typ, service))
Esempio n. 9
0
def device_scan(hosts, action, do_all, dry_run, silent_run, mode, exclude, version, variant, stock_release_info, homekit_release_info):
  ffw = version
  logger.debug(f"\n{WHITE}device_scan{NC}")
  logger.debug(f"hosts: {hosts}")
  logger.debug(f"action: {action}")
  logger.debug(f"do_all: {do_all}")
  logger.debug(f"dry_run: {dry_run}")
  logger.debug(f"silent_run: {silent_run}")
  logger.debug(f"mode: {mode}")
  logger.debug(f"exclude: {exclude}")
  logger.debug(f"version: {version}")
  logger.debug(f"variant: {variant}")
  logger.debug(f"ffw: {ffw}")
  if not do_all:
    for device in hosts:
      logger.info(f"{WHITE}Probing Shelly device for info...\n{NC}")
      if not '.local' in device:
        device = device + '.local'
      probe_info(device, action, dry_run, silent_run, mode, exclude, version, variant, stock_release_info, homekit_release_info)
  else:
    logger.info(f"{WHITE}Scanning for Shelly devices...\n{NC}")
    zc = zeroconf.Zeroconf()
    listener = MyListener()
    browser = zeroconf.ServiceBrowser(zc, '_http._tcp.local.', listener)
    time.sleep(5)
    zc.close()
    logger.debug(f"device_test: {listener.device_list}")
    # logger.debug(f"\nproperties: {listener.p_list}")
    listener.device_list.sort()
    for device in listener.device_list:
      probe_info(device + '.local', action, dry_run, silent_run, mode, exclude, version, variant, stock_release_info, homekit_release_info)
Esempio n. 10
0
 def run_zeroconf(self):
     if not ZEROCONF_AVAILABLE:
         return
     self.zeroconf = zeroconf.Zeroconf()
     self.zeroconf.listener = self
     self.browser = zeroconf.ServiceBrowser(self.zeroconf,
                                            self.service_type, self)
Esempio n. 11
0
    def scan(self) -> List[str]:
        """ Look for TiVos using Zeroconf. """
        VIDS = "_tivo-videos._tcp.local."
        names: List[str] = []

        LOGGER.info("Scanning for TiVos...")

        # Get the names of servers offering TiVo videos
        _ = zeroconf.ServiceBrowser(self.rz, VIDS, listener=ZCListener(names))

        # Give them a second to respond
        time.sleep(1)

        # any results?
        if names:
            pytivo.config.TIVOS_FOUND = True

        # Now get the addresses -- this is the slow part
        for name in names:
            info = self.rz.get_service_info(VIDS, name + "." + VIDS)
            if info:
                tsn = tsn_from_service_info(info)
                if tsn is not None:
                    address = socket.inet_ntoa(info.address)
                    port = info.port
                    pytivo.config.TIVOS[tsn] = Bdict({
                        "name": name,
                        "address": address,
                        "port": port
                    })
                    pytivo.config.TIVOS[tsn].update(info.properties)
                    LOGGER.info(name)

        return names
Esempio n. 12
0
    def __init__(self):
        self.zc = zeroconf.Zeroconf()
        self.info_entries = []

        self.our_ip = None
        self.browser = zeroconf.ServiceBrowser(self.zc, "_apt_proxy._tcp.local.", self)
        self.service_ip_ports_by_name = {}
 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)
Esempio n. 14
0
 def __init__(self, protocol = '_pyme-pyro'):
     self._protocol = protocol
     self._services = {}
     self.zc = zeroconf.Zeroconf()
     self.listener = ZCListener(self._protocol)
     
     self.browser = zeroconf.ServiceBrowser(self.zc, "%s._tcp.local." % self._protocol,
                                            self.listener) 
Esempio n. 15
0
        def browse():
            listener = ZeroconfListener(self._logger)
            browser = zeroconf.ServiceBrowser(self._zeroconf, service_type, listener)
            time.sleep(browse_timeout)
            browser.cancel()

            if callback:
                callback(result)
            result_available.set()
Esempio n. 16
0
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
Esempio n. 17
0
 def query(self):
     self.zc = zeroconf.Zeroconf()
     self.br = zeroconf.ServiceBrowser(self.zc, self.svc_type, self)
     for i in range(50):
         if self._address:
             self.br.cancel()
             return self._address, self._model
         time.sleep(0.1)
     logger.error("No scanner found in 5 sec")
Esempio n. 18
0
def device_scan(hosts, action, dry_run, quiet_run, silent_run, mode, exclude,
                version, variant, hap_setup_code):
    if hosts:
        for host in hosts:
            logger.debug(f"")
            logger.debug(f"{PURPLE}[Device Scan] manual{NC}")
            deviceinfo = Device(host)
            deviceinfo.get_device_info()
            if deviceinfo.fw_type is not None:
                device = {
                    'host': deviceinfo.host,
                    'wifi_ip': deviceinfo.wifi_ip,
                    'fw_type': deviceinfo.fw_type,
                    'device_url': deviceinfo.device_url,
                    'info': deviceinfo.info
                }
                probe_device(device, action, dry_run, quiet_run, silent_run,
                             mode, exclude, version, variant, hap_setup_code)
    else:
        logger.debug(f"{PURPLE}[Device Scan] automatic scan{NC}")
        logger.info(f"{WHITE}Scanning for Shelly devices...{NC}")
        zc = zeroconf.Zeroconf()
        listener = MyListener()
        browser = zeroconf.ServiceBrowser(zc, '_http._tcp.local.', listener)
        total_devices = 0
        while True:
            try:
                deviceinfo = listener.queue.get(timeout=20)
            except queue.Empty:
                logger.info(f"")
                if action == 'flash':
                    logger.info(
                        f"{GREEN}Devices found: {total_devices} Upgradeable: {upgradeable_devices} Flashed: {flashed_devices} Failed: {failed_flashed_devices}{NC}"
                    )
                else:
                    logger.info(
                        f"{GREEN}Devices found: {total_devices} Upgradeable: {upgradeable_devices}{NC}"
                    )
                if args.log_filename:
                    logger.info(f"Log file created: {args.log_filename}")
                zc.close()
                break
            logger.debug(f"")
            logger.debug(f"{PURPLE}[Device Scan] action queue entry{NC}")
            deviceinfo.get_device_info()
            if deviceinfo.fw_type is not None:
                device = {
                    'host': deviceinfo.host,
                    'wifi_ip': deviceinfo.wifi_ip,
                    'fw_type': deviceinfo.fw_type,
                    'device_url': deviceinfo.device_url,
                    'info': deviceinfo.info
                }
                total_devices += 1
                probe_device(device, action, dry_run, quiet_run, silent_run,
                             mode, exclude, version, variant, hap_setup_code)
Esempio n. 19
0
    def __init__(self):
        super().__init__()
        self._zeroconf = zeroconf.Zeroconf()
        self._browser = None
        self._items = []

        self._added.connect(self._onAdded)
        self._removed.connect(self._onRemoved)
        self._browser = zeroconf.ServiceBrowser(self._zeroconf,
                                                '_http._tcp.local.', self)
Esempio n. 20
0
 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("")
Esempio n. 21
0
def discover_devices(
    models_list: Optional[List[str]] = None,
    max_devices: int = None,
    timeout: int = DISCOVER_TIMEOUT,
    zeroconf_instance=None,
):
    # pylint: disable=unused-argument
    _LOGGER.debug("Discovering devices...")
    _LOGGER.debug("Importing zeroconf...")
    import zeroconf

    def callback():
        """Called when zeroconf has discovered a new chromecast."""
        if max_devices is not None and listener.count >= max_devices:
            discover_complete.set()

    _LOGGER.debug("Creating new Event for discovery completion...")
    discover_complete = Event()
    _LOGGER.debug("Creating new CastListener...")
    listener = CastListener(callback)
    if not zeroconf_instance:
        _LOGGER.debug("Creating new Zeroconf instance")
        zconf = zeroconf.Zeroconf()
    else:
        _LOGGER.debug("Using attribute Zeroconf instance")
        zconf = zeroconf_instance
    _LOGGER.debug(
        "Creating zeroconf service browser for _googlecast._tcp.local.")
    zeroconf.ServiceBrowser(zconf, "_googlecast._tcp.local.", listener)

    # Wait for the timeout or the maximum number of devices
    _LOGGER.debug("Waiting for discovery completion...")
    discover_complete.wait(timeout)

    devices = []
    _LOGGER.debug("Got {} devices. Iterating...".format(len(listener.devices)))
    for service in listener.devices:
        model = service[0]
        name = service[1]
        ip = service[2]
        access_port = service[3]
        if not models_list or model in models_list:
            _LOGGER.debug(
                "Appending new device. name: %s, ip: %s, port: %s, model: %s",
                name,
                ip,
                access_port,
                model,
            )
            devices.append(GoogleDevice(name, ip, int(access_port), model))
        else:
            _LOGGER.debug(
                'Won\'t add device since model "{}" is not in models_list'.
                format(model))
    return devices
Esempio n. 22
0
    def discover_mdns():
        _LOGGER.info("Discovering devices with mDNS, press any key to quit...")

        listener = Listener()
        browser = zeroconf.ServiceBrowser(zeroconf.Zeroconf(),
                                          "_miio._udp.local.", listener)

        input()  # to keep execution running until a key is pressed
        browser.cancel()

        return listener.found_devices
Esempio n. 23
0
 def __call__(self, getter, putter):
     zc = zeroconf.Zeroconf()
     try:
         browser = zeroconf.ServiceBrowser(
             zc,
             self.service_type,
             Listener(putter),
         )
         browser.join()
     finally:
         zc.close()
Esempio n. 24
0
    def _run(self):
        ''' starts the server
		'''
        self.browser = zeroconf.ServiceBrowser(self.zeroconf,
                                               "_xbmc-jsonrpc._tcp.local.",
                                               self)
        while self.runFlag:
            time.sleep(2)
            with self.lock:
                for device_friendly_name in self.devices:
                    self.send_device_play_status(device_friendly_name, False)
Esempio n. 25
0
 async def find_wled_devices(self):
     #Scan the LAN network that match WLED using zeroconf - Multicast DNS Service Discovery Library
     _LOGGER.info("Scanning for WLED devices...")
     zeroconf_obj = zeroconf.Zeroconf()
     listener = MyListener(self._ledfx)
     browser = zeroconf.ServiceBrowser(zeroconf_obj, "_wled._tcp.local.", listener)
     try:
         await asyncio.sleep(10)
     finally:
         _LOGGER.info("Scan Finished")
         zeroconf_obj.close()
Esempio n. 26
0
 def __enter__(self):
     zeroconf.ServiceBrowser(
         self._zc,
         [
             "_http._tcp.local.",
             "_hap._tcp.local.",
             "_services._dns-sd._udp.local.",
         ],
         self,
     )
     return self
Esempio n. 27
0
    def start(self):
        """Start discovery."""
        try:
            self.zeroconf = zeroconf.Zeroconf()

            for service in self.services:
                self._browsers.append(
                    zeroconf.ServiceBrowser(self.zeroconf, service.typ,
                                            service))
        except Exception:  # pylint: disable=broad-except
            self.stop()
            raise
Esempio n. 28
0
 def __init__(self, explicit=None):
     self.zc = zeroconf.Zeroconf()
     self.browser = zeroconf.ServiceBrowser(self.zc,
                                            "_machinekit._tcp.local.", self)
     self.instance = {}
     self.explicit = explicit if explicit else MachinekitPreferences.restServers(
     )
     self.lock = threading.Lock()
     self.thread = threading.Thread(target=serviceThread,
                                    args=(self, ),
                                    daemon=True)
     self.thread.start()
Esempio n. 29
0
 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("")
Esempio n. 30
0
    def run_zeroconf(self):
        """Starts :class:`zeroconf.Zeroconf` and :class:`zeroconf.ServiceBrowser` instances

        This is meant to be called inside of an :class:`concurrent.futures.Executor`
        and not used directly.

        """
        if not ZEROCONF_AVAILABLE:
            return
        self.zeroconf = zeroconf.Zeroconf()
        self.zeroconf.listener = self
        self.browser = zeroconf.ServiceBrowser(self.zeroconf, self.service_type, self)