Ejemplo n.º 1
0
def test_receive_with_timeout():
    class RecvBehaviour(OneShotBehaviour):
        async def run(self):
            self.agent.recv_msg = await self.receive(5.0)
            self.kill()

    agent = make_connected_agent()

    msg = Message(body="received body")
    template = Template(body="received body")
    behaviour = RecvBehaviour()
    agent.add_behaviour(behaviour, template)
    assert behaviour.mailbox_size() == 0

    future = agent.start(auto_register=False)
    future.result()
    agent._message_received(msg.prepare())
    assert agent.is_alive()
    assert agent.has_behaviour(behaviour)

    behaviour.join()

    assert agent.recv_msg.body == "received body"
    assert agent.recv_msg == msg

    agent.stop()
Ejemplo n.º 2
0
def test_match_false_metadata_with_different_key():
    template = Template()
    template.metadata = {"performative": "query"}

    message = Message()
    message.set_metadata("language", "query")

    assert not template.match(message)
Ejemplo n.º 3
0
def test_match_ior():
    t1 = Template()
    t1.sender = "sender1@host"
    t2 = Template()
    t2.to = "recv1@host"
    t2.metadata = {"performative": "query"}

    m1 = Message()
    m1.sender = "sender1@host"

    t1 |= t2

    assert t1.match(m1)

    m2 = Message()
    m2.to = "recv1@host"
    m2.metadata = {"performative": "query"}

    assert t1.match(m2)

    m3 = Message()
    m3.sender = "sender2@host"
    m3.to = "recv1@host"
    m3.metadata = {"performative": "inform"}

    assert not t1.match(m3)
Ejemplo n.º 4
0
def test_match_false_to():
    template = Template()
    template.to = "recv1@host"

    message = Message()

    assert not template.match(message)

    message.to = "recv2@host"

    assert not template.match(message)
Ejemplo n.º 5
0
 async def send_agent(self, request):
     agent_jid = request.match_info['agentjid']
     form = await request.post()
     body = form["message"]
     logger.info("Sending message to {}: {}".format(agent_jid, body))
     msg = Message(to=agent_jid, sender=str(self.agent.jid), body=body)
     aioxmpp_msg = msg.prepare()
     await self.agent.stream.send(aioxmpp_msg)
     msg.sent = True
     self.agent.traces.append(msg)
     raise aioweb.HTTPFound("/spade/agent/{agentjid}/".format(agentjid=agent_jid))
Ejemplo n.º 6
0
def test_match_false_body():
    template = Template()
    template.body = "Hello World"

    message = Message()

    assert not template.match(message)

    message.body = "Bye Bye Love"

    assert not template.match(message)
Ejemplo n.º 7
0
def test_match_false_thread():
    template = Template()
    template.thread = "thread-id"

    message = Message()

    assert not template.match(message)

    message.thread = "thread-id-false"

    assert not template.match(message)
Ejemplo n.º 8
0
def test_match_false_metadata():
    template = Template()
    template.metadata = {"performative": "query"}

    message = Message()

    assert not template.match(message)

    message.set_metadata("performative", "inform")

    assert not template.match(message)
Ejemplo n.º 9
0
        async def run(self):
            print("InformBehav running")
            msg = Message(to=self.agent.recv_jid)  # Instantiate the message
            msg.set_metadata("performative", "inform")  # Set the "inform" FIPA performative
            msg.body = "Hello World {}".format(self.agent.recv_jid)  # Set the message content

            await self.send(msg)
            print("Message sent!")

            # stop agent from behaviour
            await self.agent.stop()
Ejemplo n.º 10
0
def test_thread_empty():
    msg = Message(thread=None)

    assert msg.thread is None
    assert msg.metadata == {}

    aiomsg = msg.prepare()
    for data in aiomsg.xep0004_data:
        if data.title == SPADE_X_METADATA:
            for field in data.fields:
                assert field.var != "_thread_node"
Ejemplo n.º 11
0
def test_match_false_sender():
    template = Template()
    template.sender = "sender2@host"

    message = Message()

    assert not template.match(message)

    message.sender = "sender1@host"

    assert not template.match(message)
Ejemplo n.º 12
0
def test_body_with_languages():
    msg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
    msg.body["en"] = "Hello World"
    msg.body["es"] = "Hola Mundo"

    new_msg = Message.from_node(msg)
    assert new_msg.body == "Hello World"
