本文整理汇总了Python中zeroconf.ServiceInfo方法的典型用法代码示例。如果您正苦于以下问题:Python zeroconf.ServiceInfo方法的具体用法?Python zeroconf.ServiceInfo怎么用?Python zeroconf.ServiceInfo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zeroconf
的用法示例。
在下文中一共展示了zeroconf.ServiceInfo方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: mDNSinit
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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!')
示例2: start
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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()
示例3: add_service
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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)
示例4: announce_zeroconf
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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)
示例5: _RegisterService
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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
示例6: _onServiceAdded
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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
示例7: start
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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()
示例8: __init__
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
def __init__(self, func: Callable[[ServiceInfo], None]) -> None:
"""Initialize zeroconf listener with function callback."""
self._func = func
示例9: discover
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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
示例10: _init_service
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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
示例11: build_service_info
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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.')
示例12: UnRegisterService
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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
示例13: register_service
# 需要导入模块: import zeroconf [as 别名]
# 或者: from zeroconf import ServiceInfo [as 别名]
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)