示例#1
0
class Discover(object):
    def __init__(self, type='', advertiser_name='', service_name='', found_func=None, error_func=None):
        self.type = type
        self.results = {}  # uuid => set(results)

        discover = self

        def found(seeker, result):
            for uuid in discover.results:
                if result.uuid == uuid:
                    return
            logger.info("Found "+result.type+":"+result.sname+" at "+result.address)

        def on_error(*args, **kwargs):
            logger.error('on Discover', args, kwargs)

        self.seeker = Seeker(stype=self.type, aname=advertiser_name, sname=service_name, timeout=1.0,
                             find_callback=found_func or found, error_callback=error_func or on_error)
        self.thread = gevent.spawn(self.run_forever)
        logger.debug("Discover "+self.type+" started.")

    def __del__(self):
        self.thread.kill()
        logger.debug("Discover "+self.type+"closed.")

    def run_forever(self):
        while True:
            results = self.seeker.run()
            origin_results = set()
            for result_value in self.results.values():
                origin_results |= result_value
            results_to_add = results - origin_results
            results_to_remove = origin_results - results

            # remove first
            for result in results_to_remove:
                uuid = result.uuid
                self.results[uuid].remove(result)
                if len(self.results[uuid]) is 0:
                    del self.results[uuid]

            # then add missing
            for result in results_to_add:
                uuid = result.uuid
                if uuid not in self.results:
                    self.results[uuid] = set()
                self.results[uuid].add(result)

            gevent.sleep(0)
示例#2
0
    def __init__(self, type='', advertiser_name='', service_name='', found_func=None, error_func=None):
        self.type = type
        self.results = {}  # uuid => set(results)

        discover = self

        def found(seeker, result):
            for uuid in discover.results:
                if result.uuid == uuid:
                    return
            logger.info("Found "+result.type+":"+result.sname+" at "+result.address)

        def on_error(*args, **kwargs):
            logger.error('on Discover', args, kwargs)

        self.seeker = Seeker(stype=self.type, aname=advertiser_name, sname=service_name, timeout=1.0,
                             find_callback=found_func or found, error_callback=error_func or on_error)
        self.thread = gevent.spawn(self.run_forever)
        logger.debug("Discover "+self.type+" started.")