Ejemplo n.º 13
0
    def setup(self):
        self.web.start(templates_path="examples")
        template1 = Template(sender="agent0@fake_server")
        template2 = Template(sender="agent1@fake_server")
        template3 = Template(sender="agent2@fake_server")
        template4 = Template(sender="agent3@fake_server")

        # Create some dummy behaviours
        dummybehav = self.DummyBehav()
        self.add_behaviour(dummybehav, template=template1)
        periodbehav = self.DummyPeriodBehav(period=12.7)
        self.add_behaviour(periodbehav, template=template2)
        timeoutbehav = self.DummyTimeoutBehav(start_at=datetime.datetime.now())
        self.add_behaviour(timeoutbehav, template=template3)
        fsm_behav = self.DummyFSMBehav()
        self.add_behaviour(fsm_behav, template=template4)
        behavs = [dummybehav, periodbehav, timeoutbehav, fsm_behav]

        # Create some fake contacts
        self.add_fake_contact("agent0@fake_server", PresenceType.AVAILABLE)
        self.add_fake_contact("agent1@fake_server", PresenceType.AVAILABLE, show=PresenceShow.AWAY)
        self.add_fake_contact("agent2@fake_server", PresenceType.AVAILABLE, show=PresenceShow.DO_NOT_DISTURB)
        self.add_fake_contact("agent3@fake_server", PresenceType.UNAVAILABLE)
        self.add_fake_contact("agent4@fake_server", PresenceType.AVAILABLE, show=PresenceShow.CHAT)
        self.add_fake_contact("agent5@fake_server", PresenceType.UNAVAILABLE)

        # Send and Receive some fake messages
        self.traces.reset()
        for i in range(20):
            number = random.randint(0, 3)
            from_ = JID.fromstr("agent{}@fake_server".format(number))
            msg = aioxmpp.Message(from_=from_, to=self.jid, type_=MessageType.CHAT)
            msg.body[None] = "Hello from {}! This is a long message.".format(from_.localpart)
            msg = Message.from_node(msg)
            msg.metadata = {"performative": "inform", "acl-representation": "xml"}
            msg = msg.prepare()
            self._message_received(msg=msg)
            msg = Message(sender=str(self.jid), to=str(from_), body="This is my answer.")
            msg.sent = True
            self.traces.append(msg, category=str(behavs[number]))
Ejemplo n.º 14
0
def test_behaviour_match_without_template():
    class TestBehaviour(OneShotBehaviour):
        async def run(self):
            pass

    behaviour = TestBehaviour()

    msg = Message()
    msg.sender = "sender1@host"
    msg.to = "recv1@host"
    msg.body = "Hello World"
    msg.thread = "thread-id"
    msg.set_metadata("performative", "query")

    assert behaviour.match(msg)
Ejemplo n.º 15
0
    def _message_received(self, msg):
        """
        Callback run when an XMPP Message is reveived.
        This callback delivers the message to every behaviour
        that is waiting for it. First, the aioxmpp.Message is
        converted to spade.message.Message

        Args:
          msg (aioxmpp.Messagge): the message just received.

        Returns:
            list(asyncio.Future): a list of futures of the append of the message at each matched behaviour.

        """

        msg = Message.from_node(msg)
        return self.dispatch(msg)
Ejemplo n.º 16
0
    def _message_received(self, msg):
        """
        Callback run when an XMPP Message is reveived.
        This callback delivers the message to every behaviour
        that is waiting for it. First, the aioxmpp.Message is
        converted to spade.message.Message

        Args:
          msg (aioxmpp.Messagge): the message just received.

        Returns:
            list(asyncio.Future): a list of futures of the append of the message at each matched behaviour.

        """

        msg = Message.from_node(msg)
        return self.dispatch(msg)
Ejemplo n.º 17
0
def test_receive_without_behaviours():
    agent = make_connected_agent()
    aiomsg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
    msg = Message.from_node(aiomsg)

    assert agent.traces.len() == 0
    future = agent.start(auto_register=False)
    assert future.result() is None

    with LogCapture() as log:
        agent._message_received(aiomsg)
        log.check_present(('spade.Agent', 'WARNING', f"No behaviour matched for message: {msg}"))

    assert agent.traces.len() == 1
    assert msg in agent.traces.store[0]

    agent.stop()
