Exemplo n.º 1
0
class DandelionApp:

    def __init__(self, config_file=None):
        self._config_manager = ConfigurationManager(config_file)
    
    def start_server(self): 
        self._server = Server(self._config_manager.local_address, 
                              self._config_manager.local_port, 
                              self._config_manager.server,  #info_dict
                              self._config_manager.content_db) 
        self._server.start()
    
    def start_content_synchronizer(self): 
        self._synchronizer = Synchronizer(self._config_manager.local_address,
                                          self._config_manager.local_port,
                                          self._config_manager.type,
                                          self._config_manager.content_db)
        self._synchronizer.start()
    
    def run_ui(self): 
        
        self._ui = UI(self._config_manager.ui,  #dict 
                      self._config_manager.content_db,
                      self._server, 
                      self._synchronizer)
        self._ui.run()
    
    def exit(self):
        self._synchronizer.stop()
        self._server.stop()
Exemplo n.º 2
0
    def test_play_match(self):
        server = Server()
        server.start(False)

        client1 = Client('localhost', 8081)
        client2 = Client('localhost', 8081)

        client1_moves = [(1, 1), (2, 2), (3, 3)]
        client2_moves = [(3, 1), (3, 2)]

        client1.on_move_required = lambda ct: (client1_moves
                                               if ct else client2_moves).pop(0)
        client1.on_game_over = lambda winner: self.assertTrue(winner)

        client2.on_move_required = lambda ct: (client1_moves
                                               if ct else client2_moves).pop(0)
        client2.on_game_over = lambda winner: self.assertTrue(winner)

        client1.start(False)
        client2.start(False)

        client1.wait()
        client2.wait()

        server.stop()
Exemplo n.º 3
0
class DandelionApp:
    def __init__(self, config_file=None):
        self._config_manager = ConfigurationManager(config_file)

    def start_server(self):
        self._server = Server(
            self._config_manager.local_address,
            self._config_manager.local_port,
            self._config_manager.server,  # info_dict
            self._config_manager.content_db,
        )
        self._server.start()

    def start_content_synchronizer(self):
        self._synchronizer = Synchronizer(
            self._config_manager.local_address,
            self._config_manager.local_port,
            self._config_manager.type,
            self._config_manager.content_db,
        )
        self._synchronizer.start()

    def run_ui(self):

        self._ui = UI(
            self._config_manager.ui, self._config_manager.content_db, self._server, self._synchronizer  # dict
        )
        self._ui.run()

    def exit(self):
        self._synchronizer.stop()
        self._server.stop()
Exemplo n.º 4
0
 def run(self):
     server = Server(self.port)
     server.start()
     while not self.stopped:
         requests = server.get_requests()
         for r in requests:
             nums = r.split(',')
             self.connected = True
             if len(nums) == 2:
                 self.connected = True
                 self.depth_queue.append(int(nums[0]))
                 self.angle = int(nums[1])
             response = "{},{},{},{},{}\n".format(
                 self.convert(-self.m_front_left),
                 self.convert(-self.m_front_right),
                 self.convert(-self.m_back_left),
                 self.convert(-self.m_back_right),
                 self.convert(self.m_tail))
             response = response.encode('utf-8')
             server.offer_data(r, response)
             break
     server.stop()
Exemplo n.º 5
0
def run(ip, port):
    """
    handler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    log = logging.getLogger('kademlia')
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)
    """
    loop = asyncio.get_event_loop()
    loop.set_debug(True)

    server = Server(storage=storage.AwesomeStorage())
    loop.run_until_complete(server.listen(int(port), ip))

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.stop()
        loop.close()
Exemplo n.º 6
0
import sys
import logging
import asyncio
import storage

from network import Server

# Usage: <python3> <node_ip> <node_port> <bootstrap_node_ip> <bootstrap_node_port>

loop = asyncio.get_event_loop()
loop.set_debug(True)

server = Server(storage=storage.AwesomeStorage())
loop.run_until_complete(server.listen(int(sys.argv[2]), sys.argv[1]))
bootstrap_node = (sys.argv[3], int(sys.argv[4]))
loop.run_until_complete(server.bootstrap([bootstrap_node]))

