Example #1
0
def start_loop(agents, gui=False):
    """
        Lança o loop do twisted integrado com o loop do Qt se a opção GUI for
        verdadeira, se não lança o loop do Twisted
    """
    global AMS

    if gui:
        from pade.core.sniffer import SnifferFactory
        from pade.gui.interface import ControlAgentsGui

        controlAgentsGui = ControlAgentsGui()
        controlAgentsGui.show()

        # instancia um AID para o agente Sniffer
        aid = AID('Sniffer_Agent')
        aid.setHost(AMS['name'])
        # instancia um objeto Factory para o agente Sniffer
        snifferFactory = SnifferFactory(aid, AMS, controlAgentsGui.ui)
        # lança o agente como servidor na porta gerada pelo objeto AID
        twisted.internet.reactor.listenTCP(aid.port, snifferFactory)

    i = 1
    for agent in agents:
        twisted.internet.reactor.callLater(i, listen_agent, agent)
        i += 0.2

    # lança o loop do Twisted
    # twisted.internet.reactor.startRunning(init)
    twisted.internet.reactor.run()
Example #2
0
    def __init__(self,
                 host='localhost',
                 session=None,
                 port=8000,
                 main_ams=True,
                 debug=False):

        # Added session parameter
        if session is None:
            self.session_name = str(uuid.uuid1())[:13]
        else:
            self.session_name = session.name
            self.session = session

        self.ams = {'name': host, 'port': port}

        self.ams_aid = AID('ams@' + str(host) + ':' + str(port))
        super(AMS, self).__init__(self.ams_aid, debug=debug)
        self.ams = {'name': str(host), 'port': str(port)}
        super(AMS, self).update_ams(self.ams)
        self.host = host
        self.port = port
        self.main_ams = main_ams

        self.agents_conn_time = dict()
        self.comport_ident = PublisherBehaviour(self)

        # message to check the connection.
        message = ACLMessage(ACLMessage.REQUEST)
        message.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
        self.add_all(message)
        message.set_content('CONNECTION')
        message.set_system_message(is_system_message=True)

        self.comport_conn_verify = CompConnectionVerify(self, message)
        self.comport_send_conn_messages = ComportSendConnMessages(
            self, message, 10.0)
        self.comport_conn_verify_timed = ComportVerifyConnTimed(self, 20.0)
        self.comport_conn_verify_reg = CompVerifyRegister(self)

        self.system_behaviours.append(self.comport_ident)
        self.system_behaviours.append(self.comport_conn_verify)
        self.system_behaviours.append(self.comport_send_conn_messages)
        self.system_behaviours.append(self.comport_conn_verify_timed)
        self.system_behaviours.append(self.comport_conn_verify_reg)
        self.on_start()
Example #3
0
 def update_ams(self, ams):
     """Summary
     
     Parameters
     ----------
     ams : TYPE
         Description
     """
     super(Agent,self).update_ams(ams)
     message = ACLMessage(ACLMessage.SUBSCRIBE)
     message.set_protocol(ACLMessage.FIPA_SUBSCRIBE_PROTOCOL)
     ams_aid = AID('ams@' + self.ams['name'] + ':' + str(self.ams['port']))
     message.add_receiver(ams_aid)
     message.set_content('IDENT')
     message.set_system_message(is_system_message=True)
     self.comport_ident = SubscribeBehaviour(self, message)
     self.system_behaviours.append(self.comport_ident)
Example #4
0
    def react(self, message):
        super(Agent, self).react(message)

        if 'ams' not in message.sender.name and 'sniffer' not in self.aid.name:
            # sends the received message to Sniffer
            # building of the message to be sent to Sniffer.
            _message = ACLMessage(ACLMessage.INFORM)
            sniffer_aid = AID('sniffer@' + self.sniffer['name'] + ':' + str(self.sniffer['port']))
            _message.add_receiver(sniffer_aid)
            _message.set_content(dumps({
            'ref' : 'MESSAGE',
            'message' : message}))
            _message.set_system_message(is_system_message=True)
            self.send(_message)

        # Passes the received message to all behaviours
        if not self.ignore_ams or not message.system_message:
            self.receive(message)