Ejemplo n.º 18
0
    async def refuse_transport(self, transport_id):
        """
        Sends an ``spade.message.Message`` to a transport to refuse a travel proposal for charge.
        It uses the REQUEST_PROTOCOL and the REFUSE_PERFORMATIVE.

        Args:
            transport_id (str): The Agent JID of the transport
        """
        reply = Message()
        reply.to = str(transport_id)
        reply.set_metadata("protocol", REQUEST_PROTOCOL)
        reply.set_metadata("performative", REFUSE_PERFORMATIVE)
        content = {}
        reply.body = json.dumps(content)

        await self.send(reply)
        logger.debug(
            "Station {} refused proposal for charge from transport {}".format(
                self.agent.name, transport_id))
Ejemplo n.º 19
0
    async def cancel_proposal(self, customer_id, content=None):
        """
        Send a ``spade.message.Message`` to cancel a proposal.
        If the content is empty the proposal is sent without content.

        Args:
            customer_id (str): the id of the customer
            content (dict, optional): the optional content of the message
        """
        if content is None:
            content = {}
        logger.info("Transport {} sent cancel proposal to customer {}".format(
            self.agent.name, customer_id))
        reply = Message()
        reply.to = customer_id
        reply.set_metadata("protocol", REQUEST_PROTOCOL)
        reply.set_metadata("performative", CANCEL_PERFORMATIVE)
        reply.body = json.dumps(content)
        await self.send(reply)
Ejemplo n.º 20
0
    async def cancel_customer(self, data=None):
        """
        Sends a message to the current assigned customer to cancel the assignment.

        Args:
            data (dict, optional): Complementary info about the cancellation
        """
        logger.error("Transport {} could not get a path to customer {}.".format(self.agent_id,
                                                                                self.get("current_customer")))
        if data is None:
            data = {}
        reply = Message()
        reply.to = self.get("current_customer")
        reply.set_metadata("protocol", REQUEST_PROTOCOL)
        reply.set_metadata("performative", CANCEL_PERFORMATIVE)
        reply.body = json.dumps(data)
        logger.debug("Transport {} sent cancel proposal to customer {}".format(self.agent_id,
                                                                               self.get("current_customer")))
        await self.send(reply)
Ejemplo n.º 21
0
 async def send_get_managers(self, content=None):
     """
     Sends an ``spade.message.Message`` to the DirectoryAgent to request a managers.
     It uses the QUERY_PROTOCOL and the REQUEST_PERFORMATIVE.
     If no content is set a default content with the type_service that needs
     Args:
         content (dict): Optional content dictionary
     """
     if content is None or len(content) == 0:
         content = self.agent.fleet_type
     msg = Message()
     msg.to = str(self.agent.directory_id)
     msg.set_metadata("protocol", QUERY_PROTOCOL)
     msg.set_metadata("performative", REQUEST_PERFORMATIVE)
     msg.body = content
     await self.send(msg)
     logger.info("Customer {} asked for managers to directory {} for type {}.".format(self.agent.name,
                                                                                      self.agent.directory_id,
                                                                                      self.agent.type_service))
Ejemplo n.º 22
0
        async def run(self):
            print(
                "[InformBehav] Comportamiento encargado de enviar la información recopilada al ReglasDifusasAgent en proceso..."
            )
            print("[InformBehav] Enviando información recopilada...")
            msg = Message(to="*****@*****.**"
                          )  # Instantiate the message
            msg.set_metadata("performative",
                             "inform")  # Set the "inform" FIPA performative
            msg.set_metadata(
                "ontology",
                "myOntology")  # Set the ontology of the message content
            msg.set_metadata(
                "language", "OWL-S")  # Set the language of the message content
            #msg.body = "{'Hello': 2}"			        # Set the message content
            msg.body = str(self.agent.dict_team)

            await self.send(msg)
            print("[InformBehav] Enviado el siguiente mensaje: ")
            print(msg)

            #si hemos hecho las lecturas cesamos el comportamiento
            self.kill(exit_code=10)
 async def negotiate_end(self, behav, msg_guid, start_date, end_date,
                         receiver, delete_meeting):
     move_meeting_inform = Message(to=receiver)
     move_meeting_inform.set_metadata('performative', 'inform')
     move_meeting_inform.set_metadata('type', 'move_meeting_inform')
     move_meeting_inform.body = json.dumps({
         'meeting_guid':
         msg_guid,
         'start_date':
         time_to_str(start_date),
         'end_date':
         time_to_str(end_date),
         "delete_meeting":
         delete_meeting
     })
     await behav.send(move_meeting_inform)
