Ejemplo n.º 1
0
    def do_request(self, msg):
        """
        Performs a request. The only requirement
        of `msg` is that it has an `id` attribute.

        Publishing of the request is always yielded to prevent multiple messages
        from going over the same pipe. The returned future is for the response.

        :param msg: Message object to publish
        :return:
        """
        msg_id = str(self.get_id_from_msg(msg))
        request_type = str(self.get_request_type_from_msg(msg))
        req, cb = self._get_response_map(request_type)

        if msg_id in req:
            raise RuntimeError(
                    "Duplicate request ID: `{}` for type `{}`".format(
                            msg_id, request_type))

        future = Future()
        req[msg_id] = None
        cb[msg_id] = future
        yield From(self.publisher.publish(msg))
        raise Return(future)
Ejemplo n.º 2
0
    def insert_robot(self,
                     tree,
                     pose,
                     name=None,
                     initial_battery=0.0,
                     parents=None):
        """
        Inserts a robot into the world. This consists of two steps:

        - Sending the insert request message
        - Receiving a ModelInfo response

        This method is a coroutine because of the first step, writing
        the message must be yielded since PyGazebo doesn't appear to
        support writing multiple messages simultaneously. For the response,
        i.e. the message that confirms the robot has been inserted, a
        future is returned.

        :param tree:
        :type tree: Tree
        :param pose: Insertion pose
        :type pose: Pose
        :param name: Robot name
        :type name: str
        :param initial_battery: Initial battery level
        :param parents:
        :return: A future that resolves with the created `Robot` object.
        """
        robot_id = self.get_robot_id()
        robot_name = "gen__"+str(robot_id) \
            if name is None else str(name)

        robot = tree.to_robot(robot_id)
        sdf = self.get_simulation_sdf(robot=robot,
                                      robot_name=robot_name,
                                      initial_battery=initial_battery)
        sdf.elements[0].set_pose(pose)

        if self.output_directory:
            robot_file_path = os.path.join(self.output_directory,
                                           'robot_{}.sdf'.format(robot_id))
            with open(robot_file_path, 'w') as f:
                f.write(str(sdf))

        return_future = Future()
        insert_future = yield From(self.insert_model(sdf))
        # TODO: Unhandled error in exception handler. Fix this.
        # insert_future.add_done_callback(lambda fut: self._robot_inserted(
        #         robot_name=robot_name,
        #         tree=tree,
        #         robot=robot,
        #         initial_battery=initial_battery,
        #         parents=parents,
        #         msg=fut.result(),
        #         return_future=return_future
        # ))
        raise Return(return_future)
Ejemplo n.º 3
0
def multi_future(children, quiet_exceptions=()):
    """
    Wraps multiple futures in a single future.
    :param quiet_exceptions:
    :param children:
    """
    if isinstance(children, dict):
        keys = list(children.keys())
        children = children.values()
    else:
        keys = None
    unfinished_children = set(children)

    future = Future()
    if not children:
        future.set_result({} if keys is not None else [])

    def callback(f):
        unfinished_children.remove(f)
        if not unfinished_children:
            result_list = []
            for f in children:
                try:
                    result_list.append(f.result())
                except Exception as e:
                    if future.done():
                        if not isinstance(e, quiet_exceptions):
                            print("Multiple exceptions in yield list",
                                  file=sys.stderr)
                    else:
                        future.set_exception(sys.exc_info())
            if not future.done():
                if keys is not None:
                    future.set_result(dict(zip(keys, result_list)))
                else:
                    future.set_result(result_list)

    listening = set()
    for f in children:
        if f not in listening:
            listening.add(f)
            f.add_done_callback(callback)

    return future
Ejemplo n.º 4
0
def multi_future(children, quiet_exceptions=()):
    """
    Wraps multiple futures in a single future.
    :param quiet_exceptions:
    :param children:
    """
    if isinstance(children, dict):
        keys = list(children.keys())
        children = children.values()
    else:
        keys = None
    unfinished_children = set(children)

    future = Future()
    if not children:
        future.set_result({} if keys is not None else [])

    def callback(f):
        unfinished_children.remove(f)
        if not unfinished_children:
            result_list = []
            for f in children:
                try:
                    result_list.append(f.result())
                except Exception as e:
                    if future.done():
                        if not isinstance(e, quiet_exceptions):
                            print("Multiple exceptions in yield list", file=sys.stderr)
                    else:
                        future.set_exception(sys.exc_info())
            if not future.done():
                if keys is not None:
                    future.set_result(dict(zip(keys, result_list)))
                else:
                    future.set_result(result_list)

    listening = set()
    for f in children:
        if f not in listening:
            listening.add(f)
            f.add_done_callback(callback)

    return future
Ejemplo n.º 5
0
        def execute(script):
            future = Future()
            graph = GraphDatabase(url="ws://localhost:8182/",
                                  username="******",
                                  password="******",
                                  loop=self.loop,
                                  future_class=Future)
            future_conn = graph.connect()

            def cb(f):
                conn = f.result()
                stream = conn.send(script)
                future.set_result(stream)

            future_conn.add_done_callback(cb)

            return future
Ejemplo n.º 6
0
 def inner(*args, **kwargs):
     new_future = Future()
     new_future.set_result(result)
     return new_future
Ejemplo n.º 7
0
@asyncio.coroutine
def connect_coro(future, url):
    sock = socket.socket()
    fno = sock.fileno()
    logger.debug(fno)
    sock.connect((url, 80))
    sock.setblocking(0)
    yield From(selector(fno, 1, sock.send, 'GET / HTTP/1.0\n\n\n'))
    result = yield From(selector(fno, 0, sock.recv, 2000))
    future.set_result(result)


def got_result(future):
    print future.result()


future1 = Future()
future2 = Future()

jobs = [
    connect_coro(future1, 'ledge.co.za'),
    connect_coro(future2, 'google.com')
]

future1.add_done_callback(got_result)
future2.add_done_callback(got_result)

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(jobs))
loop.close()