Example #5
0
    def __init__(self, aid):

        super(AgenteGoose, self).__init__(aid=aid, debug=False)

        message = ACLMessage(ACLMessage.REQUEST)
        message.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
        message.set_content(
            json.dumps({
                'ref': 'R_01',
                'dados': {
                    'chaves': ['1'],
                    'estados': [0]
                }
            }))
        message.add_receiver(AID('S1_AD1'))

        comprtamento_requisicao = CompRequest1(self, message)
        self.behaviours.append(comprtamento_requisicao)
Example #6
0
 def __init__(self, agent_ref):
     """Init the AgentFactory class
     
     Parameters
     ----------
     agent_ref : Agent
         agent object instance
     """
     self.conn_count = 0
     self.agent_ref = agent_ref
     self.agent_ref.mosaik_connection = None
     self.debug = agent_ref.debug
     self.aid = agent_ref.aid  # stores the agent's identity.
     self.ams = agent_ref.ams  # stores the  ams agent's identity.
     self.messages = []
     self.react = agent_ref.react
     self.on_start = agent_ref.on_start
     self.ams_aid = AID('ams@' + self.ams['name'] + ':' + str(self.ams['port']))
     self.table = dict([('ams', self.ams_aid)])
Example #7
0
    def handle_inform(self, message):
        """
        """
        super(CompContNet1, self).handle_inform(message)

        content = json.loads(message.content)

        if content['ref'] == 'CN_04':
            display_message(self.agent.aid.name, 'Mensagem INFORM recebida')

            if self.agent.podas is not []:
                display_message(self.agent.aid.name, 'Sera realizada nova tentativa de recomposicao')
                self.agent.agentes_solicitados.append(message.sender.localname)

                message = ACLMessage(ACLMessage.CFP)
                message.set_protocol(ACLMessage.FIPA_CONTRACT_NET_PROTOCOL)
                message.set_content(json.dumps({'ref': 'CN_01',
                                                'dados': pickle.dumps(self.agent.podas)
                                                },
                                    indent=4))

                agentes = list()
                for agent in self.agent.topologia['alimentadores'].keys():
                    if self.agent.aid.localname not in agent and agent not in self.agent.agentes_solicitados:
                        agentes.append(agent)
                        message.add_receiver(AID(agent))

                if not agentes == []:
                    # lança comportamento ContractNet na versão Iniciante
                    comp = CompContNet1(self.agent, message)
                    self.agent.behaviours.append(comp)
                    comp.on_start()
                    # self.agent.call_later(1.0, comp.on_start)
                else:
                    display_message(self.agent.aid.name, 'Nao ha mais possibilidades de solicitação de ajuda')

                self.agent.behaviours.remove(self)
                del self
            else:
                display_message(self.agent.aid.name, 'Comportameto de solicitação de ajuda encerrado')
                self.agent.agentes_solicitados = list()
                del self
Example #8
0
    def add_receiver(self, aid):
        """
            add_receiver
            ------------
            Método utilizado para adicionar receptores para a mensagem que está
            sendo montada

            Parâmetros
            ----------
            aid : objeto do tipo AID que identifica o agente que receberá a mensagem
        """

        if isinstance(aid, AID):
            self.receivers.append(aid)
            receivers = self.find('receivers')
            receiver = ET.Element('receiver')
            receiver.text = str(aid.name)
            receivers.append(receiver)
        else:
            self.add_receiver(AID(name=aid))
Example #9
0
    def react(self, message):
        """Summary
        
        Parameters
        ----------
        message : TYPE
            Description
        """
        super(Agent, self).react(message)

        if 'ams' not in message.sender.name and 'sniffer' not in self.aid.name:
            # sends the received message to Sniffer
            # building of the message to be sent to Sniffer.
            _message = ACLMessage(ACLMessage.INFORM)
            sniffer_aid = AID('sniffer@' + self.sniffer['name'] + ':' +
                              str(self.sniffer['port']))
            _message.add_receiver(sniffer_aid)
            _message.set_content(dumps({'ref': 'MESSAGE', 'message': message}))
            _message.set_system_message(is_system_message=True)
            self.send(_message)