Ejemplo n.º 24
0
def test_match_not():
    t1 = Template()
    t1.sender = "sender1@host"
    t1.to = "recv1@host"
    t1.metadata = {"performative": "query"}

    m1 = Message()
    m1.sender = "sender1@host"

    assert (~t1).match(m1)

    m2 = Message()
    m2.sender = "sender1@host"
    m2.to = "recv1@host"

    assert (~t1).match(m2)

    m3 = Message()
    m3.sender = "sender1@host"
    m3.to = "recv1@host"
    m3.metadata = {"performative": "query"}

    assert not (~t1).match(m3)
Ejemplo n.º 25
0
def test_match():
    template = Template()
    template.sender = "sender1@host"
    template.to = "recv1@host"
    template.body = "Hello World"
    template.thread = "thread-id"
    template.metadata = {"performative": "query"}

    message = Message()
    message.sender = "sender1@host"
    message.to = "recv1@host"
    message.body = "Hello World"
    message.thread = "thread-id"
    message.set_metadata("performative", "query")

    assert template.match(message)
Ejemplo n.º 26
0
    async def run(self):
        response = self.request.make_reply()
        response.metadata = {'request_id': self.reqId}

        further_req = Message(to=self.source,
                              metadata={'request_id': self.reqId},
                              body=self.request.body)

        await self.send(further_req)

        resp = await self.receive(timeout=10)
        print(f'{self.__class__.__name__}: received {resp}')
        if resp:
            response.body = resp.body
        else:
            response.body = "Error"
        print(f'{self.__class__.__name__}: sending ' + str(response))
        await self.send(response)
Ejemplo n.º 27
0
def test_receive_without_behaviours():
    agent = make_connected_agent()
    aiomsg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
    msg = Message.from_node(aiomsg)

    assert agent.traces.len() == 0
    future = agent.start(auto_register=False)
    assert future.result() is None

    with LogCapture() as log:
        agent._message_received(aiomsg)
        log.check_present(('spade.Agent', 'WARNING',
                           f"No behaviour matched for message: {msg}"))

    assert agent.traces.len() == 1
    assert msg in agent.traces.store[0]

    agent.stop()
Ejemplo n.º 28
0
    async def run(self):
        msg = await self.receive(timeout=5)

        if msg:
            performative = msg.get_metadata("performative")
            transport_id = msg.sender
            if performative == CANCEL_PERFORMATIVE:
                logger.warning(
                    "Station {} received a CANCEL from Transport {}.".format(
                        self.agent.name, transport_id))
                await self.agent.deassigning_place()
            elif (performative == ACCEPT_PERFORMATIVE
                  ):  # comes from send_confirmation_travel
                if self.agent.get_status() == FREE_STATION:
                    logger.info(
                        "Station {} has a place to charge transport {}".format(
                            self.agent.name, transport_id))
                    # confirm EXPLICITLY to transport it can start charging
                    reply = Message()
                    reply.to = str(transport_id)
                    reply.set_metadata("protocol", REQUEST_PROTOCOL)
                    reply.set_metadata("performative", ACCEPT_PERFORMATIVE)
                    content = {"station_id": self.agent.name}
                    reply.body = json.dumps(content)
                    await self.send(reply)
                    await self.agent.assigning_place()
                    # self.agent.assigning_place()

                else:  # self.agent.get_status() == BUSY_STATION
                    # time statistics update
                    if len(self.agent.waiting_list) == 0:
                        self.agent.transports_in_queue_time = time.time()
                    # transport waits in a waiting_list until it is available to charge
                    self.agent.waiting_list.append(str(transport_id))
                    # list length statistics update
                    self.agent.queue_length = len(self.agent.waiting_list)
                    if self.agent.queue_length > self.agent.max_queue_length:
                        self.agent.max_queue_length = self.agent.queue_length
                    logger.info(
                        "{} is waiting at {}, whose waiting list is {}".format(
                            transport_id, self.agent.name,
                            self.agent.waiting_list))
Ejemplo n.º 29
0
async def test_get_messages(test_client, loop):
    agent = Agent("jid@server", "password")
    agent.web.setup_routes()
    client = await test_client(agent.web.app)

    # add messages to trace
    for i in range(5):
        msg = Message(body=str(i), sender="{}@server".format(i), to="receiver@server")
        agent.traces.append(msg)

    response = await client.get("/messages/")
    response = await response.text()

    sel = Selector(text=response)

    assert len(sel.css("ul.timeline > li").getall()) == 6  # num messages + end clock

    agent.stop()