try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    server.stop()
    loop.close()
Exemplo n.º 7
0
class Dispatcher(Service):
    """Handles communication from drone and devices."""

    ITEM_FPS        = 'FPS'
    ITEM_MAKESPAN   = '~Makespan'
    ITEM_THROUGHPUT = '~Throughput'

    def __init__(self, controller=None):
        Service.__init__(self, 'dispatcher')

        self.handlers[Message.TYPE_LOGIN] = self.handle_login
        self.handlers[Message.TYPE_IMAGE] = self.handle_image
        self.handlers[Message.TYPE_RESULT] = self.handle_result

        self.server = Server(self, cfg.SERVER_PORT)
        self.protocols = {}

        self.nodes = {}

        if cfg.DASHBOARD:
            self.dashboard = Dashboard()
            self.dashboard.start()

        else:
            self.dashboard = None

        measure_period = float(cfg.CONTROLLER_LOOP_TIME)/cfg.MEASURES_PER_LOOP
        self.monitor = Monitor(self.process_measurements, measure_period)
        self.monitor.register_item(self.ITEM_FPS, Monitor.ITEM_RATE)
        self.monitor.register_item(self.ITEM_MAKESPAN, Monitor.ITEM_AVG)
        self.monitor.register_item(self.ITEM_THROUGHPUT, Monitor.ITEM_RATE)

        self.controller = controller
        self.controller.dashboard = self.dashboard
        self.controller.dispatcher = self

        if self.dashboard:
            self.dashboard.controller = controller

        self.imagebuf = Queue.Queue()   # Buffer of encoded images
                                        # (time stamp, image data)

        # Initialize probe to blank image
        self.probe_image = self.generate_probe_image()

        self.tokens = Queue.Queue()
        self.job_id = 0

        self.job_image_cache = {}

        self.sub_loop = 0
        return

    def handle_login(self, protocol, msg):
        """Handles device logins."""
        name = msg.name
        self.log().info("'%s' login", name)

        protocol.name = name
        self.protocols[name] = protocol

        if not self.controller is None:
            self.controller.logon(name)

        if name != cfg.CAMERA_NAME:
            self.nodes[name] = Node(name)
            self.tokens.put(name)

        return

    def handle_image(self, protocol, msg):
        """Handles images."""

        if self.monitor:
            self.monitor.update_item(self.ITEM_FPS, 1)

        if self.dashboard:
            image = cv2.imdecode(msg.data, cv2.IMREAD_UNCHANGED)
            self.dashboard.put_image(image)

        self.imagebuf.put((time.time(), msg.data))
        self.probe_image = msg.data
        return

    def handle_result(self, protocol, msg):
        """Handles result."""
        try:
            name = protocol.name
        except AttributeError:
            self.log().warning("result from protocol with no name")
            thread.interrupt_main()
            return

        job = msg.data
        job.end = time.time()

        if job.probe:
            prefix = 'probe '
        else:
            prefix = ''

        # Update system stats
        makespan = job.end - job.start
        proc_time = job.left - job.arrived
        rtt = makespan - proc_time

        now = job.end
        suffix = ''

        # Ignore probe jobs
        if not job.probe:
            self.monitor.update_item(self.ITEM_MAKESPAN, makespan)

            if job.deadline >= now:
                self.monitor.update_item(self.ITEM_THROUGHPUT, 1)
            else:
                suffix = 'late'

            # Display result if image is cached
            if self.dashboard:
                if name in self.job_image_cache:
                    cache = self.job_image_cache[name]
                    if cache[0] == job.job_id:
                        image = cv2.imdecode(cache[1], cv2.IMREAD_UNCHANGED)
                        self.dashboard.put_result((image, job.data))

        self.log().info("%sjob %d completed by '%s' %s", prefix, job.job_id,
                        name, suffix)
        self.log().debug(job)

        self.log().debug('%sjob %d makespan: %0.6f', prefix, job.job_id, makespan)
        self.log().debug('%sjob %d proc_time: %0.6f', prefix, job.job_id, proc_time)
        self.log().debug('%sjob %d rtt: %0.6f', prefix, job.job_id, rtt)

        proc_rate = cfg.PIPELINES[job.pipeline][1][name[:3]]/proc_time

        # Update device stats
        node = self.nodes[name]
        with node.lock:
            node.processing_rate.add(proc_rate)
            node.rtt.add(rtt)

        self.log().debug('node updated %s', node)

        self.tokens.put(name)
        return

    def process_measurements(self, values):
        """Handles measurements from a Monitor."""
        self.log().debug('measurements: %s', values)

        self.sub_loop += 1
        self.sub_loop %= cfg.MEASURES_PER_LOOP

        if self.controller:
            self.controller.put_metrics(values)

            if self.sub_loop == 0:
                self.controller.loop()

            cvalues = self.controller.get_values()
            values.update(cvalues)

        values['nodes'] = self.nodes
        values['imagebuf'] = self.imagebuf.qsize()

        if self.dashboard:
            self.dashboard.put_values(values)

        return

    def start(self):
        """Starts the dispatcher server."""
        self.log().info('starting dispatcher')

        if self.monitor:
            self.monitor.start()

        if self.controller:
            self.controller.start()

        self.server.run()   # Blocking call
        return

    def stop(self):
        """Stops the dispatcher server."""
        self.log().info('stopping dispatcher')

        if self.monitor:
            self.monitor.stop()

        if self.dashboard:
            self.dashboard.stop()

        if self.controller:
            self.controller.stop()

        self.server.stop()
        return

    def disconnected(self, protocol):
        """Handles device disconnections."""
        try:
            name = protocol.name
        except AttributeError:
            self.log().warning("disconnected protocol has no name")
            return

        self.protocols.pop(name, None)
        self.log().info("'%s' disconnected", name)

        if not self.controller is None:
            self.controller.logoff(name)

        if name != cfg.CAMERA_NAME:
            del self.nodes[name]

        self.job_image_cache.pop(name, None)

        return

    def send_params(self, name, params):
        """Sends settings to client."""

        protocol = self.protocols.get(name)
        if not protocol is None:
            msg = Message(self.name, Message.TYPE_PARAMS, params)
            protocol.send(msg)

        else:
            self.log().warn("send_params: protocol '%s' not found", name)

        return

    def next_job_id(self):
        """Returns next job id."""
        job_id = self.job_id
        self.job_id += 1
        return job_id

    def generate_probe_image(self):
        """Generate random blank image for probing."""
        # Note: Due to the randomness, this will likely be larger in (encoded)
        # size than an image from the drone

        blank = np.random.randint(0, 256, (480, 640, 3), np.uint8)
        params = [cv2.IMWRITE_JPEG_QUALITY, 50]

        ret, image_data = cv2.imencode('.jpg', blank, params)
        if ret:
            return image_data
        else:
            thread.interrupt_main()

    def probe(self, name, pipeline):
        """Sends fake job to a device to probe."""

        protocol = self.protocols.get(name)
        if protocol:
            job = Job(self.next_job_id(), pipeline, self.probe_image, True)
            msg = Message(self.name, Message.TYPE_JOB, job)

            self.log().info("sending job %d to '%s'", job.job_id, name)
            self.log().debug('%s', job)
            protocol.send(msg)

        else:
            self.log().warn("probe: protocol '%s' not found", name)

        return

    def send_job(self, name, pipeline, image, timestamp, deadline):
        """Sends jobs to devices."""

        protocol = self.protocols.get(name)
        if protocol:
            job = Job(self.next_job_id(), pipeline, image)
            job.start = timestamp
            job.deadline = deadline

            msg = Message(self.name, Message.TYPE_JOB, job)

            self.log().info("sending job %d to '%s'", job.job_id, name)
            self.log().debug('%s', job)
            protocol.send(msg)

            # Cache images for results display
            if cfg.SHOW_RESULTS:
                self.job_image_cache[name] = (job.job_id, job.data)

        else:
            self.log().warn("send_job: protocol '%s' not found", name)

        return