Example #10
0
    def react(self, message):

        if message.system_message:
            for system_behaviour in self.system_behaviours:
                system_behaviour.execute(message)
        else:
            for behaviour in self.behaviours:
                #display_message(self.aid.getLocalName(), f"Sending message {message} to Behaviour: {behaviour}")
                behaviour.execute(message)

        if 'ams' not in message.sender.name and 'sniffer' not in self.aid.name:
            # sends the received message to Sniffer
            # building of the message to be sent to Sniffer.
            _message = ACLMessage(ACLMessage.INFORM)
            sniffer_aid = AID('sniffer@' + self.sniffer['name'] + ':' +
                              str(self.sniffer['port']))
            _message.add_receiver(sniffer_aid)
            _message.set_content(dumps({'ref': 'MESSAGE', 'message': message}))
            _message.set_system_message(is_system_message=True)
            self.send(_message)
Example #11
0
    def add_reply_to(self, aid):
        """
            add_reply_to
            ------------
            Método utilizado para adicionar agentes que devem receber
            a resposta desta mensagem

            Parâmetros
            ----------
            aid : objeto do tipo AID que identifica o agente que receberá a resposta
            desta mensagem

        """
        if isinstance(aid, AID):
            self.reply_to.append[aid]
            reply_to = self.find('reply_to')
            receiver = ET.Element('receiver')
            receiver.text = str(aid.name)
            reply_to.append(receiver)
        else:
            self.add_reply_to(AID(name=aid))
Example #12
0
 def __init__(self, aid, user_login, session_name, session):
     super(ValidadeUserAgent, self).__init__(aid=aid, debug=True)
     self.user_login = user_login
     self.session_name = session_name
     self.session = session
     super(ValidadeUserAgent, self).update_ams(session.ams)
     message = ACLMessage(ACLMessage.REQUEST)
     message.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
     content = dumps({
         'ref': 'REGISTER',
         'content': {
             'user_login': self.user_login,
             'session_name': self.session_name
         }
     })
     message.set_content(content)
     ams_aid = AID('ams@' + self.ams['name'] + ':' + str(self.ams['port']))
     message.add_receiver(ams_aid)
     message.set_system_message(is_system_message=True)
     self.comport_register_user = CompRegisterUser(self, message,
                                                   self.session)
     self.system_behaviours.append(self.comport_register_user)
Example #13
0
    def __init__(self, agent_ref):

        self.conn_count = 0
        self.agent_ref = agent_ref
        self.agent_ref.mosaik_connection = None
        self.debug = agent_ref.debug
        self.aid = agent_ref.aid  # stores the agent's identity.
        self.ams = agent_ref.ams  # stores the  ams agent's identity.

        self.messages = []  # stores the messages to be sent.

        # method that executes the agent's behaviour defined
        # both by the user and by the System-PADE.
        self.react = agent_ref.react
        # method that executes the agent's behaviour defined both
        # by the user and by the System-PADE when the agent is initialised
        self.on_start = agent_ref.on_start
        # AID of AMS
        self.ams_aid = AID('ams@' + self.ams['name'] + ':' + str(self.ams['port']))
        # table stores the active agents, a dictionary with keys: name and
        # values: AID
        self.table = dict([('ams', self.ams_aid)])
Example #14
0
    def step(self, time, inputs):

        # Inicia o mercado após período de aquisição de dados de uma semana
        # com negociações a cada uma hora.
        if time % (1 * 60 * 60) == 0 and time != 0 and time >= (7 * 24 * 60 *
                                                                60):
            message = ACLMessage(ACLMessage.CFP)
            message.set_protocol(ACLMessage.FIPA_CONTRACT_NET_PROTOCOL)
            message.set_content('SEND YOUR PROPOSE')

            for participant in self.agent.participants:
                message.add_receiver(AID(name=participant))

            self.agent.call_later(0.1, self.launch_contract_net_protocol,
                                  message)
            return
            # self.launch_contract_net_protocol(message)
            # d = defer.Deferred()
            # d.addCallback(self.next_step)
            # self.agent.call_later(1.0, d.callback, time)

            # return d

        return time + self.step_size