Ejemplo n.º 30
0
 async def run(self):
     msg = Message()
     msg.set_metadata(PERFORMATIVE, PERFORMATIVE_GET)
     msg.to = self.agent.service_jid
     msg.body = json.dumps({NAME: service, TEAM: self.agent.team})
     await self.send(msg)
     result = await self.receive(timeout=LONG_RECEIVE_WAIT)
     if result:
         result = json.loads(result.body)
         logger.info("{} got {} troops that offer {} service: {}".format(self.agent.name, len(result), service, result))
         self.agent.bdi.set_belief(service, tuple(result))
     else:
         self.agent.bdi.set_belief(service, tuple())
Ejemplo n.º 31
0
    async def run(self):
        msg = await self.receive(timeout=1)
        if msg:
            tick_id = msg.get_metadata("fx_tick_id")
            tick = await fx_db.get_fx_tick(tick_id)

            tick.epoch += 60
            tick.quote = tick.quote % 105 / 100

            msg = Message(to=get_xmpp_username(users['publisher']['username']))
            msg.set_metadata("stream", "publish_stream")
            msg.set_metadata("data_key", "prediction")
            msg.set_metadata(
                "data_value",
                json.dumps(
                    {'prediction': {
                        "epoch": tick.epoch,
                        "quote": tick.quote
                    }}))
            await self.send(msg)
Ejemplo n.º 32
0
        async def run(self):
            msg = await self.receive(timeout=TIMEOUT)
            if msg:
                search = msg.get_metadata("search")
                sender = cleanSender(msg.sender)

                print("## REQUEST FOR SEARCHING FOR FILES")
                print(f"Searching files by {search}")
                print(f"from {sender}")

                listOfFiles = self.findFilesByNamePart(search)
                stringList = json.dumps(listOfFiles)

                msg = Message(to=sender)
                msg.set_metadata("job", "listOfFiles")
                msg.set_metadata("search", search)
                msg.set_metadata("files", stringList)
                # print(f"Sending {msg}")
                await self.send(msg)
            print()
Ejemplo n.º 33
0
 async def send_registration(self):
     """
     Send a ``spade.message.Message`` with a proposal to directory to register.
     """
     logger.info(
         "Station {} sent proposal to register to directory {}".format(
             self.agent.name, self.agent.directory_id))
     content = {
         "jid": str(self.agent.jid),
         "type": self.agent.station_type,
         "status": self.agent.status,
         "position": self.agent.get_position(),
         "charge": self.agent.power
     }
     msg = Message()
     msg.to = str(self.agent.directory_id)
     msg.set_metadata("protocol", REGISTER_PROTOCOL)
     msg.set_metadata("performative", REQUEST_PERFORMATIVE)
     msg.body = json.dumps(content)
     await self.send(msg)
Ejemplo n.º 34
0
 async def send_registration(self):
     """
     Send a ``spade.message.Message`` with a proposal to manager to register.
     """
     logger.info(
         "Transport {} sent proposal to register to manager {}".format(self.agent.name, self.agent.fleetmanager_id))
     content = {
         "name": self.agent.name,
         "jid": str(self.agent.jid),
         "fleet_type": self.agent.fleet_type,
         "speed": float("{0:.2f}".format(self.agent.animation_speed)) if self.agent.animation_speed else None,
         "position": [float("{0:.6f}".format(coord)) for coord in self.get("current_pos")], 
         "trust": self.agent.trust,
     }
     msg = Message()
     msg.to = str(self.agent.fleetmanager_id)
     msg.set_metadata("protocol", REGISTER_PROTOCOL)
     msg.set_metadata("performative", REQUEST_PERFORMATIVE)
     msg.body = json.dumps(content)
     await self.send(msg)
Ejemplo n.º 35
0
 async def run(self):
     self.agent.log.debug('Retrieving data from Data Agent')
     msg = Message(to="[email protected]")
     msg.set_metadata("performative", "inform")
     msg.set_metadata("ontology", "history")
     msg.body = self.agent.currency_symbol
     await self.send(msg)
     reply = await self.receive(100)
     if reply is not None:
         self.agent.records = jsonpickle.loads(reply.body)
         self.agent.training_records = list(
             map(
                 lambda x: x.close,
                 sorted(filter(lambda x: x.time > 1514678400,
                               self.agent.records),
                        key=lambda x: x.time)))
         self.agent.records_ready.release()
