示例#1
0
 def action(self):
     # Setting a filter
     f = Filter()
     f.set_performative(ACLMessage.INFORM)  # Accept only INFORM messages
     message = self.read()
     if f.filter(message):  # Filtering the message
         display(self.agent, 'I received this list: \n%s' % message.content)
示例#2
0
 def action(self):
     f = Filter()
     f.set_performative(ACLMessage.REQUEST)
     f.set_ontology('foods')
     message = self.read()
     if f.filter(message):  # If the message satisfies the filter
         reply = message.create_reply()
         reply.set_content('meat\nchicken\ncookies\nice cream\nbread')
         reply.set_performative(ACLMessage.INFORM)
         self.agent.send(reply)
         display(self.agent,
                 'Food list sent to %s.' % message.sender.getLocalName())
示例#3
0
 def action(self):
     f = Filter()
     f.set_performative(ACLMessage.REQUEST)
     f.set_ontology('office')
     message = self.read()
     if f.filter(message):
         reply = message.create_reply()
         reply.set_content('pen\nclips\nscissors\npaper\npencil')
         reply.set_performative(ACLMessage.INFORM)
         self.agent.send(reply)
         display(
             self.agent, 'Office material list sent to %s.' %
             message.sender.getLocalName())
示例#4
0
class FipaProtocol(Behaviour):
    """ This class implements a basis for all FIPA-compliant
        protocols
    """
    def __init__(self, agent, message, is_initiator):
        """Inicializes the class that implements a FipaProtocol

            :param agent: instance of the agent that will execute the protocol's
                         established behaviours.
            :param message: message to be sent by the agent when is_initiator
                         parameter is true.
            :param is_initiator: boolean type parameter that specifies if the 
                         protocol instance will act as Initiator or Participant.

        """
        super(FipaProtocol, self).__init__(agent)

        self.is_initiator = is_initiator
        self.message = message

        self.filter_not_undestood = Filter()
        self.filter_not_undestood.set_performative(ACLMessage.NOT_UNDERSTOOD)

        if self.message is not None:
            self.filter_conversation_id = Filter()
            self.filter_conversation_id.set_conversation_id(
                self.message.conversation_id)

    def handle_not_understood(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_NOT_UNDERSTOOD type message 

            :param message: FIPA-ACL message
        """
        pass

    def execute(self, message):
        """This method overrides the execute method from Behaviour class.
            The selection of the method to be executed after the receival
            of a message is implemented here.

            :param message: FIPA-ACL message
        """
        super(FipaProtocol, self).execute(message)

        self.message = message

        if self.filter_not_undestood.filter(self.message):
            self.handle_not_understood(message)
示例#5
0
	def action(self):
		f = Filter()
		f.set_performative(ACLMessage.REQUEST)
		message = self.read()
		if f.filter(message):
			reply = message.create_reply()
			contact = self.search(message.content)
			if contact != None: # If the searched contact exists
				reply.set_performative(ACLMessage.INFORM)
				# Here we will serialize the object to send
				reply.set_content(pickle.dumps(contact))
			else: # If the searched contact doesn't exist
				reply.set_performative(ACLMessage.FAILURE)
				reply.set_content(pickle.dumps({'error': 404, 'description': 'Contact not found.'}))
			self.agent.send(reply)
示例#6
0
    def action(self):
        # Setting a filter
        f = Filter()
        f.set_performative(ACLMessage.REQUEST)  # Accept only REQUEST messages
        f.set_ontology('fruits')

        # Reveiving a message and filtering it
        message = self.read()
        if f.filter(message):  # If the message satisfies the filter
            reply = message.create_reply()
            reply.set_content(
                'apple\nbanana\ncocoa\ncoconuts\ngrape\norange\nstrawberry')
            reply.set_performative(ACLMessage.INFORM)
            self.agent.send(reply)
            display(self.agent,
                    'Fruit list sent to %s.' % message.sender.getLocalName())
示例#7
0
 def action(self):
     message = self.read()
     # Deserializing the received information
     contact = pickle.loads(message.content)
     # Filtering the message
     f = Filter()
     f.set_performative(ACLMessage.INFORM)
     if f.filter(message):
         template = 'Contact info: \nName: {name}\nPhone: {phone}\nE-mail: {email}'
         # Showing the deserialized data
         display(
             self.agent,
             template.format(name=contact['name'],
                             phone=contact['phone'],
                             email=contact['email']))
     elif message.performative == ACLMessage.FAILURE:
         # Showing the failure information
         display(
             self.agent, '{id}: {desc}'.format(id=contact['error'],
                                               desc=contact['description']))
示例#8
0
 def action(self):
     f = Filter()
     f.set_performative(ACLMessage.REQUEST)
     message = self.read()
     if f.filter(message):
         reply = message.create_reply()  # Creates a reply to sender
         contact = self.search(message.content)
         if contact != None:  # If the searched contact exists
             # Setting the performative of the reply to INFORM
             reply.set_performative(ACLMessage.INFORM)
             # Here we will serialize the object to send
             reply.set_content(pickle.dumps(contact))
         else:  # If the searched contact doesn't exist
             # Setting the performative of the reply to FAILURE
             reply.set_performative(ACLMessage.FAILURE)
             # Adding the reason of the FAILURE (using a dict)
             reply.set_content(
                 pickle.dumps({
                     'error': 404,
                     'description': 'Contact not found.'
                 }))
         self.send(reply)
示例#9
0
class FipaSubscribeProtocol(FipaProtocol):
    """This class implements the FipaSubscribeProtocol protocol,
        inheriting from the Behaviour class and implementing its methods.
    """
    def __init__(self, agent, message=None, is_initiator=True):
        """Initialize method
        """

        super(FipaSubscribeProtocol, self).__init__(agent, message,
                                                    is_initiator)

        self.subscribers = set()

        self.filter_protocol = Filter()
        self.filter_protocol.set_protocol(ACLMessage.FIPA_SUBSCRIBE_PROTOCOL)

        self.filter_subscribe = Filter()
        self.filter_subscribe.set_performative(ACLMessage.SUBSCRIBE)

        self.filter_agree = Filter()
        self.filter_agree.set_performative(ACLMessage.AGREE)

        self.filter_inform = Filter()
        self.filter_inform.set_performative(ACLMessage.INFORM)

        self.filter_refuse = Filter()
        self.filter_refuse.set_performative(ACLMessage.REFUSE)

        self.filter_cancel = Filter()
        self.filter_cancel.set_performative(ACLMessage.CANCEL)

        self.filter_failure = Filter()
        self.filter_failure.set_performative(ACLMessage.FAILURE)

    def on_start(self):
        """his method overrides the on_start method from Behaviour class
            and implements aditional settings to the initialize method
            of FipaSubscribeProtocol protocol.
        """
        super(FipaSubscribeProtocol, self).on_start()

        if self.is_initiator and self.message != None:
            if self.message.performative == ACLMessage.SUBSCRIBE:
                self.agent.send(self.message)
                # self.timed_behaviour()

    def handle_subscribe(self, message):
        """
            handle_subscribe

        """
        pass

    def handle_agree(self, message):
        """
            handle_agree

        """
        pass

    def handle_refuse(self, message):
        """
            handle_refuse

        """
        pass

    def handle_inform(self, message):
        """
            handle_inform

        """
        pass

    def handle_cancel(self, message):
        """
            handle_cancel

        """
        pass

    def execute(self, message):
        """This method overrides the execute method from FipaProtocol class.
            The selection of the method to be executed after the receival
            of a message is implemented here.

            :param message: FIPA-ACL message
        """
        super(FipaSubscribeProtocol, self).execute(message)

        if self.filter_protocol.filter(self.message):
            if self.filter_subscribe.filter(self.message):
                self.handle_subscribe(message)

            elif self.filter_cancel.filter(self.message):
                self.handle_cancel(message)

            elif self.filter_inform.filter(self.message):
                self.handle_inform(message)

            elif self.filter_agree.filter(self.message):
                self.handle_agree(message)

            elif self.filter_failure.filter(self.message):
                self.handle_failure(message)
            else:
                return

        else:
            return

    def register(self, aid):
        """register

        """
        self.subscribers.add(aid)

    def deregister(self, aid):
        """deregister

        """
        self.subscribers.remove(aid)

    def notify(self, message):
        """notify

        """
        for sub in self.subscribers:
            message.add_receiver(sub)
        self.agent.send(message)
示例#10
0
class FipaContractNetProtocol(FipaProtocol):
    """This class implements the FipaContractNetProtocol protocol,
        inheriting from the Behaviour class and implementing its methods.
    """
    def __init__(self, agent, message=None, is_initiator=True):
        """
        Inicializes the class that implements FipaContractNetProtocol protocol.

            :param agent: instance of the agent that will execute the protocol's
                         established behaviours.
            :param message: message to be sent by the agent when is_initiator
                         parameter is true.
            :param is_initiator: boolean type parameter that specifies if the 
                         protocol instance will act as Initiator or Participant.
        """
        super(FipaContractNetProtocol, self).__init__(agent, message,
                                                      is_initiator)

        self.received_qty = 0

        self.proposes = []

        self.filter_protocol = Filter()
        self.filter_protocol.set_protocol(
            ACLMessage.FIPA_CONTRACT_NET_PROTOCOL)

        self.filter_cfp = Filter()
        self.filter_cfp.set_performative(ACLMessage.CFP)

        self.filter_refuse = Filter()
        self.filter_refuse.set_performative(ACLMessage.REFUSE)

        self.filter_propose = Filter()
        self.filter_propose.set_performative(ACLMessage.PROPOSE)

        self.filter_accept_propose = Filter()
        self.filter_accept_propose.set_performative(ACLMessage.ACCEPT_PROPOSAL)

        self.filter_reject_propose = Filter()
        self.filter_reject_propose.set_performative(ACLMessage.REJECT_PROPOSAL)

        self.filter_failure = Filter()
        self.filter_failure.set_performative(ACLMessage.FAILURE)

        self.filter_inform = Filter()
        self.filter_inform.set_performative(ACLMessage.INFORM)

    def on_start(self):
        """This method overrides the on_start method from Behaviour class
            and implements aditional settings to the initialize method
            of FipaContractNetProtocol protocol.
        """
        super(FipaContractNetProtocol, self).on_start()

        if self.is_initiator and self.message is not None:

            if self.message.performative == ACLMessage.CFP:

                self.cfp_qty = len(self.message.receivers)
                self.received_qty = 0
                self.proposes = []
                self.agent.send(self.message)

                self.timed_behaviour()

    def handle_cfp(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_CFP type message 

            :param message: FIPA-ACL message
        """
        pass

    def handle_propose(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_PROPOSE type message 

            :param message: FIPA-ACL message
        """
        self.received_qty += 1
        print_progress_bar(self.received_qty,
                           self.cfp_qty,
                           fill='#',
                           length=50,
                           prefix='CFP responses received')
        if self.received_qty == self.cfp_qty:
            pass
            # delayed_calls = reactor.getDelayedCalls()
            # for call in delayed_calls:
            #     call.cancel()

    def handle_refuse(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_REFUSE type message 

            :param message: FIPA-ACL message
        """
        self.received_qty += 1
        print_progress_bar(self.received_qty,
                           self.cfp_qty,
                           fill='#',
                           length=50,
                           prefix='CFP responses received')
        if self.received_qty == self.cfp_qty:
            pass
            # delayed_calls = reactor.getDelayedCalls()
            # for call in delayed_calls:
            #     call.cancel()

    def handle_all_proposes(self, proposes):
        """This method should be overridden when implementing a protocol.
            This method is executed in two cases:
            *The quantity of answer received is equal to the quantity of
            requests received
            *The timeout is reached

            :param proposes: list containing the answers of the requests
            sent by the Initiator.
        """
        self.received_qty = 0

    def handle_inform(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_IMFORM type message 

            :param message: FIPA-ACL message
        """
        pass

    def handle_reject_propose(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_REJECT_PROPOSE type message 

            :param message: FIPA-ACL message
        """
        pass

    def handle_accept_propose(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_ACCEPT_PROPOSE type message 

            :param message: FIPA-ACL message
        """
        pass

    def timed_behaviour(self):
        """This method is always used when the implemented protocol 
            needs timed restrictions, for instance, the FipaContractNetProtocol.
            In this case, it uses the twisted callLater method, which
            receives a method and time delay as parameters to be executed
        """
        super(FipaContractNetProtocol, self).timed_behaviour()

        #reactor.callLater(self.timeout, self.execute_on_timeout)

    def execute_on_timeout(self):
        """This method executes the handle_all_proposes method if any 
            FIPA_CFP message sent by the agent does not get an answer.
        """

        self.handle_all_proposes(self.proposes)

    def execute(self, message):
        """This method overrides the execute method from FipaProtocol class.
            The selection of the method to be executed after the receival
            of a message is implemented here.

            :param message: FIPA-ACL message
        """

        super(FipaContractNetProtocol, self).execute(message)

        if self.filter_protocol.filter(self.message):
            if self.filter_cfp.filter(self.message):
                if not self.is_initiator:
                    self.handle_cfp(message)

            elif self.filter_propose.filter(self.message):
                if self.is_initiator:
                    self.proposes.append(message)
                    self.handle_propose(message)

                    if self.received_qty == self.cfp_qty:
                        self.handle_all_proposes(self.proposes)

            elif self.filter_refuse.filter(self.message):
                if self.is_initiator:
                    self.proposes.append(message)
                    self.handle_refuse(message)

                    if self.received_qty == self.cfp_qty:
                        self.handle_all_proposes(self.proposes)

            elif self.filter_accept_propose.filter(self.message):
                if not self.is_initiator:
                    self.handle_accept_propose(message)

            elif self.filter_reject_propose.filter(self.message):
                if not self.is_initiator:
                    self.handle_reject_propose(message)

            elif self.filter_failure.filter(self.message):
                if self.is_initiator:
                    self.handle_failure(message)

            elif self.filter_inform.filter(self.message):
                if self.is_initiator:
                    self.handle_inform(message)

            else:
                return

        else:
            return
示例#11
0
class FipaRequestProtocol(FipaProtocol):
    """This class implements the FipaRequestProtocol protocol,
        inheriting from the Behaviour class and implementing its methods.
    """
    def __init__(self, agent, message=None, is_initiator=True):
        """Inicializes the class that implements FipaRequestProtocol protocol

            :param agent: instance of the agent that will execute the protocol's
                         established behaviours.
            :param message: message to be sent by the agent when is_initiator
                         parameter is true.
            :param is_initiator: boolean type parameter that specifies if the 
                         protocol instance will act as Initiator or Participant.

        """
        super(FipaRequestProtocol, self).__init__(agent, message, is_initiator)

        self.filter_protocol = Filter()
        self.filter_protocol.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)

        self.filter_Request = Filter()
        self.filter_Request.set_performative(ACLMessage.REQUEST)

        self.filter_refuse = Filter()
        self.filter_refuse.set_performative(ACLMessage.REFUSE)

        self.filter_Agree = Filter()
        self.filter_Agree.set_performative(ACLMessage.AGREE)

        self.filter_failure = Filter()
        self.filter_failure.set_performative(ACLMessage.FAILURE)

        self.filter_inform = Filter()
        self.filter_inform.set_performative(ACLMessage.INFORM)

    def on_start(self):
        """
        This method overrides the on_start method from Behaviour class
            and implements aditional settings to the initialize method
            of FipaRequestProtocol protocol.
        """

        super(FipaRequestProtocol, self).on_start()

        if self.is_initiator and self.message != None:
            self.agent.send(self.message)

    def handle_request(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_REQUEST type message 

            :param message: FIPA-ACL message
        """
        pass

    def handle_refuse(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_REFUSE type message 

            :param message: FIPA-ACL message
        """
        pass

    def handle_agree(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_AGREE type message 

            :param message: FIPA-ACL message
        """
        pass

    def handle_failure(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_FAILURE type message 

            :param message: FIPA-ACL message
        """
        pass

    def handle_inform(self, message):
        """
        This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_IMFORM type message 

            :param message: FIPA-ACL message
        """
        pass

    def execute(self, message):
        """This method overrides the execute method from FipaProtocol class.
            The selection of the method to be executed after the receival
            of a message is implemented here.

            :param message: FIPA-ACL message
        """
        super(FipaRequestProtocol, self).execute(message)

        if self.filter_protocol.filter(self.message):

            if self.filter_Request.filter(self.message):
                self.handle_request(message)

            elif self.filter_refuse.filter(self.message):
                self.handle_refuse(message)

            elif self.filter_Agree.filter(self.message):
                self.handle_agree(message)

            elif self.filter_failure.filter(self.message):
                self.handle_failure(message)

            elif self.filter_inform.filter(self.message):
                self.handle_inform(message)

            else:
                return
        else:
            return
示例#12
0
class FipaSubscribeProtocol(Behaviour):
    """Classe que implementa o protocolo FipaSubscribeProtocol
        herdando a classe Behaviour e implementando seus métodos
    """

    def __init__(self, agent, message=None, is_initiator=True):
        """método de inicialização
        """

        super(FipaSubscribeProtocol, self).__init__(agent)

        self.is_initiator = is_initiator
        self.message = message

        self.subscribers = set()

        self.filter_protocol = Filter()
        self.filter_protocol.set_protocol(ACLMessage.FIPA_SUBSCRIBE_PROTOCOL)

        self.filter_subscribe = Filter()
        self.filter_subscribe.set_performative(ACLMessage.SUBSCRIBE)

        self.filter_agree = Filter()
        self.filter_agree.set_performative(ACLMessage.AGREE)

        self.filter_inform = Filter()
        self.filter_inform.set_performative(ACLMessage.INFORM)

        self.filter_refuse = Filter()
        self.filter_refuse.set_performative(ACLMessage.REFUSE)

        self.filter_cancel = Filter()
        self.filter_cancel.set_performative(ACLMessage.CANCEL)

        self.filter_failure = Filter()
        self.filter_failure.set_performative(ACLMessage.FAILURE)

    def on_start(self):
        """Este método sobrescreve o metoso on_start da classe
            Behaviour e implementa configurações adicionais
            à inicialização do protocolo FipaContractNetProtocol
        """
        super(FipaSubscribeProtocol, self).on_start()

        if self.is_initiator and self.message != None:

            if self.message.performative == ACLMessage.SUBSCRIBE:
                self.agent.send(self.message)
                # self.timed_behaviour()

    def handle_subscribe(self, message):
        """
            handle_subscribe

        """
        pass

    def handle_agree(self, message):
        """
            handle_agree

        """
        pass

    def handle_refuse(self, message):
        """
            handle_refuse

        """
        pass

    def handle_inform(self, message):
        """
            handle_inform

        """
        pass

    def handle_cancel(self, message):
        """
            handle_cancel

        """
        pass

    def execute(self, message):
        """Este método sobrescreve o metodo execute da classe 
            Behaviour. Nele esta implementado a seleção de qual
            método será executado logo após o recebimento de uma
            mensagem

            :param message: Mensagem FIPA-ACL
        """

        super(FipaSubscribeProtocol, self).execute(message)

        self.message = message

        if self.filter_protocol.filter(self.message):
            if self.filter_subscribe.filter(self.message):
                self.handle_subscribe(message)

            elif self.filter_cancel.filter(self.message):
                self.handle_cancel(message)

            elif self.filter_inform.filter(self.message):
                self.handle_inform(message)

            elif self.filter_agree.filter(self.message):
                self.handle_agree(message)

            elif self.filter_failure.filter(self.message):
                self.handle_failure(message)
            else:
                return

        else:
            return

    def register(self, aid):
        """register

        """
        self.subscribers.add(aid)

    def deregister(self, aid):
        """deregister

        """
        self.subscribers.remove(aid)

    def notify(self, message):
        """notify

        """
        for sub in self.subscribers:
            message.add_receiver(sub)
        self.agent.send(message)
示例#13
0
class FipaContractNetProtocol(Behaviour):

    """Classe que implementa o protocolo FipaContractNetProtocol
        herdando a classe Behaviour e implementando seus métodos
    """

    def __init__(self, agent, message=None, is_initiator=True):
        """
            Inicializa a classe que implementa o protocolo
            FipaContractNetProtocol

            :param agent: instância do agente que executara os comportamentos
                    estebelecidos pelo protocolo
            :param message: mensagem a ser enviada pelo agente quando o
                      parâmetro is_initiator for verdadeiro
            :param is_initiator: parâmetro do tipo booleano que indica se esta
                          instancia do protocolo agirá como Initiator
                          ou como participante

        """
        super(FipaContractNetProtocol, self).__init__(agent)

        self.is_initiator = is_initiator
        self.received_qtd = 0

        self.proposes = []

        self.message = message

        self.filter_protocol = Filter()
        self.filter_protocol.set_protocol(ACLMessage.FIPA_CONTRACT_NET_PROTOCOL)

        self.filter_cfp = Filter()
        self.filter_cfp.set_performative(ACLMessage.CFP)

        self.filter_refuse = Filter()
        self.filter_refuse.set_performative(ACLMessage.REFUSE)

        self.filter_propose = Filter()
        self.filter_propose.set_performative(ACLMessage.PROPOSE)

        self.filter_accept_propose = Filter()
        self.filter_accept_propose.set_performative(ACLMessage.ACCEPT_PROPOSAL)

        self.filter_reject_propose = Filter()
        self.filter_reject_propose.set_performative(ACLMessage.REJECT_PROPOSAL)

        self.filter_failure = Filter()
        self.filter_failure.set_performative(ACLMessage.FAILURE)

        self.filter_inform = Filter()
        self.filter_inform.set_performative(ACLMessage.INFORM)

    def on_start(self):
        """Este método sobrescreve o metoso on_start da classe
            Behaviour e implementa configurações adicionais
            à inicialização do protocolo FipaContractNetProtocol
        """
        super(FipaContractNetProtocol, self).on_start()

        if self.is_initiator and self.message is not None:

            if self.message.performative == ACLMessage.CFP:

                self.cfp_qtd = len(self.message.receivers)
                self.agent.send(self.message)

                self.timed_behaviour()

    def handle_cfp(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_CFP

            :param message: Mensagem FIPA-ACL
        """
        pass

    def handle_propose(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_PROPOSE

            :param message: Mensagem FIPA-ACL
        """
        self.received_qtd += 1
        if self.received_qtd == self.cfp_qtd:
            delayed_calls = reactor.getDelayedCalls()
            for call in delayed_calls:
                call.cancel()

    def handle_refuse(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_REFUSE

            :param message: Mensagem FIPA-ACL
        """
        self.received_qtd += 1
        if self.received_qtd == self.cfp_qtd:
            delayed_calls = reactor.getDelayedCalls()
            for call in delayed_calls:
                call.cancel()

    def handle_all_proposes(self, proposes):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado em um dos dois casos:
            * A quantidade de respostas recebidas for igual a quantidade
            de solicitações recebidas
            * O timeout for atingido

            :param proposes: lista com as respostas das solicitações envidas
                       pelo Initiator
        """
        self.received_qtd = 0

    def handle_inform(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_INFORM

            :param message: Mensagem FIPA-ACL
        """
        pass

    def handle_reject_propose(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_REJECT_PROPOSE

            :param message: Mensagem FIPA-ACL
        """
        pass

    def handle_accept_propose(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_ACCEPT_PROPOSE

            :param message: Mensagem FIPA-ACL
        """
        pass

    def timed_behaviour(self):
        """Este método é implementado sempre que o protocolo a ser 
            implementado necessitar de restrições temporais, como é
            o caso do FipaContractNetProtocol. Neste caso ele faz
            uso do metodo callLater do twisted que recebe como 
            parâmetro um método e o atrazo de tempo para que este
            método seja executado

        """
        super(FipaContractNetProtocol, self).timed_behaviour()

        reactor.callLater(self.timeout, self.execute_on_timeout)

    def execute_on_timeout(self):
        """Este método executa o método handle_all_proposes caso nem
            todas as mensagens FIPA_CFP enviadas pelo agente obtenham
            resposta
        """

        self.handle_all_proposes(self.proposes)

    def execute(self, message):
        """Este método sobrescreve o metodo execute da classe 
            Behaviour. Nele esta implementado a seleção de qual
            método será executado logo após o recebimento de uma
            mensagem

            :param message: Mensagem FIPA-ACL
        """

        super(FipaContractNetProtocol, self).execute(message)

        self.message = message

        if self.filter_protocol.filter(self.message):
            if self.filter_cfp.filter(self.message):
                if not self.is_initiator:
                    self.handle_cfp(message)

            elif self.filter_propose.filter(self.message):
                if self.is_initiator:
                    self.proposes.append(message)
                    self.handle_propose(message)

                    if self.received_qtd == self.cfp_qtd:
                        self.handle_all_proposes(self.proposes)

            elif self.filter_refuse.filter(self.message):
                if self.is_initiator:
                    self.proposes.append(message)
                    self.handle_refuse(message)

                    if self.received_qtd == self.cfp_qtd:
                        self.handle_all_proposes(self.proposes)

            elif self.filter_accept_propose.filter(self.message):
                if not self.is_initiator:
                    self.handle_accept_propose(message)

            elif self.filter_reject_propose.filter(self.message):
                if not self.is_initiator:
                    self.handle_reject_propose(message)

            elif self.filter_failure.filter(self.message):
                if self.is_initiator:
                    self.handle_failure(message)

            elif self.filter_inform.filter(self.message):
                if self.is_initiator:
                    self.handle_inform(message)

            else:
                return

        else:
            return
示例#14
0
class FipaRequestProtocol(Behaviour):

    """Classe que implementa o protocolo FipaRequestProtocol
        herdando a classe Behaviour e implementando seus métodos
    """

    def __init__(self, agent, message=None, is_initiator=True):
        """Inicializa a classe que implementa o protocolo
            FipaRequestProtocol

            :param agent: instância do agente que executara os comportamentos
                    estebelecidos pelo protocolo
            :param message: mensagem a ser enviada pelo agente quando o 
                      parâmetro is_initiator for verdadeiro
            :param is_initiator: parâmetro do tipo booleano que indica se esta 
                          instancia do protocolo agirá como Initiator
                          ou como participante

        """
        super(FipaRequestProtocol, self).__init__(agent)

        self.is_initiator = is_initiator
        self.message = message

        self.filter_protocol = Filter()
        self.filter_protocol.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)

        self.filter_Request = Filter()
        self.filter_Request.set_performative(ACLMessage.REQUEST)

        self.filter_refuse = Filter()
        self.filter_refuse.set_performative(ACLMessage.REFUSE)

        self.filter_Agree = Filter()
        self.filter_Agree.set_performative(ACLMessage.AGREE)

        self.filter_failure = Filter()
        self.filter_failure.set_performative(ACLMessage.FAILURE)

        self.filter_inform = Filter()
        self.filter_inform.set_performative(ACLMessage.INFORM)

    def on_start(self):
        """Este método sobrescreve o metoso on_start da classe
            Behaviour e implementa configurações adicionais
            à inicialização do protocolo FipaRequestProtocol
        """

        super(FipaRequestProtocol, self).on_start()

        if self.is_initiator and self.message != None:
            self.agent.send(self.message)

    def handle_request(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_REQUEST

            :param message: Mensagem FIPA-ACL
        """
        pass

    def handle_refuse(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_REFUSE

            :param message: Mensagem FIPA-ACL
        """
        pass

    def handle_agree(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_AGREE

            :param message: Mensagem FIPA-ACL
        """
        pass

    def handle_failure(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_FAILURE

            :param message: Mensagem FIPA-ACL
        """
        pass

    def handle_inform(self, message):
        """Este método deve ser sobrescrito quando na implementação
            do protocolo, sendo executado sempre que o agente receber
            uma mensagem do tipo FIPA_INFORM

            :param message : Mensagem FIPA-ACL
        """
        pass

    def execute(self, message):
        """Este método sobrescreve o metodo execute da classe 
            Behaviour. Nele esta implementado a seleção de qual
            método será executado logo após o recebimento de uma
            mensagem

            :param message: Mensagem FIPA-ACL
        """

        self.message = message

        if self.filter_protocol.filter(self.message):

            if self.filter_Request.filter(self.message):
                self.handle_request(message)

            elif self.filter_refuse.filter(self.message):
                self.handle_refuse(message)

            elif self.filter_Agree.filter(self.message):
                self.handle_agree(message)

            elif self.filter_failure.filter(self.message):
                self.handle_failure(message)

            elif self.filter_inform.filter(self.message):
                self.handle_inform(message)

            else:
                return
        else:
            return