コード例 #1
0
ファイル: test_base.py プロジェクト: vishalbelsare/agents-aea
def test_envelope_initialisation():
    """Testing the envelope initialisation."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = Message(content="hello")
    msg.counterparty = receiver_address
    assert Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=msg,
    ), "Cannot generate a new envelope"

    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=msg,
    )

    envelope.to = "ChangedAgent"
    envelope.sender = "ChangedSender"
    envelope.protocol_id = "my_changed_protocol"
    envelope.message = b"HelloWorld"

    assert envelope.to == "ChangedAgent", "Cannot set to value on Envelope"
    assert envelope.sender == "ChangedSender", "Cannot set sender value on Envelope"
    assert (
        envelope.protocol_id == "my_changed_protocol"
    ), "Cannot set protocol_id on Envelope "
    assert envelope.message == b"HelloWorld", "Cannot set message on Envelope"
    assert envelope.context.uri_raw is not None
コード例 #2
0
    def handle(self, message: Message, sender: str) -> None:
        """
        Implement the reaction to a message.

        :param message: the message
        :param sender: the sender
        :return: None
        """
        # convenience representations
        fipa_msg = cast(FIPAMessage, message)
        msg_performative = FIPAMessage.Performative(message.get('performative'))
        message_id = cast(int, message.get("message_id"))

        # recover dialogue
        dialogues = cast(Dialogues, self.context.dialogues)
        if dialogues.is_belonging_to_registered_dialogue(fipa_msg, sender, self.context.agent_public_key):
            dialogue = cast(Dialogue, dialogues.get_dialogue(fipa_msg, sender, self.context.agent_public_key))
            dialogue.incoming_extend(fipa_msg)
        else:
            self._handle_unidentified_dialogue(fipa_msg, sender)
            return

        # handle message
        if msg_performative == FIPAMessage.Performative.PROPOSE:
            self._handle_propose(fipa_msg, sender, message_id, dialogue)
        elif msg_performative == FIPAMessage.Performative.DECLINE:
            self._handle_decline(fipa_msg, sender, message_id, dialogue)
        elif msg_performative == FIPAMessage.Performative.MATCH_ACCEPT_W_ADDRESS:
            self._handle_match_accept(fipa_msg, sender, message_id, dialogue)
        elif msg_performative == FIPAMessage.Performative.INFORM:
            self._handle_inform(fipa_msg, sender, message_id, dialogue)
コード例 #3
0
    def handle(self, message: Message) -> None:
        """
        Handle an internal message from the skills.

        :param message: the internal message
        :return: None
        """
        message.counterparty = uuid4().hex  # TODO: temporary fix only
        message.is_incoming = True
        self.decision_maker_handler.handle(message)
コード例 #4
0
ファイル: test_base.py プロジェクト: hame58gp/agents-aea
    def test_to(self):
        """Test the 'to' attribute getter and setter."""
        message = Message()
        with pytest.raises(ValueError, match="Message's 'To' field must be set."):
            message.to

        message.to = "to"
        assert message.to == "to"

        with pytest.raises(AEAEnforceError, match="To already set."):
            message.to = "to"
コード例 #5
0
ファイル: test_base.py プロジェクト: ejfitzgerald/agents-aea
    def test_to(self):
        """Test the 'to' attribute getter and setter."""
        message = Message()
        with pytest.raises(AssertionError, match="To must not be None."):
            message.to

        message.to = "to"
        assert message.to == "to"

        with pytest.raises(AssertionError, match="To already set."):
            message.to = "to"
コード例 #6
0
    def _message_to_percept(self, message: Message) -> Feedback:
        """
        Transform the message received from the gym environment into observation, reward, done, info.

        :param: the message received as a response to the action performed in apply_action.
        :return: the standard feedback (observation, reward, done, info) of a gym environment.
        """
        observation = cast(Any, message.get("observation"))
        reward = cast(float, message.get("reward"))
        done = cast(bool, message.get("done"))
        info = cast(dict, message.get("info"))

        return observation, reward, done, info
コード例 #7
0
ファイル: base.py プロジェクト: hame58gp/agents-aea
 def _check_consistency(message: Message, to: str, sender: str) -> Message:
     """Check consistency of sender and to."""
     if message.has_to:
         enforce(message.to == to,
                 "To specified on message does not match envelope.")
     else:
         message.to = to
     if message.has_sender:
         enforce(
             message.sender == sender,
             "Sender specified on message does not match envelope.",
         )
     else:
         message.sender = sender
     return message
コード例 #8
0
ファイル: serialization.py プロジェクト: Physsix27/agents-aea
    def encode(self, msg: Message) -> bytes:
        """
        Decode the message.

        :param msg: the message object
        :return: the bytes
        """
        performative = GymMessage.Performative(msg.get("performative"))
        new_body = copy.copy(msg.body)
        new_body["performative"] = performative.value

        if performative == GymMessage.Performative.ACT:
            action = msg.body["action"]  # type: Any
            action_bytes = base64.b64encode(
                pickle.dumps(action)).decode("utf-8")
            new_body["action"] = action_bytes
            new_body["step_id"] = msg.body["step_id"]
        elif performative == GymMessage.Performative.PERCEPT:
            # observation, reward and info are gym implementation specific, done is boolean
            observation = msg.body["observation"]  # type: Any
            observation_bytes = base64.b64encode(
                pickle.dumps(observation)).decode("utf-8")
            new_body["observation"] = observation_bytes
            reward = msg.body["reward"]  # type: Any
            reward_bytes = base64.b64encode(
                pickle.dumps(reward)).decode("utf-8")
            new_body["reward"] = reward_bytes
            info = msg.body["info"]  # type: Any
            info_bytes = base64.b64encode(pickle.dumps(info)).decode("utf-8")
            new_body["info"] = info_bytes
            new_body["step_id"] = msg.body["step_id"]

        gym_message_bytes = json.dumps(new_body).encode("utf-8")
        return gym_message_bytes
コード例 #9
0
ファイル: serialization.py プロジェクト: 8ball030/agents-aea
    def encode(self, msg: Message) -> bytes:
        """
        Decode the message.

        :param msg: the message object
        :return: the bytes
        """
        oef_type = OEFMessage.Type(msg.get("type"))
        new_body = copy.copy(msg.body)
        new_body["type"] = oef_type.value

        if oef_type in {OEFMessage.Type.REGISTER_SERVICE, OEFMessage.Type.UNREGISTER_SERVICE}:
            service_description = msg.body["service_description"]  # type: Description
            service_description_bytes = base64.b64encode(pickle.dumps(service_description)).decode("utf-8")
            new_body["service_description"] = service_description_bytes
        elif oef_type in {OEFMessage.Type.REGISTER_AGENT, OEFMessage.Type.UNREGISTER_AGENT}:
            agent_description = msg.body["agent_description"]  # type: Description
            agent_description_bytes = base64.b64encode(pickle.dumps(agent_description)).decode("utf-8")
            new_body["agent_description"] = agent_description_bytes
        elif oef_type in {OEFMessage.Type.SEARCH_SERVICES, OEFMessage.Type.SEARCH_AGENTS}:
            query = msg.body["query"]  # type: Query
            query_bytes = base64.b64encode(pickle.dumps(query)).decode("utf-8")
            new_body["query"] = query_bytes
        elif oef_type in {OEFMessage.Type.SEARCH_RESULT}:
            # we need this cast because the "agents" field might contains
            # the Protobuf type "RepeatedScalarContainer", which is not JSON serializable.
            new_body["agents"] = list(msg.body["agents"])
        elif oef_type in {OEFMessage.Type.OEF_ERROR}:
            operation = msg.body["operation"]
            new_body["operation"] = str(operation)

        oef_message_bytes = json.dumps(new_body).encode("utf-8")
        return oef_message_bytes
コード例 #10
0
def test_envelope_initialisation():
    """Testing the envelope initialisation."""
    msg = Message(content="hello")
    message_bytes = ProtobufSerializer().encode(msg)
    assert Envelope(
        to="Agent1",
        sender="Agent0",
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=message_bytes,
    ), "Cannot generate a new envelope"

    envelope = Envelope(
        to="Agent1",
        sender="Agent0",
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=message_bytes,
    )

    envelope.to = "ChangedAgent"
    envelope.sender = "ChangedSender"
    envelope.protocol_id = "my_changed_protocol"
    envelope.message = b"HelloWorld"

    assert envelope.to == "ChangedAgent", "Cannot set to value on Envelope"
    assert envelope.sender == "ChangedSender", "Cannot set sender value on Envelope"
    assert (envelope.protocol_id == "my_changed_protocol"
            ), "Cannot set protocol_id on Envelope "
    assert envelope.message == b"HelloWorld", "Cannot set message on Envelope"
    assert envelope.context.uri_raw is not None
コード例 #11
0
ファイル: handlers.py プロジェクト: pbukva/agents-aea
    def handle(self, message: Message) -> None:
        """
        Implement the reaction to a message.

        :param message: the message
        :return: None
        """
        # convenience representations
        fipa_msg = cast(FipaMessage, message)
        msg_performative = FipaMessage.Performative(
            message.get("performative"))

        # recover dialogue
        dialogues = cast(Dialogues, self.context.dialogues)
        if dialogues.is_belonging_to_registered_dialogue(
                fipa_msg, self.context.agent_address):
            dialogue = cast(
                Dialogue,
                dialogues.get_dialogue(fipa_msg, self.context.agent_address))
            dialogue.incoming_extend(fipa_msg)
        else:
            self._handle_unidentified_dialogue(fipa_msg)
            return

        # handle message
        if msg_performative == FipaMessage.Performative.PROPOSE:
            self._handle_propose(fipa_msg, dialogue)
        elif msg_performative == FipaMessage.Performative.DECLINE:
            self._handle_decline(fipa_msg, dialogue)
        elif msg_performative == FipaMessage.Performative.MATCH_ACCEPT_W_INFORM:
            self._handle_match_accept(fipa_msg, dialogue)
        elif msg_performative == FipaMessage.Performative.INFORM:
            self._handle_inform(fipa_msg, dialogue)
コード例 #12
0
ファイル: dialogues.py プロジェクト: 8ball030/agents-aea
    def get_dialogue(self, fipa_msg: Message, sender: Address,
                     agent_pbk: Address) -> Dialogue:
        """
        Retrieve dialogue.

        :param fipa_msg: the fipa message
        :param sender_pbk: the sender public key
        :param agent_pbk: the public key of the agent

        :return: the dialogue
        """
        fipa_msg = cast(FIPAMessage, fipa_msg)
        dialogue_reference = cast(Tuple[str, str],
                                  fipa_msg.get("dialogue_reference"))
        self_initiated_dialogue_label = DialogueLabel(dialogue_reference,
                                                      sender, agent_pbk)
        other_initiated_dialogue_label = DialogueLabel(dialogue_reference,
                                                       sender, sender)
        if other_initiated_dialogue_label in self.dialogues:
            other_initiated_dialogue = cast(
                FIPADialogue, self.dialogues[other_initiated_dialogue_label])
            if other_initiated_dialogue.is_valid_next_message(fipa_msg):
                result = other_initiated_dialogue
        if self_initiated_dialogue_label in self.dialogues:
            self_initiated_dialogue = cast(
                FIPADialogue, self.dialogues[self_initiated_dialogue_label])
            if self_initiated_dialogue.is_valid_next_message(fipa_msg):
                result = self_initiated_dialogue
        if result is None:
            raise ValueError('Should have found dialogue.')
        return result
コード例 #13
0
    def update(self, message: Message) -> bool:
        """
        Extend the list of incoming/outgoing messages with 'message', if 'message' is valid.

        :param message: a message to be added
        :return: True if message successfully added, false otherwise
        """
        if (message.is_incoming and self.last_message is not None
                and self.last_message.message_id == self.STARTING_MESSAGE_ID
                and self.dialogue_label.dialogue_reference[1]
                == self.OPPONENT_STARTER_REFERENCE):
            self._update_self_initiated_dialogue_label_on_second_message(
                message)

        counterparty = None  # type: Optional[str]
        try:
            counterparty = message.counterparty
        except AssertionError:
            message.counterparty = self.dialogue_label.dialogue_opponent_addr

        if counterparty is not None:
            assert (
                message.counterparty ==
                self.dialogue_label.dialogue_opponent_addr
            ), "The counterparty specified in the message is different from the opponent in this dialogue."

        is_extendable = self.is_valid_next_message(message)
        if is_extendable:
            if message.is_incoming:
                self._incoming_messages.extend([message])
            else:
                self._outgoing_messages.extend([message])
        return is_extendable
コード例 #14
0
    def _update_self_initiated_dialogue_label_on_second_message(
        self, second_message: Message
    ) -> None:
        """
        Update this (self initiated) dialogue's dialogue_label with a complete dialogue reference from counterparty's first message

        :param second_message: The second message in the dialogue (the first by the counterparty)
        :return: None
        """
        dialogue_reference = cast(
            Tuple[str, str], second_message.get("dialogue_reference")
        )
        self_initiated_dialogue_reference = (dialogue_reference[0], "")
        self_initiated_dialogue_label = DialogueLabel(
            self_initiated_dialogue_reference,
            second_message.counterparty,
            self.agent_address,
        )

        if not self.is_empty:
            message_id = second_message.message_id

            if (
                self.dialogue_label == self_initiated_dialogue_label
                and self.last_message.message_id == 1  # type: ignore
                and message_id == 2
                and second_message.is_incoming
            ):
                updated_dialogue_label = DialogueLabel(
                    dialogue_reference,
                    self_initiated_dialogue_label.dialogue_opponent_addr,
                    self_initiated_dialogue_label.dialogue_starter_addr,
                )
                self._dialogue_label = updated_dialogue_label
コード例 #15
0
ファイル: test_mail.py プロジェクト: 8ball030/agents-aea
def test_envelope_initialisation():
    """Testing the envelope initialisation."""
    msg = Message(content='hello')
    message_bytes = ProtobufSerializer().encode(msg)
    assert Envelope(to="Agent1",
                    sender="Agent0",
                    protocol_id="my_own_protocol",
                    message=message_bytes), "Cannot generate a new envelope"

    envelope = Envelope(to="Agent1",
                        sender="Agent0",
                        protocol_id="my_own_protocol",
                        message=message_bytes)

    envelope.to = "ChangedAgent"
    envelope.sender = "ChangedSender"
    envelope.protocol_id = "my_changed_protocol"
    envelope.message = b"HelloWorld"

    assert envelope.to == "ChangedAgent", "Cannot set to value on Envelope"
    assert envelope.sender == "ChangedSender",\
                              "Cannot set sender value on Envelope"
    assert envelope.protocol_id == "my_changed_protocol",\
                                   "Cannot set protocol_id on Envelope "
    assert envelope.message == b"HelloWorld", "Cannot set message on Envelope"
コード例 #16
0
    def _update_self_initiated_dialogue_label_on_second_message(
        self, second_message: Message
    ) -> None:
        """
        Update a self initiated dialogue label with a complete dialogue reference from counterparty's first message

        :param second_message: The second message in the dialogue (the first by the counterparty in a self initiated dialogue)
        :return: None
        """
        dialogue_reference = cast(
            Tuple[str, str], second_message.get("dialogue_reference")
        )

        self_initiated_dialogue_reference = (dialogue_reference[0], "")
        self_initiated_dialogue_label = DialogueLabel(
            self_initiated_dialogue_reference,
            second_message.counterparty,
            self.agent_address,
        )

        if self_initiated_dialogue_label in self.dialogues:
            self_initiated_dialogue = self.dialogues[self_initiated_dialogue_label]
            self.dialogues.pop(self_initiated_dialogue_label)
            final_dialogue_label = DialogueLabel(
                dialogue_reference,
                self_initiated_dialogue_label.dialogue_opponent_addr,
                self_initiated_dialogue_label.dialogue_starter_addr,
            )
            self_initiated_dialogue._dialogue_label = final_dialogue_label
            assert self_initiated_dialogue.dialogue_label not in self.dialogues
            self.dialogues.update(
                {self_initiated_dialogue.dialogue_label: self_initiated_dialogue}
            )
コード例 #17
0
    def _get_dialogue(self, message: Message) -> Optional[Dialogue]:
        """
        Retrieve the dialogue 'message' belongs to.

        :param message: a message
        :return: the dialogue, or None in case such a dialogue does not exist
        """
        dialogue_reference = cast(Tuple[str, str], message.get("dialogue_reference"))
        counterparty = message.counterparty

        self_initiated_dialogue_label = DialogueLabel(
            dialogue_reference, counterparty, self.agent_address
        )
        other_initiated_dialogue_label = DialogueLabel(
            dialogue_reference, counterparty, counterparty
        )

        if other_initiated_dialogue_label in self.dialogues:
            result = self.dialogues[
                other_initiated_dialogue_label
            ]  # type: Optional[Dialogue]
        elif self_initiated_dialogue_label in self.dialogues:
            result = self.dialogues[self_initiated_dialogue_label]
        else:
            result = None

        return result
コード例 #18
0
ファイル: test_base.py プロジェクト: ejfitzgerald/agents-aea
def test_inbox_nowait():
    """Tests the inbox without waiting."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = Message(content="hello")
    msg.counterparty = receiver_address
    multiplexer = Multiplexer([_make_dummy_connection()])
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=msg,
    )
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)
    assert (inbox.get_nowait() == envelope
            ), "Check for a message on the in queue and wait for no time."