Ejemplo n.º 36
0
    async def accept_transport(self, transport_id):
        """
        Sends a ``spade.message.Message`` to a transport to accept a travel proposal.
        It uses the REQUEST_PROTOCOL and the ACCEPT_PERFORMATIVE.

        Args:
            transport_id (str): The Agent JID of the transport
        """
        reply = Message()
        reply.to = str(transport_id)
        reply.set_metadata("protocol", REQUEST_PROTOCOL)
        reply.set_metadata("performative", ACCEPT_PERFORMATIVE)
        content = {
            "customer_id": str(self.agent.jid),
            "origin": self.agent.current_pos,
            "dest": self.agent.dest
        }
        reply.body = json.dumps(content)
        await self.send(reply)
        self.agent.transport_assigned = str(transport_id)
        logger.info("Customer {} accepted proposal from transport {}".format(self.agent.name, transport_id))
Ejemplo n.º 37
0
 def _send(agent, term, intention):
     receivers = asp.grounded(term.args[0], intention.scope)
     if isinstance(receivers, str) or isinstance(
             receivers, asp.Literal):
         receivers = (receivers, )
     ilf = asp.grounded(term.args[1], intention.scope)
     if not asp.is_atom(ilf):
         return
     ilf_type = ilf.functor
     mdata = {
         "performative": "BDI",
         "ilf_type": ilf_type,
     }
     for receiver in receivers:
         body = asp.asl_str(
             asp.freeze(term.args[2], intention.scope, {}))
         msg = Message(to=str(receiver), body=body, metadata=mdata)
         self.agent.submit(self.send(msg))
     yield
Ejemplo n.º 38
0
    async def accept_transport(self, transport_id):
        """
        Sends a ``spade.message.Message`` to a transport to accept a travel proposal for charge.
        It uses the REQUEST_PROTOCOL and the ACCEPT_PERFORMATIVE.

        Args:
            transport_id (str): The Agent JID of the transport
        """
        reply = Message()
        reply.to = str(transport_id)
        reply.set_metadata("protocol", REQUEST_PROTOCOL)
        reply.set_metadata("performative", INFORM_PERFORMATIVE)
        content = {
            "station_id": str(self.agent.jid),
            "dest": self.agent.current_pos
        }
        reply.body = json.dumps(content)
        await self.send(reply)
        logger.debug(
            "Station {} accepted proposal for charge from transport {}".format(
                self.agent.name, transport_id))
Ejemplo n.º 39
0
        async def connectWithPeer(self, myFile):
            print(
                "############### Conecting with peer with the file ###############"
            )
            name = input("Peer Name: ")
            msg = Message(to=name + "@jabber.at")
            msg.set_metadata("job", "connectFiles")
            msg.set_metadata("title", myFile)
            await self.send(msg)

            msg = await self.receive(timeout=TIMEOUT)
            if msg:
                print()
                print("Recived answer")
                fileAsked = msg.get_metadata("file")
                print("Files:")
                print(fileAsked)
            print()
Ejemplo n.º 40
0
        async def run(self):
            msg = await self.receive(timeout=TIMEOUT)
            if msg:
                title = msg.get_metadata("title")
                sender = cleanSender(msg.sender)

                print("## REQUEST FOR GETTING A FILE")
                print("title of asked file: {}".format(title))
                print("from: {}".format(sender))

                if title in self.direc:
                    listOfPeers = self.direc[title]
                else:
                    listOfPeers = []
                stringList = json.dumps(listOfPeers)

                msg = Message(to=sender)
                msg.set_metadata("job", "listOfPeers")
                msg.set_metadata("title", title)
                msg.set_metadata("list", stringList)
                await self.send(msg)
            print()
Ejemplo n.º 41
0
    def create_ev(cls, device, time, protocol_version):
        """
        This method creates the Create Ev message.

        Args:
            device: Device the message refers to.
            time: Simulation Time.
            protocol_version: Distinguish between schedulers.
        """
        if protocol_version == "1.0":
            mex = Message(to=cls.basejid + "/actormanager")
            message = "CREATE_EV [" + str(
                device.device.id) + "] " + device.device.capacity + " " + device.device.max_ch_pow_ac + " " + \
                      device.device.max_ch_pow_cc + " " + device.device.max_all_en + " " + device.device.min_all_en + \
                      " " + device.device.sb_ch + " " + device.device.sb_dis + " " + device.device.ch_eff + " " + \
                      device.device.dis_eff + " " + device.v2g + " " + str(time)
            mex.body = message
            return mex
        else:
            mex = Message(to=cls.basejid + "/" + cls.jid)
            message = '{"message" : {"subject" : "CREATE_EV" , "id" : "[' + str(
                device.device.id) + ']", "capacity" : " ' + str(
                    device.device.capacity
                ) + ' " , "max_ch_pow_ac" : " ' + str(
                    device.device.max_ch_pow_ac
                ) + ' " , "max_ch_pow_cc" : " ' + str(
                    device.device.max_ch_pow_cc
                ) + ' " , "max_dis_pow_ac" : " ' + str(
                    device.device.max_dis_pow_ac
                ) + ' " , "max_dis_pow_cc" : " ' + str(
                    device.device.max_dis_pow_cc
                ) + ' " , "max_all_en" : " ' + str(
                    device.device.max_all_en) + ' " , "min_all_en" : " ' + str(
                        device.device.min_all_en) + ' " , "sb_ch" : " ' + str(
                            device.device.sb_ch) + ' " , "sb_dis" : " ' + str(
                                device.device.sb_dis
                            ) + ' " , "ch_eff" :  " ' + str(
                                device.device.ch_eff
                            ) + ' " , "dis_eff": " ' + str(
                                device.device.dis_eff
                            ) + ' " , "v2g" : " ' + str(device.v2g) + ' "}}'
            mex.body = message
            mex.metadata = time
            return mex
