def find(self, id, timeout=30): from zeroconf import ServiceBrowser, Zeroconf print("Discovering Digital Paper for {} seconds…".format(timeout)) sys.stdout.flush() self.id = id zc = Zeroconf() self.lock.acquire() ServiceBrowser(zc, "_digitalpaper._tcp.local.", self) wait = self.lock.acquire(timeout=timeout) or (self.addr is not None) zc.close() if not wait: print("Failed".format(timeout)) return None else: print("Found digital paper at", self.addr) print("To skip the discovery process (and this message), call:") print() print(" {} --addr {} {}".format(sys.argv[0], self.addr, " ".join(sys.argv[1:]))) print() return self.addr
def startDiscovery(self) -> None: if self._browser: self._browser.cancel() self._browser = None # type: Optional[ServiceBrowser] self._printers = [] # type: List[PrinterOutputModel] self.instanceListChanged.emit() try: self._zero_conf = Zeroconf() except Exception: self._zero_conf = None self._keep_alive_timer.stop() Logger.logException( "e", "Failed to create Zeroconf instance. Auto-discovery will not work." ) if self._zero_conf: self._browser = ServiceBrowser(self._zero_conf, u'_octoprint._tcp.local.', [self._onServiceChanged]) if self._browser and self._browser.is_alive(): self._keep_alive_timer.start() else: Logger.log( "w", "Failed to create Zeroconf browser. Auto-discovery will not work." ) # Add manual instances from preference for name, properties in self._manual_instances.items(): additional_properties = { b"path": properties["path"].encode("utf-8"), b"useHttps": b"true" if properties.get("useHttps", False) else b"false", b'userName': properties.get("userName", "").encode("utf-8"), b'password': properties.get("password", "").encode("utf-8"), b"manual": b"true" } # These additional properties use bytearrays to mimick the output of zeroconf self.addInstance(name, properties["address"], properties["port"], additional_properties)
def start_zeroconf(self): self.zeroconf = Zeroconf() self.service_ident = auth.get_singleton().get_ident() self.service_name = "%s.%s" % (self.service_ident, SERVICE_TYPE) # If this process is killed (either kill ot logout), the service # never gets unregistered, which will prevent remotes from seeing us # when we come back. Our first service info is to get us back on # momentarily, and the unregister properly, so remotes get notified. # Then we'll do it again without the flush property for the real # connection. init_info = wrappers.new_service_info(SERVICE_TYPE, self.service_name, socket.inet_aton(util.get_ip()), prefs.get_port(), properties={ 'hostname': util.get_hostname(), 'type': 'flush' }) self.zeroconf.register_service(init_info) time.sleep(3) self.zeroconf.unregister_service(init_info) time.sleep(3) self.info = wrappers.new_service_info(SERVICE_TYPE, self.service_name, socket.inet_aton(util.get_ip()), prefs.get_port(), properties={ 'hostname': util.get_hostname(), 'type': 'real' }) self.zeroconf.register_service(self.info) self.browser = ServiceBrowser(self.zeroconf, SERVICE_TYPE, self) return False
def main(): logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--find', action='store_true', help='Browse all available services') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--v6', action='store_true') version_group.add_argument('--v6-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6: ip_version = IPVersion.All elif args.v6_only: ip_version = IPVersion.V6Only else: ip_version = IPVersion.V4Only zeroconf = Zeroconf(ip_version=ip_version) services = ["_http._tcp.local.", "_hap._tcp.local."] if args.find: services = list(ZeroconfServiceTypes.find(zc=zeroconf)) print("\nBrowsing %d service(s), press Ctrl-C to exit...\n" % len(services)) browser = ServiceBrowser(zeroconf, services, handlers=[on_service_state_change]) try: while True: sleep(0.1) except KeyboardInterrupt: pass finally: zeroconf.close()
def probe(self): if not self.can_probe: return # do not search if host is specified by commandline, or again try: from zeroconf import ServiceBrowser, ServiceStateChange, Zeroconf except Exception as e: print(_('failed to') + ' import zeroconf, ' + _('autodetecting pypilot server not possible')) print(_('try') + ' pip3 install zeroconf' + _('or') + ' apt install python3-zeroconf') class Listener: def __init__(self, client): self.client = client def remove_service(self, zeroconf, type, name): pass def add_service(self, zeroconf, type, name): #print('service', name) self.name_type = name, type info = zeroconf.get_service_info(type, name) #print('info', info, info.parsed_addresses()[0]) if not info: return try: #for name, value in info.properties.items(): config = self.client.config #print('info', info.addresses) config['host'] = socket.inet_ntoa(info.addresses[0]) config['port'] = info.port print('found pypilot', config['host'], config['port']) self.client.probed = True zeroconf.close() except Exception as e: print('zeroconf service exception', e) self.can_probe = False zeroconf = Zeroconf() listener = Listener(self) browser = ServiceBrowser(zeroconf, "_pypilot._tcp.local.", listener)
def main(): # Catch CNTRL-C signel global shutdown signal.signal(signal.SIGINT, signal_cntrl_c) init_logging("", 2) context = zmq.Context.instance() zeroconf = Zeroconf() listener = ZeroConfListener(context) browser = ServiceBrowser(zeroconf, "_DashZMQ._tcp.local.", listener) b = zmq_tcpBridge(tcp_port=5001, context=context) while not shutdown: time.sleep(1) print("Goodbye") zeroconf.unregister_all_services() b.close() time.sleep(1) zeroconf.close()
def discover_homekit_devices(): zeroconf = Zeroconf() listener = CollectingListener() ServiceBrowser(zeroconf, '_hap._tcp.local.', listener) sleep(1) for info in listener.get_data(): print('Name: {name}'.format(name=info.name)) print('Url: http://{ip}:{port}'.format(ip=inet_ntoa(info.address), port=info.port)) print('Configuration number (c#): {conf}'.format(conf=info.properties[b'c#'].decode())) flags = int(info.properties[b'ff'].decode()) print('Feature Flags (ff): {f} (Flag: {flags})'.format(f=FeatureFlags[flags], flags=flags)) print('Device ID (id): {id}'.format(id=info.properties[b'id'].decode())) print('Model Name (md): {md}'.format(md=info.properties[b'md'].decode())) print('Protocol Version (pv): {pv}'.format(pv=info.properties[b'pv'].decode())) print('State Number (s#): {sn}'.format(sn=info.properties[b's#'].decode())) print('Status Flags (sf): {sf}'.format(sf=info.properties[b'sf'].decode())) category = int(info.properties[b'ci'].decode()) print('Category Identifier (ci): {c} (Id: {ci})'.format(c=Categories[category], ci=category)) print() zeroconf.close()
def refresh_listeners(): interfaces = netifaces.interfaces() log.debug("Initial list of interfaces: %r", interfaces) for interface in interfaces: # find ipv4 address for interface ip = get_ipv4_addr(interface) if not ip: log.debug(("Interface %r was skipped because" + "it didn't have an IPv4 address"), interface) continue if ip in ['0.0.0.0']: log.debug(("Interface %r was skipped because" + "it had a unsupported IPv4 address"), interface) continue # start zeroconf service browser restricted to the interface's address log.info("Starting Zeroconf listener on %r, ip = %r", interface, ip) zeroconf = Zeroconf([ip]) listener = LiquidServiceListener(interface) ServiceBrowser(zeroconf, SERVICE_TYPE, listener)
def startDiscovery(self): self.stop() if self._browser: self._browser.cancel() self._browser = None self._old_printers = [ printer_name for printer_name in self._printers ] self._printers = {} self.printerListChanged.emit() # After network switching, one must make a new instance of Zeroconf # On windows, the instance creation is very fast (unnoticable). Other platforms? self._zero_conf = Zeroconf() self._browser = ServiceBrowser(self._zero_conf, u'_ultimaker._tcp.local.', [self._onServiceChanged]) # Look for manual instances from preference for address in self._manual_instances: if address: self.addManualPrinter(address)
def connect(self, num_retries): """ Connects to the drone :param num_retries: maximum number of retries :return: True if the connection succeeded and False otherwise """ zeroconf = Zeroconf() listener = mDNSListener(self) browser = ServiceBrowser(zeroconf, self.mdns_address, listener) # basically have to sleep until the info comes through on the listener num_tries = 0 while (num_tries < num_retries and not self.is_connected): time.sleep(1) num_tries += 1 # if we didn't hear the listener, return False if (not self.is_connected): color_print("connection failed: did you remember to connect your machine to the Drone's wifi network?", "ERROR") return False else: browser.cancel() # perform the handshake and get the UDP info handshake = self._handshake(num_retries) if (handshake): self._create_udp_connection() self.listener_thread = threading.Thread(target=self._listen_socket) self.listener_thread.start() color_print("Success in setting up the wifi network to the drone!", "SUCCESS") return True else: color_print("Error: TCP handshake failed.", "ERROR") return False
def _get_ds1000z_results(if_any_return_after=1.0, timeout=2.5): """ Zeroconf service discovery of ``_scpi-raw._tcp.local.`` The results are filtered for entries matching the Rigol DS1000Z scope series. :return: The filtered results list created by the Listener(): A list of dictionaries, each containing the entries ``zc_name``, ``zc_type``, and ``zc_info``. :rtype: list of dict """ zc = Zeroconf() def ds1000z_filter(result): check_results = [ re.match(b'DS1\d\d\dZ', result['zc_info'].properties[b'Model']), re.match(b'RIGOL TECHNOLOGIES', result['zc_info'].properties[b'Manufacturer']), ] if not all(check_results): return False return True listener = Listener(filter_func=ds1000z_filter, cast_service_info=DS1000ZServiceInfo) browser = ServiceBrowser(zc, '_scpi-raw._tcp.local.', listener=listener) start = clock() while True: # Because multithreading sucks. et = clock() - start # elapsed time if len(listener.results) and et >= if_any_return_after: break if et >= timeout: break time.sleep(0.005) zc.close() return listener.results
def main() -> None: zeroconf = Zeroconf() listener = MyListener() ServiceBrowser(zeroconf, '_ewelink._tcp.local.', listener=listener) while True: if listener.all_sub_num > 0: all_info_dict = listener.all_info_dict.copy() for x in all_info_dict.keys(): info = all_info_dict[x] info = zeroconf.get_service_info(info.type, x) if info is not None: data = info.properties cur_str = (x[8:18] + ' ' + parse_address(info.addresses[0]) + ' ' + str(info.port) + ' ' + str(data)) print(cur_str) if len(listener.all_del_sub) > 0: for x in listener.all_del_sub: cur_str = x[8:18] + '\nDEL' print(cur_str) time.sleep(0.5)
def main(): print_noti("should ok") parser = OptionParser( usage='usage: %prog [options] <map-file>', description= "This script print the dependencies of emv-modules to non-emv-modules", prog=os.path.basename(__file__)) parser = OptionParser() parser.add_option("-w", "--wav-writer", dest="wav_writer", action="store_true", default=False, help="Enable record pcm stream to wav file") parser.add_option("-p", "--play", dest="pcm_player", action="store_true", default=False, help="Enable play pcm stream to audio out") (options, args) = parser.parse_args() if options.pcm_player: globalConfig["PcmPlayer"] = True if options.wav_writer: globalConfig["WavFileWriter"] = True print(globalConfig) nlpServiceInst = NLPService() nlpService = threading.Thread(target=nlpServiceInst.run) nlpService.start() wsServer = threading.Thread(target=RunWsServer) wsServer.start() snowBoyRunner = threading.Thread(target=RunSnowboy) snowBoyRunner.start() zeroconf = Zeroconf() listener = DeviceDetectListener() browser = ServiceBrowser(zeroconf, "_arduino._tcp.local.", listener) RunFlaskServer()
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()
def startDiscovery(self): if self._browser: self._browser.cancel() self._browser = None self._printers = {} self.instanceListChanged.emit() self._zero_conf.__init__() self._browser = ServiceBrowser(self._zero_conf, u'_wirelessprint._tcp.local.', [self._onServiceChanged]) # Add manual instances from preference for name, properties in self._manual_instances.items(): additional_properties = { b"path": properties["path"].encode("utf-8"), b"useHttps": b"true" if properties.get("useHttps", False) else b"false", b"manual": b"true" } # These additional properties use bytearrays to mimick the output of zeroconf self.addInstance(name, properties["address"], properties["port"], additional_properties)
def main(args): try: # FIXME: Maybe we should not use zeroconf and instead implement # our own avahi browser. zeroconf = Zeroconf() client = _StoqClient() client.show_all() ServiceBrowser(zeroconf, '%s.local.' % (AVAHI_STYPE, ), client) gtk.gdk.threads_init() gtk.main() finally: zeroconf.close() env = os.environ.copy() env['PYTHONPATH'] = ':'.join(client.python_paths + [env.get('PYTHONPATH', '')]) popen = subprocess.Popen([sys.executable, client.executable_path], env=env) try: popen.communicate() except KeyboardInterrupt: popen.terminate()
def discover_host(): from zeroconf import ServiceBrowser, Zeroconf host = None def on_service_state_change(zeroconf, service_type, name, state_change): pass zeroconf = Zeroconf() browser = ServiceBrowser(zeroconf, "_zigate._tcp.local.", handlers=[on_service_state_change]) i = 0 while not host: time.sleep(0.1) if browser.services: service = list(browser.services.values())[0] info = zeroconf.get_service_info(service.name, service.alias) host = socket.inet_ntoa(info.address) i += 1 if i > 50: break zeroconf.close() return host
def __init__(self, parent): super().__init__(parent) self._dialog_ui = Ui_Dialog() self._dialog_ui.setupUi(self) self._zeroconf_instance = Zeroconf() self._listener = QSpyderRemoteListener() self._kernels = [] # Widgets self.host_combo = self._dialog_ui.spyderHosts self.user_combo = self._dialog_ui.user self.env_comvo = self._dialog_ui.condaEnvironments self.req = self._dialog_ui.requirements self.req_label = self._dialog_ui.label_6 self.keyring_check = self._dialog_ui.keyring self.password = self._dialog_ui.password self.cancel_button = self._dialog_ui.cancelButton self.connect_button = self._dialog_ui.connectButton self.load_req_button = self._dialog_ui.findRequirements self.feedback_label = self._dialog_ui.feedback self.feedback_label.setText("") self.setWindowTitle("Connect to remote kernel") # Signals self.cancel_button.clicked.connect(self.close) self.connect_button.clicked.connect(self.connect) self.host_combo.currentIndexChanged.connect(self.change_host) self._listener.sig_service_added.connect(self._on_service_update) self._listener.sig_service_removed.connect(self._on_service_update) self._listener.sig_service_updated.connect(self._on_service_update) # Start zeroconf service browser self._browser = ServiceBrowser( self._zeroconf_instance, SERVICE_TYPE, self._listener, )
def zeroconf_find_server(): # Alert user... print(F'Probing LAN for a Helios server, please wait...') # Initialize Zeroconf... zeroconf = Zeroconf() # Construct listener... listener = LocalNetworkServiceListener() # Begin listening... browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener) # Wait until it finds server... listener.found_event.wait() # Cleanup... zeroconf.close() # Return host and port of first found... return listener.get_found()[0]
def __init__(self, ifname: str, wg_iface: WGInterface): self._setLoggerName(ifname) self.ifname = ifname self.ifindex: int = IPRoute().link_lookup(ifname=ifname)[0] self.wg_iface = wg_iface self.addresses = self.get_addrs() self.zeroconf = Zeroconf([addr.compressed for addr in self.addresses]) self.listener = WGServiceListener(self) self.browser = ServiceBrowser(self.zeroconf, WG_TYPE, self.listener) digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(MACHINE_ID.encode('utf-8')) digest.update(ifname.encode('utf-8')) self.hostname = digest.finalize()[:16].hex() self.service: WGServiceInfo = WGServiceInfo.new( self.hostname, addresses=[addr.packed for addr in self.addresses], hostname=HOSTNAME, config=wg_iface.config, ) self.zeroconf.register_service(self.service)
def discover_chromecasts(max_devices=None, timeout=DISCOVER_TIMEOUT): """ Discover chromecasts on the network. """ try: zconf = Zeroconf() listener = CastListener() browser = ServiceBrowser(zconf, "_googlecast._tcp.local.", listener) if max_devices is None: time.sleep(timeout) return listener.devices else: start = time.time() while (time.time() - start < timeout and listener.count < max_devices): time.sleep(.1) return listener.devices finally: browser.cancel() zconf.close()
def __init__(self, name): super(ZeroConfExplorer, self).__init__() # init explorer to None self.oscquery_device = None if not name: name = 'OSCJSON thru TCP Explorer' # create the view self.explorer = QTreeView() # Hide Useless Header self.explorer.header().hide() self.panel = Panel() # create right-click menu self.explorer.setContextMenuPolicy(Qt.CustomContextMenu) self.explorer.customContextMenuRequested.connect(self.contextual_menu) # create the model self.devices_model = QStandardItemModel() # link model to the view self.explorer.setModel(self.devices_model) self.explorer.selectionModel().selectionChanged.connect( self.selection_updated) # set selection self.device_selection_model = self.explorer.selectionModel() # set layout and group Layout = QGridLayout() # add the view to the layout Layout.addWidget(self.explorer, 0, 0) Layout.addWidget(self.panel, 0, 1) # add the layout to the GroupBox self.setLayout(Layout) #self.setMinimumSize(300, 300) self.explorer.setFixedSize(300, 300) # start zeroconf services zeroconf = Zeroconf() # start the callback, it will create items listener = ZeroConfListener(self.devices_model) listener.add_device.connect(self.connect_device) browser = ServiceBrowser(zeroconf, "_oscjson._tcp.local.", listener) self.current_remote = None
def get_remote(cls, dacp_id, token, timeout): """ :param dacp_id: clients dacp_id :param token: token of client :param timeout: time after which the search for the airplay remote will be terminated :return: instance of AirplayRemote """ from zeroconf import ServiceBrowser, Zeroconf from .airplayservicelistener import AirplayServiceListener from ..util import binary_ip_to_string zeroconf = Zeroconf() listener = None try: listener = AirplayServiceListener(dacp_id) browser = ServiceBrowser(zeroconf, AIRPLAY_ZEROCONF_SERVICE, listener) # pylint: disable=W0612 wait_thread = listener.start_listening() wait_thread.join(timeout=timeout) # if the thread is still alive a timeout occurred if wait_thread.is_alive(): listener.stop_listening() return None except Exception as exc: # pylint: disable=W0703 logger.warning(exc) finally: zeroconf.close() # connection established if listener and listener.info: host = binary_ip_to_string(listener.info.address if hasattr( listener.info, "address") else listener.info.addresses[0]) return cls(dacp_id, token, host, listener.info.port, hostname=listener.info.server) return None
def discover_devices(timeout=5): """Discover devices on the local network. :param timeout: Max time to wait in seconds. Default 5 """ devices = [] # Using Queue as a timeout timer add_devices_queue = Queue() def add_device_function(name, host, port): """Add device callback.""" _LOGGER.info("%s discovered (host: %s, port: %i)", name, host, port) devices.append(soundtouch_device(host, port)) zeroconf = Zeroconf() listener = SoundtouchDeviceListener(add_device_function) _LOGGER.debug("Starting discovery...") ServiceBrowser(zeroconf, "_soundtouch._tcp.local.", listener) try: add_devices_queue.get(timeout=timeout) except Empty: _LOGGER.debug("End of discovery...") return devices
def discover_chromecasts(max_devices=None, timeout=DISCOVER_TIMEOUT): try: zconf = Zeroconf() listener = CastListener() browser = ServiceBrowser(zconf, "_googlecast._tcp.local.", listener) t = 0 if max_devices is None: time.sleep(DISCOVER_TIMEOUT) return listener.devices else: while t < DISCOVER_TIMEOUT: time.sleep(.1) if listener.count >= max_devices: return listener.devices return listener.devices finally: browser.cancel() zconf.close()
def discover_via_mdns(): zeroconf = Zeroconf() listener = MyListener() t1 = datetime.now() browser = ServiceBrowser(zeroconf, "_hue._tcp.local.", listener) time.sleep(2) zeroconf.close() t2 = datetime.now() for sv in listener.services: service = listener.services[sv] ip = socket.gethostbyname(service.server) if service.port == 443: protocol = 'https' else: protocol = 'http' bridge_id = service.properties[b'bridgeid'].decode() add_discovered_bridge(ip, service.port)
def main(): zeroconf = Zeroconf() listener = MyListener() browser = ServiceBrowser(zeroconf, "_ewelink._tcp.local.", listener=listener) while True: if listener.all_sub_num > 0: dict = listener.all_info_dict.copy() for x in dict.keys(): info = dict[x] info = zeroconf.get_service_info(info.type, x) if info != None: data = info.properties cur_str = x[8:18] + " " + parseAddress( info.address) + " " + str( info.port) + " " + str(data) print(cur_str) if len(listener.all_del_sub) > 0: for x in listener.all_del_sub: cur_str = x[8:18] + "\nDEL" print(cur_str) time.sleep(0.5)
def get_hosts(): """ Returns a list of available hosts in the network """ hosts = [] def search_hostnames(zeroconf, service_type, name, state_change): """ Prints the hostname to stdout """ if state_change is ServiceStateChange.Added: hostname = name.split('.') hosts.append(hostname[0]) zeroconf = Zeroconf() browser = ServiceBrowser(zeroconf, '_lanshare._tcp.local.', handlers=[search_hostnames]) # Should sleep to allow discover? zeroconf.close() return hosts
def test_10(self): """Node advertises a Node type mDNS announcement with no ver_* TXT records in the presence of a Registration API""" test_number = "10" test_description = "Node advertises a Node type mDNS announcement with no ver_* TXT records in the presence " \ "of a Registration API" zeroconf = Zeroconf() listener = MdnsListener() browser = ServiceBrowser(zeroconf, "_nmos-node._tcp.local.", listener) sleep(5) zeroconf.close() node_list = listener.get_service_list() for node in node_list: address = socket.inet_ntoa(node.address) port = node.port if address in self.url and ":{}".format(port) in self.url: properties_raw = node.properties for prop in properties_raw: if "ver_" in prop.decode('ascii'): return test_number, test_description, "Fail", "Found 'ver_'-txt record while node " \ "is registered." return test_number, test_description, "Pass", "" return test_number, test_description, "Fail", "No matching mdns announcement found for node."
def discover_hub(self, min_search_time: int = 2, max_search_time: int = 10): """ Call zeroconf service browser to find Wiser hubs on the local network. param (optional) min_search_time: min seconds to wait for responses before returning param (optional) max_search_time: max seconds to wait for responses before returning return: list of discovered hubs """ timeout = 0 zeroconf = Zeroconf() services = ["_http._tcp.local."] ServiceBrowser( zeroconf, services, handlers=[self._zeroconf_on_service_state_change] ) while ( len(self._discovered_hubs) < 1 or timeout < min_search_time * 10 ) and timeout < max_search_time * 10: sleep(0.1) timeout += 1 zeroconf.close() return self._discovered_hubs