Python zeroconf.ServiceInfo() Examples

The following are 13 code examples of zeroconf.ServiceInfo(). 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: 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 #3
Source File: controller.py    From PrusaControl with GNU General Public License v3.0 6 votes vote down vote up
def add_service(self, zeroconf, type, name):
        info = zeroconf.get_service_info(type, name)
        print("Service %s added, service info: %s" % (name, info))

        # Try zeroconf cache first
        info = ServiceInfo(type, name, properties = {})
        for record in zeroconf.cache.entries_with_name(name.lower()):
            info.update_record(zeroconf, time.time(), record)
        for record in zeroconf.cache.entries_with_name(info.server):
            info.update_record(zeroconf, time.time(), record)
            if info.address and info.address[:2] != b'\xa9\xfe': # 169.254.x.x addresses are self-assigned; reject them
                break
        # Request more data if info from cache is not complete
        if not info.address or not info.port:
            info = zeroconf.get_service_info(type, name)
            if not info:
                print("Could not get information about %s" % name)
                return
        if info.address and info.port:
            address = '.'.join(map(lambda n: str(n), info.address))

        self.controller.list_of_printing_services.add(address) 
Example #4
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 #5
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 #6
Source File: ZeroConfClient.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _onServiceAdded(self, zero_conf: Zeroconf, service_type: str, name: str) -> bool:
        """Handler for when a ZeroConf service was added."""

        # First try getting info from zero-conf cache
        info = ServiceInfo(service_type, name, properties={})
        for record in zero_conf.cache.entries_with_name(name.lower()):
            info.update_record(zero_conf, time(), record)

        for record in zero_conf.cache.entries_with_name(info.server):
            info.update_record(zero_conf, time(), record)
            if info.address:
                break

        # Request more data if info is not complete
        if not info.address:
            new_info = zero_conf.get_service_info(service_type, name)
            if new_info is not None:
                info = new_info

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

        return True 
Example #7
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 #8
Source File: zeroconf.py    From pyvizio with MIT License 5 votes vote down vote up
def __init__(self, func: Callable[[ServiceInfo], None]) -> None:
        """Initialize zeroconf listener with function callback."""
        self._func = func 
Example #9
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 #10
Source File: server.py    From opendrop with GNU General Public License v3.0 5 votes vote down vote up
def _init_service(self):
        properties = self.get_properties()
        server = self.config.host_name + '.local.'
        service_name = self.config.service_id + '._airdrop._tcp.local.'
        info = ServiceInfo('_airdrop._tcp.local.',
                           service_name,
                           port=self.config.port,
                           properties=properties,
                           server=server,
                           addresses=[self.ip_addr.packed])
        return info 
Example #11
Source File: advertise.py    From touchosc2midi with MIT License 5 votes vote down vote up
def build_service_info(ip):
    """Create a zeroconf ServiceInfo for touchoscbridge
    on for `ip` or the guessed default route interface's IP.
    """
    return ServiceInfo(type_=TOUCHOSC_BRIDGE,
                       name="{}.{}".format(
                           socket.gethostname(),
                           TOUCHOSC_BRIDGE
                       ),
                       address=socket.inet_aton(ip),
                       port=PORT,
                       properties=dict(),
                       server=socket.gethostname() + '.local.') 
Example #12
Source File: ServicePublisher.py    From OpenPLC_Editor with GNU General Public License v3.0 5 votes vote down vote up
def UnRegisterService(self):
        if self.retrytimer is not None:
            self.retrytimer.cancel()

        if self.server is not None:
            self.server.unregister_service(
                zeroconf.ServiceInfo(service_type,
                                     self.service_name,
                                     self.ip_32b,
                                     self.port,
                                     properties=self.serviceproperties))
            self.server.close()
            self.server = None 
Example #13
Source File: mdns.py    From ironic-lib with Apache License 2.0 4 votes vote down vote up
def register_service(self, service_type, endpoint, params=None):
        """Register a service.

        This call announces the new services via multicast and instructs the
        built-in server to respond to queries about it.

        :param service_type: OpenStack service type, e.g. "baremetal".
        :param endpoint: full endpoint to reach the service.
        :param params: optional properties as a dictionary.
        :raises: :exc:`.ServiceRegistrationFailure` if the service cannot be
            registered, e.g. because of conflicts.
        """
        parsed = _parse_endpoint(endpoint, service_type)

        all_params = CONF.mdns.params.copy()
        if params:
            all_params.update(params)
        all_params.update(parsed.params)

        # TODO(dtantsur): allow overriding TTL values via configuration
        info = zeroconf.ServiceInfo(_MDNS_DOMAIN,
                                    '%s.%s' % (service_type, _MDNS_DOMAIN),
                                    addresses=parsed.addresses,
                                    port=parsed.port,
                                    properties=all_params,
                                    server=parsed.hostname)

        LOG.debug('Registering %s via mDNS', info)
        # Work around a potential race condition in the registration code:
        # https://github.com/jstasiak/python-zeroconf/issues/163
        delay = 0.1
        try:
            for attempt in range(CONF.mdns.registration_attempts):
                try:
                    self._zc.register_service(info)
                except zeroconf.NonUniqueNameException:
                    LOG.debug('Could not register %s - conflict', info)
                    if attempt == CONF.mdns.registration_attempts - 1:
                        raise
                    # reset the cache to purge learned records and retry
                    self._zc.cache = zeroconf.DNSCache()
                    time.sleep(delay)
                    delay *= 2
                else:
                    break
        except zeroconf.Error as exc:
            raise exception.ServiceRegistrationFailure(
                service=service_type, error=exc)

        self._registered.append(info)