Ejemplo n.º 42
0
    async def run(self):
        """[summary]
        """
        for contact in self.agent.available_contacts.copy():
            contact_data = self.agent.sent_data[contact]
            if ((len(contact_data) > 0)
                    and (contact_data[-1] == id(self.agent.cache[-1]))):
                continue

            to_send = []
            to_send_id = []
            for item in self.agent.cache:
                if id(item) in contact_data:
                    continue
                to_send.append(item)
                to_send_id.append(id(item))
            msg = Message(to=contact, body=str(orjson.dumps(to_send), "utf-8"))
            await self.send(msg)
            self.agent.sent_data[contact].extend(to_send_id)
            self._logger.debug(f"Sent to contact {contact} data {to_send}")
Ejemplo n.º 43
0
    async def refuse_taxi(self, taxi_id):
        """
        Sends an ``spade.message.Message`` to a taxi to refuse a travel proposal.
        It uses the REQUEST_PROTOCOL and the REFUSE_PERFORMATIVE.

        Args:
            taxi_id (str): The Agent JID of the taxi
        """
        reply = Message()
        reply.to = str(taxi_id)
        reply.set_metadata("protocol", REQUEST_PROTOCOL)
        reply.set_metadata("performative", REFUSE_PERFORMATIVE)
        content = {
            "passenger_id": str(self.agent.jid),
            "origin": self.agent.current_pos,
            "dest": self.agent.dest
        }
        reply.body = json.dumps(content)

        await self.send(reply)
        self.logger.debug("Passenger {} refused proposal from taxi {}".format(self.agent.name,
                                                                              taxi_id))
Ejemplo n.º 44
0
 async def first_handshake(self, message: Message):
     """
     Send the first message for the handshake, with the action I choose to do.
     Then the agent send back his action.
     :param message:
     """
     to_send = message.make_reply()
     my_action_key = self.__pick_my_actions()
     to_send.set_metadata("performative", "inform")
     to_send.body = my_action_key
     logger.info("Sending my chose action to the other agent")
     await self.send(to_send)
     reply = await self.receive(100)
     reply_verif = Template()
     reply_verif.set_metadata("performative", "inform")
     if reply_verif.match(reply):
         logger.info("Received the action of the other agent")
         self.my_actions = self.coord_action.actions[my_action_key]
         self.actions_remaining.remove(my_action_key)
         self.actions_remaining.remove(reply.body)
Ejemplo n.º 45
0
    async def inform_objectives(self, behaviour):

        msg = Message()
        msg.set_metadata(PERFORMATIVE, PERFORMATIVE_OBJECTIVE)
        content = {
            X: self.map.get_target_x(),
            Y: self.map.get_target_y(),
            Z: self.map.get_target_z(),
        }
        msg.body = json.dumps(content)
        for agent in self.agents.values():
            msg.to = agent.jid
            logger.info("Sending objective to {}: {}".format(agent.jid, msg))
            await behaviour.send(msg)
        logger.info("Manager: Sending Objective notification to agents")
Ejemplo n.º 46
0
 async def run(self):
     msg = Message()
     msg.set_metadata(PERFORMATIVE, PERFORMATIVE_GET)
     msg.to = self.agent.service_jid
     msg.body = json.dumps({NAME: BACKUP_SERVICE, TEAM: self.agent.team})
     await self.send(msg)
     result = await self.receive(timeout=LONG_RECEIVE_WAIT)
     if result:
         result = json.loads(result.body)
         self.agent.soldiers_count = len(result)
         logger.info("{} got {} fieldops: {}".format(self.agent.name, self.agent.soldiers_count, result))
         self.agent.bdi.set_belief(MY_BACKUPS, tuple(result))
     else:
         self.agent.bdi.set_belief(MY_BACKUPS, tuple())
         self.agent.soldiers_count = 0