コード例 #19
0
ファイル: test_base.py プロジェクト: ejfitzgerald/agents-aea
    def test_performative(self):
        """Test message performative."""
        class SomePerformative(Message.Performative):
            value = "value"

        message = Message(performative=SomePerformative.value)
        assert message.performative == SomePerformative.value
        assert str(message.performative) == "value"
コード例 #20
0
    def encode(self, msg: Message) -> bytes:
        """Encode a 'default' message into bytes."""
        body = {}  # Dict[str, Any]

        msg_type = DefaultMessage.Type(msg.get("type"))
        body["type"] = str(msg_type.value)

        if msg_type == DefaultMessage.Type.BYTES:
            content = cast(bytes, msg.get("content"))
            body["content"] = base64.b64encode(content).decode("utf-8")
        elif msg_type == DefaultMessage.Type.ERROR:
            body["error_code"] = cast(str, msg.get("error_code"))
            body["error_msg"] = cast(str, msg.get("error_msg"))
            body["error_data"] = cast(str, msg.get("error_data"))
        else:
            raise ValueError("Type not recognized.")

        bytes_msg = json.dumps(body).encode("utf-8")
        return bytes_msg
コード例 #21
0
ファイル: test_base.py プロジェクト: vishalbelsare/agents-aea
def test_inbox_get():
    """Tests for a envelope on the in queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = Message(content="hello")
    msg.counterparty = receiver_address
    multiplexer = Multiplexer([_make_dummy_connection()])
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=msg,
    )
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)

    assert (
        inbox.get() == envelope
    ), "Checks if the returned envelope is the same with the queued envelope."
コード例 #22
0
    def get_dialogue(self, fipa_msg: Message, sender: Address, agent_pbk: Address) -> Dialogue:
        """
        Retrieve dialogue.

        :param fipa_msg: the fipa message
        :param sender_pbk: the sender public key
        :param agent_pbk: the public key of the agent

        :return: the dialogue
        """
        dialogue_id = cast(int, fipa_msg.get("dialogue_id"))
        opponent = sender
        target = cast(int, fipa_msg.get("target"))
        performative = fipa_msg.get("performative")
        self_initiated_dialogue_label = DialogueLabel(dialogue_id, opponent, agent_pbk)
        other_initiated_dialogue_label = DialogueLabel(dialogue_id, opponent, opponent)
        if performative == FIPAMessage.Performative.PROPOSE and target == PROPOSE_TARGET and self_initiated_dialogue_label in self.dialogues:
            dialogue = self.dialogues[self_initiated_dialogue_label]
        elif performative == FIPAMessage.Performative.ACCEPT:
            if target == ACCEPT_TARGET and other_initiated_dialogue_label in self.dialogues:
                dialogue = self.dialogues[other_initiated_dialogue_label]
            else:
                raise ValueError('Should have found dialogue.')
        elif performative == FIPAMessage.Performative.MATCH_ACCEPT:
            if target == MATCH_ACCEPT_TARGET and self_initiated_dialogue_label in self.dialogues:
                dialogue = self.dialogues[self_initiated_dialogue_label]
            else:
                raise ValueError('Should have found dialogue.')
        elif performative == FIPAMessage.Performative.DECLINE:
            if target == DECLINED_CFP_TARGET and self_initiated_dialogue_label in self.dialogues:
                dialogue = self.dialogues[self_initiated_dialogue_label]
            elif target == DECLINED_PROPOSE_TARGET and other_initiated_dialogue_label in self.dialogues:
                dialogue = self.dialogues[other_initiated_dialogue_label]
            elif target == DECLINED_ACCEPT_TARGET and self_initiated_dialogue_label in self.dialogues:
                dialogue = self.dialogues[self_initiated_dialogue_label]
            else:
                raise ValueError('Should have found dialogue.')
        else:
            raise ValueError('Should have found dialogue.')
        dialogue = cast(Dialogue, dialogue)
        return dialogue
コード例 #23
0
ファイル: utils.py プロジェクト: hame58gp/agents-aea
    def dummy_envelope(
        cls,
        to: str = "test",
        sender: str = "test",
        protocol_id: PublicId = DefaultMessage.protocol_id,
        message: Message = None,
    ) -> Envelope:
        """
        Create envelope, if message is not passed use .dummy_message method.

        :return: Envelope
        """
        message = message or cls.dummy_default_message()
        message.sender = sender
        message.to = to
        return Envelope(
            to=to,
            sender=sender,
            protocol_id=protocol_id,
            message=message,
        )
コード例 #24
0
    def handle(self, message: Message) -> None:
        """
        Implement the reaction to a message.

        :param message: the message
        :return: None
        """
        self.dialogue.update(message)
        self.handled_message = message
        message.counterparty = self.dialogue.dialogue_label.dialogue_opponent_addr
        self.dialogue.update(self.message_2)
        self.context.outbox.put_message(self.message_2)
コード例 #25
0
ファイル: test_mail.py プロジェクト: 8ball030/agents-aea
def test_inbox_nowait():
    """Tests the inbox without waiting."""
    msg = Message(content="hello")
    message_bytes = ProtobufSerializer().encode(msg)
    multiplexer = Multiplexer([DummyConnection()])
    envelope = Envelope(to="Agent1",
                        sender="Agent0",
                        protocol_id="my_own_protocol",
                        message=message_bytes)
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)
    assert inbox.get_nowait(
    ) == envelope, "Check for a message on the in queue and wait for no time."
コード例 #26
0
    def is_permitted_for_new_dialogue(self, fipa_msg: Message, sender: Address) -> bool:
        """
        Check whether a fipa message is permitted for a new dialogue.

        That is, the message has to
        - be a CFP, and
        - have the correct msg id and message target.

        :param message: the fipa message
        :param sender: the sender

        :return: a boolean indicating whether the message is permitted for a new dialogue
        """
        fipa_msg = cast(FIPAMessage, fipa_msg)
        msg_id = fipa_msg.get("id")
        target = fipa_msg.get("target")
        performative = fipa_msg.get("performative")

        result = performative == FIPAMessage.Performative.CFP \
            and msg_id == STARTING_MESSAGE_ID \
            and target == STARTING_MESSAGE_TARGET
        return result
コード例 #27
0
    def is_belonging_to_registered_dialogue(self, fipa_msg: Message, sender: Address, agent_pbk: Address) -> bool:
        """
        Check whether an agent message is part of a registered dialogue.

        :param fipa_msg: the fipa message
        :param sender: the sender
        :param agent_pbk: the public key of the agent

        :return: boolean indicating whether the message belongs to a registered dialogue
        """
        dialogue_id = cast(int, fipa_msg.get("dialogue_id"))
        opponent = sender
        target = cast(int, fipa_msg.get("target"))
        performative = fipa_msg.get("performative")
        self_initiated_dialogue_label = DialogueLabel(dialogue_id, opponent, agent_pbk)
        other_initiated_dialogue_label = DialogueLabel(dialogue_id, opponent, opponent)
        result = False
        if performative == FIPAMessage.Performative.PROPOSE and target == PROPOSE_TARGET and self_initiated_dialogue_label in self.dialogues:
            self_initiated_dialogue = cast(Dialogue, self.dialogues[self_initiated_dialogue_label])
            result = self_initiated_dialogue.is_expecting_propose()
        elif performative == FIPAMessage.Performative.ACCEPT:
            if target == ACCEPT_TARGET and other_initiated_dialogue_label in self.dialogues:
                other_initiated_dialogue = cast(Dialogue, self.dialogues[other_initiated_dialogue_label])
                result = other_initiated_dialogue.is_expecting_initial_accept()
        elif performative == FIPAMessage.Performative.MATCH_ACCEPT:
            if target == MATCH_ACCEPT_TARGET and self_initiated_dialogue_label in self.dialogues:
                self_initiated_dialogue = cast(Dialogue, self.dialogues[self_initiated_dialogue_label])
                result = self_initiated_dialogue.is_expecting_matching_accept()
        elif performative == FIPAMessage.Performative.DECLINE:
            if target == DECLINED_CFP_TARGET and self_initiated_dialogue_label in self.dialogues:
                self_initiated_dialogue = cast(Dialogue, self.dialogues[self_initiated_dialogue_label])
                result = self_initiated_dialogue.is_expecting_cfp_decline()
            elif target == DECLINED_PROPOSE_TARGET and other_initiated_dialogue_label in self.dialogues:
                other_initiated_dialogue = cast(Dialogue, self.dialogues[other_initiated_dialogue_label])
                result = other_initiated_dialogue.is_expecting_propose_decline()
            elif target == DECLINED_ACCEPT_TARGET and self_initiated_dialogue_label in self.dialogues:
                self_initiated_dialogue = cast(Dialogue, self.dialogues[self_initiated_dialogue_label])
                result = self_initiated_dialogue.is_expecting_accept_decline()
        return result
コード例 #28
0
    def update(self, message: Message) -> Optional[Dialogue]:
        """
        Update the state of dialogues with a new incoming message.

        If the message is for a new dialogue, a new dialogue is created with 'message' as its first message, and returned.
        If the message is addressed to an existing dialogue, the dialogue is retrieved, extended with this message and returned.
        If there are any errors, e.g. the message dialogue reference does not exists or the message is invalid w.r.t. the dialogue, return None.

        :param message: a new message
        :return: the new or existing dialogue the message is intended for, or None in case of any errors.
        """
        dialogue_reference = message.dialogue_reference

        if (  # new dialogue by other
                dialogue_reference[0] != "" and dialogue_reference[1] == ""
                and message.is_incoming):
            dialogue = self._create_opponent_initiated(
                dialogue_opponent_addr=message.counterparty,
                dialogue_reference=dialogue_reference,
                role=self._role_from_first_message(message),
            )  # type: Optional[Dialogue]
        elif (  # new dialogue by self
                dialogue_reference[0] != "" and dialogue_reference[1] == ""
                and not message.is_incoming):
            assert (
                message.counterparty is not None
            ), "The message counter-party field is not set {}".format(message)
            dialogue = self._create_self_initiated(
                dialogue_opponent_addr=message.counterparty,
                role=self._role_from_first_message(message),
            )
        else:  # existing dialogue
            self._update_self_initiated_dialogue_label_on_second_message(
                message)
            dialogue = self.get_dialogue(message)

        if dialogue is not None:
            if message.counterparty is None:
                message.counterparty = dialogue.dialogue_label.dialogue_opponent_addr
            else:
                assert (
                    message.counterparty ==
                    dialogue.dialogue_label.dialogue_opponent_addr
                ), "The counterparty specified in the message is different from the opponent in this dialogue."

            dialogue.update(message)
            result = dialogue  # type: Optional[Dialogue]
        else:  # couldn't find the dialogue
            result = None

        return result
コード例 #29
0
def test_outbox_put():
    """Tests that an envelope is putted into the queue."""
    msg = Message(content="hello")
    message_bytes = ProtobufSerializer().encode(msg)
    my_queue = Queue()
    envelope = Envelope(to="Agent1",
                        sender="Agent0",
                        protocol_id="my_own_protocol",
                        message=message_bytes)
    my_queue.put(envelope)
    _outbox = OutBox(my_queue)
    _outbox.put(envelope)
    assert _outbox.empty() is False,\
        "Oubox must not be empty after putting an envelope"
コード例 #30
0
ファイル: test_mail.py プロジェクト: 8ball030/agents-aea
def test_inbox_get():
    """Tests for a envelope on the in queue."""
    msg = Message(content="hello")
    message_bytes = ProtobufSerializer().encode(msg)
    multiplexer = Multiplexer([DummyConnection()])
    envelope = Envelope(to="Agent1",
                        sender="Agent0",
                        protocol_id="my_own_protocol",
                        message=message_bytes)
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)

    assert inbox.get(
    ) == envelope, "Checks if the returned envelope is the same with the queued envelope."