Example #15
0
def test_ied_messages(start_runtime, mock_receive_ied_event, queue):
    """Testa a geração de mensagens pelo IED e envia ao ACom"""

    # Test preparation
    acom = AgenteCom(
        AID('acom@localhost:60002'),
        substation='AQZ',
        IEDs=[
            FileIED('CH13', ('localhost', 50000), 'tests/ied-events/CH13.txt')
        ],
        debug=True)
    acom.ams = start_runtime

    # Start test
    with start_loop_test([acom]):

        # Delay to initiate agents
        time.sleep(2)

        # Simulate an IED event
        with open('tests/ied-events/CH13.txt', 'w') as file:
            file.write('XCBR BRKF')

        assert queue.get(timeout=10) == ('XCBR', 'BRKF')
def main():

    c = 0
    agents_list = list()
    port = argv[1]

    goal_keeper = 'goalkeeper_{}@localhost:{}'.format(port, port)
    time_agent = agents.GoalKeeper(AID(name=goal_keeper))
    agents_list.append(time_agent)

    port = int(port) + 1000
    winger1 = 'winger_{}@localhost:{}'.format(port, port)
    time_agent = agents.Winger(AID(name=winger1))
    agents_list.append(time_agent)

    port = int(port) + 1000
    winger2 = 'winger_{}@localhost:{}'.format(port, port)
    time_agent = agents.Winger(AID(name=winger2))
    agents_list.append(time_agent)

    port = int(port) + 1000
    attacker = 'attacker_{}@localhost:{}'.format(port, port)
    time_agent = agents.Striker(AID(name=attacker))
    agents_list.append(time_agent)

    port = int(port) + 1000
    defender = 'enemy_defender_{}@localhost:{}'.format(port, port)
    time_agent = agents.Defender(AID(name=defender))
    agents_list.append(time_agent)

    port = int(port) + 1000
    scorer = 'scorer_{}@localhost:{}'.format(port, port)
    time_agent = agents.Scorer(AID(name=scorer))
    agents_list.append(time_agent)

    print("Starting match")
    start_loop(agents_list)
Example #17
0
#!coding=utf-8
from pade.misc.utility import start_loop
from sys import argv
from pade.acl.aid import AID
# Agents files
from colector import ColectorAgent
from classifier import ClassifierAgent

if __name__ == '__main__':
    agents_per_process = 1
    # c = 0
    agents = list()

    colector_name = 'colector'
    colector = ColectorAgent(AID(name=colector_name))
    agents.append(colector)

    for i in range(agents_per_process):
        # port = int(argv[1]) + c
        classifier_name = 'classifier{}'.format(i)
        classifier = ClassifierAgent(AID(name=classifier_name))
        agents.append(classifier)

        # c += 1000

    start_loop(agents)
Example #18
0
    def send_message(self, receiver_agent):
        message = ACLMessage(ACLMessage.INFORM)
        message.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
        message.add_receiver(receiver_agent)
        self.add_all_agents(message.receivers)
        message.set_content(self.message)
        self.send(message)

    def add_all_agents(self, receivers):
        for receiver in receivers:
            self.agentInstance.table[receiver.localname] = receiver


if __name__ == '__main__':
    msg = {
        'board': [-1, -1, -1, -1, -1, -1, -1, -1, -1],
        'magicSquare': [8, 3, 4, 1, 5, 9, 6, 7, 2],
        'move': 1
    }

    agents = list()
    computer_agent_aid = AID(name='receiver@localhost:{}'.format(30001))
    computerAgent = ComputerAgent(computer_agent_aid)
    agents.append(computerAgent)

    human_agent = HumanAgent(AID(name='sender@localhost:{}'.format(30000)),
                             computer_agent_aid, msg)
    agents.append(human_agent)

    start_loop(agents)
 def on_start(self):
     display_message(self.aid.localname, 'Enviando Mensagem')
     message = ACLMessage(ACLMessage.INFORM)
     message.add_receiver(AID('destinatario'))
     message.set_content('Ola')
     self.send(message)
    def on_start(self):
        display_message(self.aid.localname, 'Enviando Mensagem')
        message = ACLMessage(ACLMessage.INFORM)
        message.add_receiver(AID('destinatario'))
        message.set_content('Ola')
        self.send(message)

    def react(self, message):
        pass


class Destinatario(Agent):
    def __init__(self, aid):
        super(Destinatario, self).__init__(aid=aid, debug=False)

    def react(self, message):
        display_message(self.aid.localname, 'Mensagem recebida')


