本文整理汇总了Python中zeroconf.Zeroconf.register_service方法的典型用法代码示例。如果您正苦于以下问题:Python Zeroconf.register_service方法的具体用法?Python Zeroconf.register_service怎么用?Python Zeroconf.register_service使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zeroconf.Zeroconf
的用法示例。
在下文中一共展示了Zeroconf.register_service方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_integration
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def test_integration():
service_added = Event()
service_removed = Event()
type_ = "_http._tcp.local."
registration_name = "xxxyyy.%s" % type_
def on_service_state_change(zeroconf, service_type, state_change, name):
if name == registration_name:
if state_change is ServiceStateChange.Added:
service_added.set()
elif state_change is ServiceStateChange.Removed:
service_removed.set()
zeroconf_browser = Zeroconf()
browser = ServiceBrowser(zeroconf_browser, type_, [on_service_state_change])
zeroconf_registrar = Zeroconf()
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_, registration_name,
socket.inet_aton("10.0.1.2"), 80, 0, 0,
desc, "ash-2.local.")
zeroconf_registrar.register_service(info)
try:
service_added.wait(1)
assert service_added.is_set()
# Don't remove service, allow close() to cleanup
finally:
zeroconf_registrar.close()
browser.cancel()
zeroconf_browser.close()
示例2: advertise
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def advertise(self):
postfix = self.config['global']['service_prefix']
self.port = int(self.config['global']['port'])
#print(self.config['device']['hostname']+postfix)
info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix,
socket.inet_aton(self.ip), self.port, 0, 0,
{'info': self.config['device']['description']}, "hazc.local.")
self.bindConnection()
zeroconf = Zeroconf()
zeroconf.register_service(info)
try:
while True:
# try:
print("Ready")
self.conn, self.addr = self.webcontrol.accept()
self.listen()
self.conn.close()
except KeyboardInterrupt:
pass
finally:
print()
print("Unregistering...")
zeroconf.unregister_service(info)
zeroconf.close()
try:
print("Shutting down socket")
self.webcontrol.shutdown(socket.SHUT_RDWR)
except Exception as e:
print(e)
示例3: setup
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)
requires_api_password = hass.config.api.api_password is not None
params = {
'version': __version__,
'base_url': hass.config.api.base_url,
'requires_api_password': requires_api_password,
}
host_ip = util.get_local_ip()
try:
host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
except socket.error:
host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
hass.http.server_port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
示例4: setup
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = "{}.{}".format(hass.config.location_name,
ZEROCONF_TYPE)
requires_api_password = (hass.config.api.api_password is not None)
params = {"version": __version__, "base_url": hass.config.api.base_url,
"requires_api_password": requires_api_password}
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name,
socket.inet_aton(hass.config.api.host),
hass.config.api.port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_BLUMATE_STOP, stop_zeroconf)
return True
示例5: test_integration_with_subtype_and_listener
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def test_integration_with_subtype_and_listener(self):
subtype_ = "_subtype._sub"
type_ = "_type._tcp.local."
name = "xxxyyy"
# Note: discovery returns only DNS-SD type not subtype
discovery_type = "%s.%s" % (subtype_, type_)
registration_name = "%s.%s" % (name, type_)
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
discovery_type, registration_name,
socket.inet_aton("10.0.1.2"), 80, 0, 0,
desc, "ash-2.local.")
zeroconf_registrar.register_service(info)
try:
service_types = ZeroconfServiceTypes.find(
interfaces=['127.0.0.1'], timeout=0.5)
assert discovery_type in service_types
service_types = ZeroconfServiceTypes.find(
zc=zeroconf_registrar, timeout=0.5)
assert discovery_type in service_types
finally:
zeroconf_registrar.close()
示例6: setup
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)
requires_api_password = hass.config.api.api_password is not None
params = {
'version': __version__,
'base_url': hass.config.api.base_url,
'requires_api_password': requires_api_password,
}
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name,
socket.inet_aton(hass.config.api.host),
hass.config.api.port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
示例7: GlancesAutoDiscoverClient
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
class GlancesAutoDiscoverClient(object):
"""Implementation of the zeroconf protocol (client side for the Glances server)."""
def __init__(self, hostname, args=None):
if zeroconf_tag:
zeroconf_bind_address = args.bind_address
try:
self.zeroconf = Zeroconf()
except socket.error as e:
logger.error("Cannot start zeroconf: {}".format(e))
# XXX *BSDs: Segmentation fault (core dumped)
# -- https://bitbucket.org/al45tair/netifaces/issues/15
if not BSD:
try:
# -B @ overwrite the dynamic IPv4 choice
if zeroconf_bind_address == '0.0.0.0':
zeroconf_bind_address = self.find_active_ip_address()
except KeyError:
# Issue #528 (no network interface available)
pass
# Check IP v4/v6
address_family = socket.getaddrinfo(zeroconf_bind_address, args.port)[0][0]
# Start the zeroconf service
self.info = ServiceInfo(
zeroconf_type, '{}:{}.{}'.format(hostname, args.port, zeroconf_type),
address=socket.inet_pton(address_family, zeroconf_bind_address),
port=args.port, weight=0, priority=0, properties={}, server=hostname)
try:
self.zeroconf.register_service(self.info)
except socket.error as e:
logger.error("Error while announcing Glances server: {}".format(e))
else:
print("Announce the Glances server on the LAN (using {} IP address)".format(zeroconf_bind_address))
else:
logger.error("Cannot announce Glances server on the network: zeroconf library not found.")
@staticmethod
def find_active_ip_address():
"""Try to find the active IP addresses."""
import netifaces
# Interface of the default gateway
gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1]
# IP address for the interface
return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']
def close(self):
if zeroconf_tag:
self.zeroconf.unregister_service(self.info)
self.zeroconf.close()
示例8: ZeroconfService
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
class ZeroconfService(AbstractZeroconfService):
"""
:class:`ZeroconfService` uses `python zeroconf`_
.. _python zeroconf: https://pypi.org/project/zeroconf/
Install::
.. code-block:: bash
pip install zeroconf
"""
def __init__(self, name, port):
super(ZeroconfService, self).__init__(name, port)
self._zeroconf = None
self._infos = []
@classmethod
def has_support(cls):
return support
def start(self):
self._zeroconf = Zeroconf()
for index, ip in enumerate(self.ips):
info = self._gerenate_service_info(index, ip)
self._infos.append(info)
self._zeroconf.register_service(info)
self._log('Zeroconf {} - Registered service: name={}, regtype={}, domain={}', self.__class__.__name__,
self.name, self.type, 'local.')
self._log(' Network: {}', ip)
def _gerenate_service_info(self, index, ip):
name = '{}-{}.{}.local.'.format(self.name.lower(), index, self.type, '.local.')
return ServiceInfo(
self.type + '.local.',
name,
socket.inet_aton(ip),
self.port,
0,
0,
{}
)
def close(self):
for info in self._infos:
self._zeroconf.unregister_service(info)
示例9: createService
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def createService():
zeroconf = Zeroconf()
# Look up info's __init__ in python-zeroconf's documentation #
info = ServiceInfo("_http._tcp.local.", "Takiyaki._http._tcp.local.", socket.inet_aton(socket.gethostbyname(socket.gethostname())), 8080,0,0,socket.gethostname() + ".local.")
# Server is supported but not compulsory, set server as inputted name #
print "Registered Service [" + info.name + "]"
zeroconf.register_service(info)
try:
while True: sleep(0.1)
except KeyboardInterrupt:
zeroconf.unregister_service(info)
print("Unregistered")
zeroconf.close()
print("Service registered")
zeroconf.close()
示例10: GlancesAutoDiscoverClient
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
class GlancesAutoDiscoverClient(object):
"""Implementation of the zeroconf protocol (client side for the Glances server)."""
def __init__(self, hostname, args=None):
if zeroconf_tag:
zeroconf_bind_address = args.bind_address
try:
self.zeroconf = Zeroconf()
except socket.error as e:
logger.error("Cannot start zeroconf: {0}".format(e))
try:
# -B @ overwrite the dynamic IPv4 choice
if zeroconf_bind_address == '0.0.0.0':
zeroconf_bind_address = self.find_active_ip_address()
except KeyError:
# Issue #528 (no network interface available)
pass
print("Announce the Glances server on the LAN (using {0} IP address)".format(zeroconf_bind_address))
self.info = ServiceInfo(
zeroconf_type, '{0}:{1}.{2}'.format(hostname, args.port, zeroconf_type),
address=socket.inet_aton(zeroconf_bind_address), port=args.port,
weight=0, priority=0, properties={}, server=hostname)
self.zeroconf.register_service(self.info)
else:
logger.error("Cannot announce Glances server on the network: zeroconf library not found.")
@staticmethod
def find_active_ip_address():
"""Try to find the active IP addresses."""
if not 'freebsd' in sys.platform:
import netifaces
# Interface of the default gateway
gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1]
# IP address for the interface
return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']
else:
raise KeyError, 'On FreeBSD, this would segfault'
def close(self):
if zeroconf_tag:
self.zeroconf.unregister_service(self.info)
self.zeroconf.close()
示例11: Advertisement
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
class Advertisement(object):
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 main_ip())
def register(self):
"""Registers the service on the network.
"""
self.zeroconf.register_service(self.info)
log.debug("Registered {} on {}:{}".format(self.info.name,
self.ip,
self.info.port))
def unregister(self):
"""Unregisters the service.
"""
self.zeroconf.unregister_service(self.info)
log.debug("Unregistered touchoscbridge.")
def update(self, ip=None):
"""Re-register the the service on the network.
:ip: if string `ip` is given, use given IP when registering.
"""
self.unregister()
self.info = build_service_info(ip=ip or main_ip())
self.register()
def close(self):
"""Free resources.
Advertisement.unregister() should be called before closing.
"""
self.zeroconf.close()
def get_ip(self):
""":return: the service's IP as a string.
"""
return socket.inet_ntoa(self.info.address)
ip = property(get_ip)
示例12: GlancesAutoDiscoverClient
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
class GlancesAutoDiscoverClient(object):
"""Implementation of the zeroconf protocol (client side for the Glances server)."""
def __init__(self, hostname, args=None):
if zeroconf_tag:
zeroconf_bind_address = args.bind_address
try:
self.zeroconf = Zeroconf()
except socket.error as e:
logger.error("Cannot start zeroconf: {0}".format(e))
if netifaces_tag:
# -B @ overwrite the dynamic IPv4 choice
if zeroconf_bind_address == '0.0.0.0':
zeroconf_bind_address = self.find_active_ip_address()
else:
logger.error("Couldn't find the active IP address: netifaces library not found.")
logger.info("Announce the Glances server on the LAN (using {0} IP address)".format(zeroconf_bind_address))
print("Announce the Glances server on the LAN (using {0} IP address)".format(zeroconf_bind_address))
self.info = ServiceInfo(
zeroconf_type, '{0}:{1}.{2}'.format(hostname, args.port, zeroconf_type),
address=socket.inet_aton(zeroconf_bind_address), port=args.port,
weight=0, priority=0, properties={}, server=hostname)
self.zeroconf.register_service(self.info)
else:
logger.error("Cannot announce Glances server on the network: zeroconf library not found.")
def find_active_ip_address(self):
"""Try to find the active IP addresses."""
try:
# Interface of the default gateway
gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1]
# IP address for the interface
return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']
except Exception:
return None
def close(self):
if zeroconf_tag:
self.zeroconf.unregister_service(self.info)
self.zeroconf.close()
示例13: __init__
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
class ServiceDiscoveryServer:
def __init__(self, port):
inet = netifaces.AF_INET
hostname = socket.gethostname()
def_gw = netifaces.gateways()['default'][inet][1]
addr = netifaces.ifaddresses(def_gw)[inet][0]['addr']
addr = socket.inet_aton(addr)
self.zeroconf = Zeroconf()
self.info = ServiceInfo(
SRV_TYPE, srv_fqname(), addr, port, 0, 0,
{}, '{}.local.'.format(hostname)
)
def start(self):
self.zeroconf.register_service(self.info)
def stop(self):
self.zeroconf.unregister_service(self.info)
self.zeroconf.close()
示例14: test_integration_with_listener
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def test_integration_with_listener(self):
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
)
zeroconf_registrar.register_service(info)
try:
service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=0.5)
assert type_ in service_types
service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=0.5)
assert type_ in service_types
finally:
zeroconf_registrar.close()
示例15: test_integration
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import register_service [as 别名]
def test_integration():
service_added = Event()
service_removed = Event()
type_ = "_http._tcp.local."
registration_name = "xxxyyy.%s" % type_
class MyListener(object):
def remove_service(self, zeroconf, type_, name):
if name == registration_name:
service_removed.set()
def add_service(self, zeroconf, type_, name):
if name == registration_name:
service_added.set()
zeroconf_browser = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf_browser, type_, listener)
zeroconf_registrar = Zeroconf()
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_, registration_name,
socket.inet_aton("10.0.1.2"), 80, 0, 0,
desc, "ash-2.local.")
zeroconf_registrar.register_service(info)
try:
service_added.wait(1)
assert service_added.is_set()
zeroconf_registrar.unregister_service(info)
service_removed.wait(1)
assert service_removed.is_set()
finally:
zeroconf_registrar.close()
browser.cancel()
zeroconf_browser.close()