def _get_service(agent, term, intention): """Request for troop agents that offer the service specified by <service>. This action sends a FIPA REQUEST message to the service agent asking for those who offer the <service> service. :param service: service requested :type service: str """ args = asp.grounded(term.args, intention.scope) service = str(args[0]) class GetServiceBehaviour(OneShotBehaviour): 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()) t = Template() t.set_metadata(PERFORMATIVE, service) b = GetServiceBehaviour() self.add_behaviour(b, t) yield
def _get_backups(agent, term, intention): """Request for backup agents. This action sends a FIPA REQUEST message to the service agent asking for those who offer the Backup service. """ class GetBackupBehaviour(OneShotBehaviour): 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 t = Template() t.set_metadata(PERFORMATIVE, PERFORMATIVE_CFB) b = GetBackupBehaviour() self.add_behaviour(b, t) yield
def setup(self): print("Receiver agent started") self.add_behaviour(self.Behav1()) b = self.ReceiveBehaviour() template = Template() template.set_metadata("performative", "cfp") self.add_behaviour(b, template)
def run_strategy(self): """ Runs the strategy for the directory agent. """ template = Template() template.set_metadata("protocol", QUERY_PROTOCOL) self.add_behaviour(self.strategy(), template)
async def setup(self): """Executed when the agent starts.""" logger.info("ImageAgent starting . . .") # Ingredients names with open((CNN_DIR / 'classes.csv'), 'r') as f: self.CLASS_NAMES = list(csv.reader(f))[0] # Uncomment if TensorFlow for GPU is enabled. # gpus = tf.config.experimental.list_physical_devices('GPU') # if gpus: # try: # # Currently, memory growth needs to be the same across GPUs # for gpu in gpus: # tf.config.experimental.set_memory_growth(gpu, True) # logical_gpus = tf.config.experimental.list_logical_devices( # 'GPU') # print(len(gpus), "Physical GPUs,", len( # logical_gpus), "Logical GPUs") # except RuntimeError as e: # # Memory growth must be set before GPUs have been initialized # print(e) b = self.ClassifyBehaviour() t = Template() t.set_metadata("performative", "request") self.add_behaviour(b, t)
async def setup(self): log.info(f"[{self.name}] Server running") self.add_behaviour(self.PresenceSetup()) self.broadcast_template = Template() self.broadcast_template.set_metadata('action', 'send_message') self.add_behaviour(self.BroadcastMessage(), self.broadcast_template)
async def setup(self): print("DQNAgent started") start_at = datetime.datetime.now() + datetime.timedelta(seconds=5) b = self.DQNBehav(period=2, start_at=start_at, config=self.config) template = Template() template.set_metadata("performative", "inform") self.add_behaviour(b)
async def setup(self): print("Player started") b = self.WaitTurn() template = Template() template.set_metadata("ludoMETA", "getIndex") self.add_behaviour(b, template)
def Launch_Sight_ResponderBehaviour(self): class CyclicBehaviourSight(Behaviour): async def run(self): msg = await self.receive(timeout=100000) if msg: s_content = msg.body s_content = s_content.split() FOVObjects = self.agent.GetObjectsInFieldOfView(s_content[1]) s_content = " #: " + str(len(FOVObjects)) + " " for s in FOVObjects: s_content += "TEAM: " + str(s.m_eTeam) + " TYPE: " + str(s.m_eType) s_content += " ANGLE: " + str(s.m_dAngle) + " DISTANCE: " + str(s.m_dDistance) + " " s_content += "HEALTH: " + str(s.m_iHealth) s_content += " ( " + str(s.m_Position.x) + " , " + str(s.m_Position.y) + " , " + str(s.m_Position.z) + " ) " reply = msg.make_reply() reply.body = s_content reply.set_metadata("performative", "sight") await self.send(reply) template = Template() template.set_metadata("performative", "sight") self.add_behaviour(CyclicBehaviourSight(), template)
async def setup(self): util.mas_print_info("[MISSILE] ({}) starting...".format(self.aid)) b = RecvBehav(self.aid) template = Template() template.set_metadata("performative", "inform") self.add_behaviour(b, template)
def __init__(self, jid, password, *, graph, workflow, factory_creator, storage_username, verify_security=False, neighbours=None, agent_type=None, produced_components=None, is_recovered=False): """ Simulation agent initializer. :param jid: agent username in XMPP server, e.g. 'agent 0' :param password: agent password in XMPP server, e.g. 'agent 0' :param verify_security: XMPP server parameter - whether agents should be verified or not :param neighbours: list of agents' username (e.g. 'agent 0') being the agent neighbours (for whom the agent can sent a message) """ super().__init__(jid=jid, password=password, verify_security=verify_security) if neighbours is None: neighbours = dict() self.username = jid self.neighbours = neighbours self.successors = self.neighbours['successors'] self.predecessors = self.neighbours['predecessors'] self.propagate_behav = None self.listen_behav = None self.agentType = agent_type self.factory_creator = factory_creator self.storage_username = storage_username self.produced_components = produced_components self.workflow = workflow self.graph = graph template = Template() template.set_metadata("performative", "inform") self.common_template = template self.message_thread_counter_list = [] self.sent_messages_registry = [] self.respawn_after_breakdown = is_recovered self.was_ever_revived = is_recovered
async def setup(self): # print("<Chord> {}".format(str(self.jid).split("@")[0])) self.set("inversion", None) inversion_template = Template() inversion_template.set_metadata("performative", "inversion") self.add_behaviour(self.receiveInversion(), inversion_template) self.add_behaviour(self.sendChord())
def Launch_DataFromTroop_ListenerBehaviour(self): class CyclicBehaviourDFT(Behaviour): async def run(self): msg = await self.receive(timeout=100000) if msg: s_content = msg.body s_content = s_content.split() id_agent = int(s_content[1]) self.agent.m_AgentList[id_agent].m_Locate.m_Position.x = float(s_content[3]) self.agent.m_AgentList[id_agent].m_Locate.m_Position.y = float(s_content[5]) self.agent.m_AgentList[id_agent].m_Locate.m_Position.z = float(s_content[7]) self.agent.m_AgentList[id_agent].m_Locate.m_Velocity.x = float(s_content[10]) self.agent.m_AgentList[id_agent].m_Locate.m_Velocity.y = float(s_content[12]) self.agent.m_AgentList[id_agent].m_Locate.m_Velocity.z = float(s_content[14]) self.agent.m_AgentList[id_agent].m_Locate.m_Heading.x = float(s_content[17]) self.agent.m_AgentList[id_agent].m_Locate.m_Heading.y = float(s_content[19]) self.agent.m_AgentList[id_agent].m_Locate.m_Heading.z = float(s_content[21]) self.agent.m_AgentList[id_agent].m_iHealth = int(s_content[24]) self.agent.m_AgentList[id_agent].m_iAmmo = int(s_content[26]) self.agent.CheckObjectsAtStep(id_agent) if self.agent.CheckGameFinished(id_agent): self.agent.InformGameFinished("ALLIED", self) print("\n\nManager: GAME FINISHED!! Winner Team: ALLIED! (Target Returned)\n") template = Template() template.set_metadata("performative", "data") self.add_behaviour(CyclicBehaviourDFT(), template)
def get_template(agent: AgentType): temp = Template() to = agent.value if to in users: to = users[to] temp.to = get_xmpp_username(to['username']) temp.set_metadata("stream", agent.value) return temp
async def setup(self): log.info(f"[{self.name}] Avatar running") self.add_behaviour(self.PresenceSetup()) message_template = Template() message_template.set_metadata('action', 'send_message') self.add_behaviour(ReceiveMessage(), message_template) self.add_behaviour(self.Chat())
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)
async def setup(self): util.mas_print_info("[HQ] {} starting...".format(self.aid)) b = RecvBehav(self.locations) template = Template() template.set_metadata("performative", "inform") self.add_behaviour(b, template) self.presence.set_available(show=aioxmpp.PresenceShow.CHAT)
def run_strategy(self): """ Runs the strategy for the transport agent. """ if not self.running_strategy: template = Template() template.set_metadata("protocol", REQUEST_PROTOCOL) self.add_behaviour(self.strategy(), template) self.running_strategy = True
async def setup(self): template = Template(metadata={"performative": "Modify"}) self.add_behaviour(self.Modify(period=5, start_at=datetime.now()), template) template = Template(metadata={"performative": "Ending"}) self.add_behaviour( self.Behav4(start_at=datetime.now() + timedelta(seconds=11)), template)
async def setup(self): print(Fore.CYAN+Style.BRIGHT+f"[{self.jid}]", Style.NORMAL+" AGENTE REGLAS STARTED"+Fore.RESET+Style.RESET_ALL) b = self.ReglasBehaviour() # Creamos una template con la que solo podremos recibir mensaje de con performativa inform template = Template() template.set_metadata("performative", "inform") # Añadimos comportamiento self.add_behaviour(b, template)
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]))
def launch_pack_management_responder_behaviour(self): class PackManagementResponderBehaviour(CyclicBehaviour): async def run(self): msg = await self.receive(LONG_RECEIVE_WAIT) if msg: content = json.loads(msg.body) id_ = content[NAME] action = content[ACTION] if action == DESTROY: self.agent.game_statistic.pack_destroyed( self.agent.din_objects[id_]) try: del self.agent.din_objects[id_] logger.info("Pack removed") except KeyError: logger.info("Pack {} cannot be erased".format(id_)) return if action == CREATE: type_ = int(content[TYPE]) team = int(content[TEAM]) x = float(content[X]) y = float(content[Y]) z = float(content[Z]) din_object = DinObject() din_object.jid = msg.sender din_object.type = type_ if din_object.type == PACK_OBJPACK: din_object.render_id = 1 else: din_object.render_id = abs(hash( din_object.jid)) % 1024 din_object.team = team din_object.position.x = x din_object.position.y = y din_object.position.z = z self.agent.din_objects[din_object.jid] = din_object logger.info("Added DinObject {}".format(din_object)) self.agent.game_statistic.pack_created( din_object, team) else: logger.warning( "Action not identified: {}".format(action)) return template = Template() template.set_metadata(PERFORMATIVE, PERFORMATIVE_PACK) self.add_behaviour(PackManagementResponderBehaviour(), template)
async def setup(self): fsm = DeviceBehaviour() fsm.add_state(name=S_RECEIVING, state=StateOne(), initial=True) fsm.add_state(name=S_SENDING, state=StateTwo()) fsm.add_transition(source=S_RECEIVING, dest=S_SENDING) fsm.add_transition(source=S_RECEIVING, dest=S_RECEIVING) fsm.add_transition(source=S_SENDING, dest=S_RECEIVING) sndTemplate = Template() sndTemplate.set_metadata("msg", "snd") self.add_behaviour(fsm, sndTemplate)
async def setup(self): sensorMessageTemplate = Template() sensorMessageTemplate.set_metadata("performative", "malfunction") sensorMessageTemplate.set_metadata("ontology", "device") self.add_behaviour(ReceiveSensorMessagesBehaviour(), template=sensorMessageTemplate) bidMessageTemplate = Template() bidMessageTemplate.set_metadata("performative", "bid") bidMessageTemplate.set_metadata("ontology", "auction") self.add_behaviour(ReceiveBidderMessagesBehaviour(), template=bidMessageTemplate)
def add_strategy(self, strategy_class): """ Sets the strategy for the taxi agent. Args: strategy_class (``TaxiStrategyBehaviour``): The class to be used. Must inherit from ``TaxiStrategyBehaviour`` """ template = Template() template.set_metadata("protocol", REQUEST_PROTOCOL) self.add_behaviour(strategy_class(), template)
def prepare_heartbeat(self): if self.successors: self.add_behaviour(Heartbeat(self.successors)) predecessors_wo_storage = {v for v in self.predecessors if v != self.storage_username} if predecessors_wo_storage: template = Template() template.set_metadata("performative", Heartbeat.performative) heartbeat_verificator = HeartbeatVerificator(predecessors_wo_storage, agent_factory=self.factory_creator, owning_agent=self.name) self.add_behaviour(heartbeat_verificator, template)
async def setup(self): self.type = PACK_OBJPACK self.origin.x = self.position.x self.origin.y = self.position.y self.origin.z = self.position.z t = Template() t.set_metadata(PERFORMATIVE, PERFORMATIVE_PACK_LOST) self.add_behaviour(self.PackLostResponderBehaviour(), t) await super().setup()
async def setup(self): LogManager.log(self.name, "StatisticalAgent starting...") t1 = Template(metadata={"performative": "temp"}) t2 = Template(metadata={"performative": "query"}) stat_presence_behav = self.PresenceNotificationBehav(1) time_rec_behav = self.TimeReceiverBehav(1) statistic_behav = self.StatisticalBehav(1) self.add_behaviour(stat_presence_behav) self.add_behaviour(time_rec_behav, t1) self.add_behaviour(statistic_behav, t2)
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)
def setup(self): print(f"[{self.jid}] Hello World! I'm agent {self.jid}") # Update topology - waiting for request from manager template_msg = Template() template_msg.sender = self.manager_jid template_msg.set_metadata('performative', 'request') self.add_behaviour(UpdateTopology(period=config.UPDATE_TOPOLOGY_FREQ), template_msg) # Handler for subscribe request template_msg = Template() template_msg.set_metadata('performative', 'subscribe') self.add_behaviour(Subscribe(), template_msg) # Reporting to manager self.add_behaviour( SendReportForSubscribers(period=config.SEND_REPORT_FREQ)) # Get data from sensors self.add_behaviour(GetCars(period=config.GET_DATA_FREQ)) self.add_behaviour(GetLightsStatus(period=config.GET_DATA_FREQ)) # Control lights #self.add_behaviour(ChangeLights(config.CHANGE_LIGHTS_FREQ)) # Answering protocol self.add_behaviour( CrossroadsMessanger.NegotiatingProtocolParticipant()) self.add_behaviour(CrossroadsMessanger.NegotiatingProtocolInitiator())
async def setup(self): print("Instanciado agente ReglasDifusasAgent") # Instanciamos el comportamiento RecvBehav b = self.RecvBehav() # Declaramos la plantilla que utilizaremos para filtrar los mensajes que recibiremos en el comportamiento RecvBehav template = Template() template.set_metadata("performative", "inform") # Añadimos el comportamiento junto con la plantilla definida self.add_behaviour(b, template)
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)
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)
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)
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)
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)
async def setup(self): try: template = Template() template.set_metadata("protocol", TRAVEL_PROTOCOL) travel_behaviour = TravelBehaviour() self.add_behaviour(travel_behaviour, template) while not self.has_behaviour(travel_behaviour): logger.warning("Customer {} could not create TravelBehaviour. Retrying...".format(self.agent_id)) self.add_behaviour(travel_behaviour, template) except Exception as e: logger.error("EXCEPTION creating TravelBehaviour in Customer {}: {}".format(self.agent_id, e))
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)
def test_multiple_templates(): class Template1Behaviour(OneShotBehaviour): async def run(self): self.agent.msg1 = await self.receive(timeout=2) class Template2Behaviour(OneShotBehaviour): async def run(self): self.agent.msg2 = await self.receive(timeout=2) class Template3Behaviour(OneShotBehaviour): async def run(self): self.agent.msg3 = await self.receive(timeout=2) self.kill() agent = make_connected_agent() template1 = Template() template1.set_metadata("performative", "template1") agent.add_behaviour(Template1Behaviour(), template1) template2 = Template() template2.set_metadata("performative", "template2") agent.add_behaviour(Template2Behaviour(), template2) template3 = Template() template3.set_metadata("performative", "template3") behaviour = Template3Behaviour() agent.add_behaviour(behaviour, template3) msg1 = Message(metadata={"performative": "template1"}).prepare() msg2 = Message(metadata={"performative": "template2"}).prepare() msg3 = Message(metadata={"performative": "template3"}).prepare() future = agent.start(auto_register=False) future.result() agent._message_received(msg1) agent._message_received(msg2) agent._message_received(msg3) behaviour.join() assert agent.msg1.get_metadata("performative") == "template1" assert agent.msg2.get_metadata("performative") == "template2" assert agent.msg3.get_metadata("performative") == "template3" agent.stop()
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)
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)
def test_behaviour_match(): class TestBehaviour(OneShotBehaviour): async def run(self): pass template = Template() template.sender = "sender1@host" template.to = "recv1@host" template.body = "Hello World" template.thread = "thread-id" template.metadata = {"performative": "query"} behaviour = TestBehaviour() behaviour.set_template(template) 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)
async def setup(self): print("ReceiverAgent started") b = self.RecvBehav() template = Template() template.set_metadata("performative", "inform") self.add_behaviour(b, template)