if __name__ == '__main__':
    agents = list() 

    destinatario_agent = Destinatario(AID(name='destinatario'))
    agents.append(destinatario_agent)

    remetente_agent = Remetente(AID(name='remetente'))
    agents.append(remetente_agent)

    start_loop(agents)
 def set_message(self, message_content):
     message = ACLMessage(ACLMessage.INFORM)
     message.add_receiver(AID(BallReceivingWinger))
     message.set_content(message_content)
     self.message = message.as_xml()
Example #22
0
from pade.acl.messages import ACLMessage
from pade.acl.aid import AID
import json

index = [0, 0]

message_autonomo = ACLMessage(ACLMessage.REQUEST)
message_autonomo.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
message_autonomo.add_receiver(AID(name='sensor'))
message_autonomo.set_content(json.dumps(index))

message_conforto = ACLMessage(ACLMessage.REQUEST)
message_conforto.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
message_conforto.add_receiver(AID(name='sensor'))
message_conforto.set_content(json.dumps(index))


def updateIndex(NewValue):
    message_autonomo.set_content(NewValue)
    message_conforto.set_content(NewValue)
Example #23
0
from pade.misc.utility import display_message, start_loop
from pade.core.agent import Agent
from pade.acl.aid import AID
from sys import argv

class AgenteHelloWorld(Agent):
    def __init__(self, aid):
        super(AgenteHelloWorld, self).__init__(aid=aid)
        display_message(self.aid.localname, 'Hello World!')


if __name__ == '__main__':

    agents_per_process = 3
    c = 0
    agents = list()
    for i in range(agents_per_process):
        port = int(argv[1]) + c
        agent_name = 'agente_hello_{}@localhost:{}'.format(port, port)
        agente_hello = AgenteHelloWorld(AID(name=agent_name))
        agents.append(agente_hello)
        c += 1000

    start_loop(agents)Hello
Example #24
0
        self.behaviours.append(self.timed)


if __name__ == '__main__':

    agents_per_process = 2
    c = 0
    agents = list()
    for i in range(agents_per_process):
        port = int(argv[1]) + c
        k = 10000
        participants = list()

        agent_name = 'agent_publisher_{}@localhost:{}'.format(port, port)
        participants.append(agent_name)
        agent_pub_1 = AgentPublisher(AID(name=agent_name))
        agents.append(agent_pub_1)

        msg = ACLMessage(ACLMessage.SUBSCRIBE)
        msg.set_protocol(ACLMessage.FIPA_SUBSCRIBE_PROTOCOL)
        msg.set_content('Subscription request')
        msg.add_receiver(agent_pub_1.aid)

        agent_name = 'agent_subscriber_{}@localhost:{}'.format(
            port + k, port + k)
        participants.append(agent_name)
        agent_sub_1 = AgentSubscriber(AID(name=agent_name), msg)
        agents.append(agent_sub_1)

        agent_name = 'agent_subscriber_{}@localhost:{}'.format(
            port - k, port - k)
