本文整理汇总了Python中zeroconf.Zeroconf.close方法的典型用法代码示例。如果您正苦于以下问题:Python Zeroconf.close方法的具体用法?Python Zeroconf.close怎么用?Python Zeroconf.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zeroconf.Zeroconf
的用法示例。
在下文中一共展示了Zeroconf.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def main():
desc = '%s [Args] [Options]\nDetailed options -h or --help' % __file__
parser = ArgumentParser(description=desc)
add_mqtt_arguments(parser, topic_default=DEFAULT_TOPIC_BASE)
args = parser.parse_args()
global topic_base
topic_base = args.topic
logging.basicConfig(level=get_log_level(args), format=LOG_FORMAT)
zeroconf = Zeroconf()
mqtt_client = mqtt.Client()
listener = HostListener(mqtt_client)
mqtt_client.on_connect = listener.on_connect
mqtt_client.on_message = listener.on_message
connect_mqtt(args, mqtt_client)
browser = ServiceBrowser(zeroconf, SERVICE_TYPE, listener)
try:
mqtt_client.loop_forever()
except KeyboardInterrupt:
pass
finally:
zeroconf.close()
示例2: MDnsListener
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
class MDnsListener(object):
"""A MDNS Listener."""
def __init__(self):
self.logger = _log.GetLogger('LogoCert')
self.zeroconf = Zeroconf(InterfaceChoice.All)
self.listener = MDnsService()
def add_listener(self, proto):
"""Browse for announcements of a particular protocol.
Args:
proto: string, type of traffic to listen for.
Returns:
boolean, True = browser activated, False = errors detected.
"""
protocols = {'http': '_http._tcp.local.',
'ipp': '_ipp._tcp.local.',
'mdns': '_mdns._udp.local.',
'printer': '_printer._tcp.local.',
'privet': '_privet._tcp.local.',
}
if proto not in protocols:
self.logger.error('Error starting listener, %s protocal unkown', proto)
return False
ServiceBrowser(self.zeroconf, protocols[proto], self.listener)
self.logger.info('Browsing for %s services...', proto)
return True
def remove_listeners(self):
"""Remove all listeners."""
self.zeroconf.close()
self.logger.info('All listeners have been stopped.')
示例3: Scanner
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
class Scanner(threading.Thread):
def __init__(self):
super(Scanner, self).__init__()
self.abort = False
def run(self):
utils.Log('Starting Zeroconf Scan')
self.listener = MyListener()
self.zeroconf = Zeroconf()
self.browser = ServiceBrowser(self.zeroconf, "_http._tcp.local.", self.listener)
while not self.abort:
xbmc.sleep(100)
self.zeroconf.close()
utils.Log('Ending Zeroconf Scan')
exit()
def stop(self):
self.abort = True
def getServers(self):
return getServers()
示例4: test_integration
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [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()
示例5: discover
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def discover(self):
print("{status} Smart Module hosting asset {asset_id} {asset_type} {asset_context}.".format(
status="Mock" if self.rtc.mock else "Real",
asset_id=self.asset.id,
asset_type=self.asset.type,
asset_context=self.asset.context))
try:
max_sleep_time = 3 # Calling sleep should be reviewed.
zeroconf = Zeroconf()
Log.info("Performing Broker discovery...")
self.find_broker(zeroconf)
time.sleep(max_sleep_time) # Wait for max_sleep_time to see if we found it.
if self.comm.broker_name or self.comm.broker_ip: # Found it.
Log.info("MQTT Broker: {broker_name} IP: {broker_ip}.".format(
broker_name=self.comm.broker_name,
broker_ip=self.comm.broker_ip))
else: # Make necessary actions to become the broker.
Log.info("Broker not found. Becoming the broker.")
self.become_broker()
time.sleep(max_sleep_time)
self.comm.connect() # Now it's time to connect to the broker.
except Exception as excpt:
Log.exception("[Exiting] Trying to find or become the broker.")
finally:
Log.info("Closing Zeroconf connection.")
zeroconf.close()
t_end = time.time() + 10
while (time.time() < t_end) and not self.comm.is_connected:
time.sleep(1)
self.comm.subscribe("SCHEDULER/RESPONSE")
self.comm.send("SCHEDULER/QUERY", "Where are you?")
Log.info("Waiting for Scheduler response...")
time.sleep(5) # Just wait for reply... Need a review?
self.comm.send("ANNOUNCE", self.hostname + " is online.")
t_end = time.time() + 2
while (time.time() < t_end) and not self.comm.is_connected:
time.sleep(1)
if not self.comm.scheduler_found: # Become the Scheduler (necessary actions as Scheduler)
try:
Log.info("No Scheduler found. Becoming the Scheduler.")
self.scheduler = Scheduler()
self.scheduler.smart_module = self
self.scheduler.prepare_jobs(self.scheduler.load_schedule())
self.comm.scheduler_found = True
self.comm.subscribe("SCHEDULER/QUERY")
self.comm.unsubscribe("SCHEDULER/RESPONSE")
self.comm.subscribe("STATUS/RESPONSE" + "/#")
self.comm.subscribe("ASSET/RESPONSE" + "/#")
self.comm.subscribe("ALERT" + "/#")
self.comm.send("SCHEDULER/RESPONSE", self.hostname)
self.comm.send("ANNOUNCE", self.hostname + " is running the Scheduler.")
Log.info("Scheduler program loaded.")
except Exception as excpt:
Log.exception("Error initializing scheduler. %s.", excpt)
示例6: advertise
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [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)
示例7: test_integration_with_subtype_and_listener
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [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()
示例8: find
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def find(cls, timeout=10, fast=False):
"""Use Zeroconf/Bonjour to locate AirPlay servers on the local network
Args:
timeout(int): The number of seconds to wait for responses.
If fast is false, then this function will always block for this number of seconds.
fast(bool): If true, do not wait for timeout to expire,
return as soon as we've found at least one AirPlay server
Returns:
list: A list of AirPlay() objects; one for each AirPlay server found
"""
# 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
devices.append(
cls(socket.inet_ntoa(info.address), info.port, name)
)
# 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
# enforce the timeout
timeout = time.time() + timeout
try:
while time.time() < timeout:
# if they asked us to be quick, bounce as soon as we have one AirPlay
if fast and len(devices):
break
time.sleep(0.05)
except KeyboardInterrupt: # pragma: no cover
pass
finally:
zeroconf.close()
return devices
示例9: get_others
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def get_others(self):
"""
Wait for other services to make themselves visible
"""
zeroconf = Zeroconf()
_ = ServiceBrowser(zeroconf, "_http._tcp.local.", handlers=[self.on_service_state_change])
for _ in range(1, 10 + 1):
time.sleep(1)
zeroconf.close()
return self.known_servers
示例10: main
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def main():
"""Main entry point."""
main = MainApplication()
zeroconf = Zeroconf()
listener = MyListener(main.get_control())
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
try:
main.mainloop()
finally:
zeroconf.close()
示例11: test_close_waits_for_threads
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def test_close_waits_for_threads():
class Dummy(object):
def add_service(self, zeroconf_obj, service_type, name):
pass
def remove_service(self, zeroconf_obj, service_type, name):
pass
z = Zeroconf()
z.add_service_listener('_privet._tcp.local.', listener=Dummy())
z.close()
assert not z.browsers[0].is_alive()
示例12: GlancesAutoDiscoverClient
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [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()
示例13: serviceStatus
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def serviceStatus():
zeroconf = Zeroconf()
info = zeroconf.get_service_info("_http._tcp.local.", "Takiyaki._http._tcp.local.")
# If service registered #
if info:
return (socket.inet_ntoa(info.address), info.port)
# No named service registered #
else:
print("Service doesn't exist")
zeroconf.close()
示例14: run
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def run(self):
#Log.debug('get_service_info')
zeroconf = Zeroconf()
listener = ServiceListener()
service_type = "_compass_discovery._tcp.local."
browser = ServiceBrowser(zeroconf, service_type, listener)
#Log.debug('enter browser')
try:
while True:
pass
finally:
zeroconf.close()
示例15: from_dacp_id
# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import close [as 别名]
def from_dacp_id(cls, dacp_id, token):
zeroconf = Zeroconf()
try:
listener = ServiceListener(airplay_prefix.format(dacp_id=dacp_id), zeroconf)
browser = ServiceBrowser(zeroconf, airplay_zeroconf_service, listener)
wait_for_it = ResultWaiter(listener, browser)
wait_for_it.start()
wait_for_it.join()
del wait_for_it
finally:
zeroconf.close()
assert(listener.info) # fails if service was not found.
host = "http://" + binary_ip_to_str(listener.info.address)
port = listener.info.port
return AirplayRemote(token, host, port)