Ejemplo n.º 47
0
        async def run(self):
            print("Čekam poruku...")
            message = await self.receive(timeout=DEFAULT_TIMEOUT)
            if message:
                reply = Message(to=str(message.sender))
                reply.set_metadata("performative", "confirmation")
                reply.set_metadata("ontology", "device")

                status = True
                for voltmeter in voltmeters:
                    voltage = voltmeter.getValue()
                    status = status and voltage > 200 and voltage < 250

                reply.body = "OK" if status else "ERROR"
                await self.send(reply)
            else:
                print(
                    f"Nije bilo upita u posljednjih {DateTimeUtils.secondsToHumanTime(DEFAULT_TIMEOUT)}"
                )
Ejemplo n.º 48
0
 async def run(self):
     option = int(self.internMenu())
     msg = Message(to="*****@*****.**")  # Instcdantiate the message
     msg.set_metadata("performative",
                      "inform")  # Set the "inform" FIPA performative
     # msg.body = "Hello World"                    # Set the message content
     if option == 1:
         msg.body = "Archivo"
         await self.send(msg)
     elif option == 2:
         msg.body = "Tipo"
         await self.send(msg)
     elif option == 3:
         msg.body = "Cpu"
         await self.send(msg)
     elif option == 0:
         self.kill()
     else:
         print("Opcion no disponible, intenta nuevamente")
Ejemplo n.º 49
0
def test_message_from_node():
    aiomsg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
    data = forms_xso.Data(type_=forms_xso.DataType.FORM)

    data.fields.append(
        forms_xso.Field(
            var="performative",
            type_=forms_xso.FieldType.TEXT_SINGLE,
            values=["request"],
        )
    )

    data.fields.append(forms_xso.Field(var="_thread_node",
                                       type_=forms_xso.FieldType.TEXT_SINGLE,
                                       values=["thread-id"]))
    data.title = SPADE_X_METADATA
    aiomsg.xep0004_data = [data]

    msg = Message.from_node(aiomsg)

    assert msg.thread == "thread-id"
    assert msg.get_metadata("performative") == "request"
    assert msg.metadata == {"performative": "request"}
Ejemplo n.º 50
0
def test_body_set_none():
    msg = Message()
    msg.body = None
Ejemplo n.º 51
0
def test_match_xor():
    t1 = Template()
    t1.sender = "sender1@host"
    t2 = Template()
    t2.to = "recv1@host"
    t2.metadata = {"performative": "query"}

    m1 = Message()
    m1.sender = "sender1@host"

    assert (t1 ^ t2).match(m1)

    m2 = Message()
    m2.to = "recv1@host"
    m2.metadata = {"performative": "query"}

    assert (t1 ^ t2).match(m2)

    m3 = Message()
    m3.sender = "sender2@host"
    m3.to = "recv1@host"
    m3.metadata = {"performative": "inform"}

    assert not (t1 ^ t2).match(m3)

    t1 = Template()
    t1.sender = "sender1@host"
    t2 = Template()
    t2.sender = "sender1@host"
    m4 = Message()
    m4.sender = "sender1@host"

    assert not (t1 ^ t2).match(m4)
Ejemplo n.º 52
0
def test_to_set_string():
    msg = Message()
    msg.to = "agent@fakeserver"
Ejemplo n.º 53
0
def test_thread_set_none():
    msg = Message()
    msg.thread = None
Ejemplo n.º 54
0
def test_sender_set_not_string():
    msg = Message()
    with pytest.raises(TypeError):
        msg.sender = 1000
Ejemplo n.º 55
0
def test_message_from_node_attribute_error():
    with pytest.raises(AttributeError) as e:
        Message.from_node(Message())
Ejemplo n.º 56
0
def test_thread_set_string():
    msg = Message()
    msg.thread = "thread_id_001"
Ejemplo n.º 57
0
def test_sender_set_string():
    msg = Message()
    msg.sender = "agent@fakeserver"
Ejemplo n.º 58
0
def test_thread_set_not_string():
    msg = Message()
    with pytest.raises(TypeError):
        msg.thread = 1000
Ejemplo n.º 59
0
def test_to_set_none():
    msg = Message()
    msg.to = None
Ejemplo n.º 60
0
def test_sender_set_none():
    msg = Message()
    msg.sender = None