Example #25
0
    def set_message(self, data):
        aclmsg = ET.fromstring(data)

        try:
            self.performative = aclmsg.find('performative').text
            self.find('performative').text = self.performative
        except:
            pass

        try:
            system_message = aclmsg.find('system-message').text
            if system_message == 'True':
                self.system_message = True
                self.find('system-message').text = system_message
            else:
                self.system_message = False
                self.find('system-message').text = system_message
        except:
            pass

        try:
            self.conversation_id = aclmsg.find('conversationID').text
            self.find('conversationID').text = self.conversation_id
        except:
            pass

        try:
            self.messageID = aclmsg.find('messageID').text
            self.find('messageID').text = self.messageID
        except:
            pass

        try:
            datetime_tag = aclmsg.find('datetime')
            my_datetime_tag = self.find('datetime')

            day = int(datetime_tag.findtext('day'))
            my_datetime_tag.find('day').text = str(day)
            month = int(datetime_tag.findtext('month'))
            my_datetime_tag.find('month').text = str(month)
            year = int(datetime_tag.findtext('year'))
            my_datetime_tag.find('year').text = str(year)
            hour = int(datetime_tag.findtext('hour'))
            my_datetime_tag.find('hour').text = str(hour)
            minute = int(datetime_tag.findtext('minute'))
            my_datetime_tag.find('minute').text = str(minute)
            second = int(datetime_tag.findtext('second'))
            my_datetime_tag.find('second').text = str(second)
            microsecond = int(datetime_tag.findtext('microsecond'))
            my_datetime_tag.find('microsecond').text = str(microsecond)

            self.datetime = datetime(year=year,
                                     month=month,
                                     day=day,
                                     hour=hour,
                                     minute=minute,
                                     second=second,
                                     microsecond=microsecond)
        except:
            pass

        try:
            self.sender = AID(name=aclmsg.find('sender').text)
            self.find('sender').text = self.sender.name
        except:
            pass

        try:
            receivers = aclmsg.find('receivers').getchildren()

            for receiver in receivers:
                aid = AID(name=receiver.text)
                self.receivers.append(aid)
                r = ET.Element('receiver')
                r.text = aid.name
                self.find('receivers').append(r)
        except:
            pass

        try:
            receivers = aclmsg.find('reply-to').getchildren()

            for receiver in receivers:
                aid = AID(name=receiver.text)
                self.reply_to.append(aid)
                r = ET.Element('receiver')
                r.text = aid.name
                self.find('reply-to').append(r)
        except:
            pass

        try:
            self.content = aclmsg.find('content').text
            self.find('content').text = self.content
        except:
            pass

        try:
            self.language = aclmsg.find('language').text
            self.find('language').text = self.language
        except:
            pass

        try:
            self.encoding = aclmsg.find('encoding').text
            self.find('encoding').text = self.encoding
        except:
            pass

        try:
            self.ontology = aclmsg.find('ontology').text
            self.find('ontology').text = self.ontology
        except:
            pass

        try:
            self.protocol = aclmsg.find('protocol').text
            self.find('protocol').text = self.protocol
        except:
            pass

        try:
            self.reply_with = aclmsg.find('reply-with').text
            self.find('reply-with').text = self.reply_with
        except:
            pass

        try:
            self.in_reply_to = aclmsg.find('in-reply-to').text
            self.find('in-reply-to').text = self.in_reply_to
        except:
            pass

        try:
            self.reply_by = aclmsg.find('reply-by').text
            self.find('reply-by').text = self.reply_by
        except:
            pass
Example #26
0
		super().__init__(name)
		self.ping = ping_aid # Gets the ping AID

	def setup(self):
		self.add_behaviour(PongTurn(self))

class PongTurn(CyclicBehaviour):
	def action(self):
		if self.agent.has_messages():
			message = self.agent.read()
			if message.sender == self.agent.ping:
				# Preparing a reply to 'ping'
				reply = message.create_reply()
				reply.set_content('PONG')
				display_message(self.agent, 'Turn: %s' % message.content)
				self.wait(0.5)
				# Sending the reply
				self.send(reply)


# ==== Starting main loop of PADE ====

if __name__ == '__main__':
	ping_aid = AID('ping') # Creates an AID for ping
	pong_aid = AID('pong') # Creates an AID for pong
	# Creates a PingAgent using the AID ping_aid and passing the address (AID) of PongAgent (pong_aid)
	ping = PingAgent(ping_aid, pong_aid)
	# Creates a PongAgent using the AID pong_aid and passing the address (AID) of PingAgent (ping_aid)
	pong = PongAgent(pong_aid, ping_aid)
	start_loop([ping, pong])
Example #27
0
    sio.emit('my response', {'response': 'my response'})

@sio.on('hola')
def hola(data):
    print(data)

@sio.event
def disconnect():
    print('disconnected from server') """


### BT ###
def escuchaBT():
    """service = DiscoveryService()    
    devices = service.discover(2)
    print (devices)"""

    nearby_devices = bluetooth.discover_devices()
    print(nearby_devices)


if __name__ == '__main__':

    agents = list()

    agente_hello = AgenteHelloWorld(AID(name='Agent2'))
    hello_agent = HelloAgent(AID(name='Agent'))
    agents.append(hello_agent)
    agents.append(agente_hello)

    start_loop(agents)
Example #28
0
                        'is_start_of_negotiation': True,
                        'price': price,
                        'growth': self.type_growth[self.type]
                    }))
                message.add_receiver(self.connection)
                self.send(message)
            else:
                display_message(self.aid.localname, "YCombinator always been")
                message = ACLMessage(performative=ACLMessage.REJECT_PROPOSAL)
                message.add_receiver(self.connection)
                self.send(message)


if __name__ == '__main__':
    agents = list()
    buyer_aid = AID(name='huge_company@localhost:8011')
    startup_aid = AID(name="startup@localhost:8022")
    huge_company = Buyer(buyer_aid, startup_aid)
    startup = Seller(startup_aid, buyer_aid)

    agents.append(huge_company)
    agents.append(startup)

    start_loop(agents)

# [startup] 20/12/2020 20:46:29.854 --> Hello, we want to sell 10% of company on your investments
# [huge_company] 20/12/2020 20:46:29.857 --> Hello!
# [huge_company] 20/12/2020 20:46:29.857 --> How much you growth last month?
# [startup] 20/12/2020 20:46:29.861 --> Which value u interested in?
# [huge_company] 20/12/2020 20:46:29.865 --> Let's talk about users
# [huge_company] 20/12/2020 20:46:29.865 --> We can invest 4425456$
Example #29
0
# agent_example_1.py
# A simple hello agent in PADE!

from pade.misc.utility import display_message, start_loop
from pade.core.agent import Agent
from pade.acl.aid import AID
from sys import argv
import civil, bombeiro, incendiario, policial

if __name__ == '__main__':
    agents_per_process = 3
    agents = list()

    port = 20001
    agent_name = 'incendiario'.format(port, port)
    agenteIncendiario = incendiario.Incendiario(AID(name=agent_name))
    agents.append(agenteIncendiario)

    port = 20003
    nomeBombeiro = 'bombeiro_{}@localhost:{}'.format(port, port)
    agenteBombeiro = bombeiro.Bombeiro(AID(name=nomeBombeiro), portC=10000)
    agents.append(agenteBombeiro)

    port = 20004
    nomeBombeiro = 'policial_{}@localhost:{}'.format(port, port)
    agentePolicial = policial.Policial(AID(name=nomeBombeiro), portC=10010)
    agents.append(agentePolicial)

    port = 20002
    agent_name = 'agent_civil_{}@localhost:{}'.format(port, port)
    agenteCivil = civil.Civil(AID(name=agent_name), agenteBombeiro,
Example #30
0
class AgentParticipant(Agent):
    def __init__(self, aid):
        super(AgentParticipant, self).__init__(aid)

        self.protocol = SubscribeParticipant(self)
        self.timed = Time(self, self.protocol.notify)

        self.behaviours.append(self.protocol)
        self.behaviours.append(self.timed)

        call_in_thread(my_time, 'a', 'b')


if __name__ == '__main__':

    editor = AgentParticipant(AID('editor'))

    msg = ACLMessage(ACLMessage.SUBSCRIBE)
    msg.set_protocol(ACLMessage.FIPA_SUBSCRIBE_PROTOCOL)
    msg.set_content('Subscription request')
    msg.add_receiver(editor.aid)

    subs1 = AgentInitiator(AID('subscriber_1'), msg)
    # subs1.ams = {'name': 'localhost', 'port': 5000}

    subs2 = AgentInitiator(AID('subscriber_2'), msg)
    #subs2.ams = {'name': 'localhost', 'port': 5000}

    agents = [editor, subs1, subs2]

    s = PadeSession()
Example #31
0
    def filter(self, message):
        state = True
        
        if self.conversationID != None and self.conversationID != message.conversationID:
            state = False
        
        if self.sender != None and self.sender != message.sender:
            state = False
        
        if self.performative != None and self.performative != message.performative:
            state = False
        
        if self.protocol != None and self.protocol != message.protocol:
            state = False
            
        return state

if __name__ == '__main__':
    message = ACLMessage(ACLMessage.REQUEST)
    message.set_sender(AID('lucas'))
    message.add_receiver('allana')
    message.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
    
    filtro = Filter()
    filtro.set_protocol(ACLMessage.FIPA_REQUEST_PROTOCOL)
    
    if filtro.filter(message):
        print message.as_xml()
    else:
        print 'A mensagem foi barrada pelo protocolo'