async def run(self): message = Message(to="to@outerhost") await self.send(message) self.kill()
async def check_objects_at_step(self, id_agent, behaviour): if len(self.din_objects) <= 0: return if self.agents[id_agent].health <= 0: return xmin = self.agents[id_agent].locate.position.x - WIDTH zmin = self.agents[id_agent].locate.position.z - WIDTH xmax = self.agents[id_agent].locate.position.x + WIDTH zmax = self.agents[id_agent].locate.position.z + WIDTH packs = [] keys = list(self.din_objects.keys()) for key in keys: if key not in self.din_objects: continue din_object = self.din_objects[key] if din_object.type == PACK_MEDICPACK and self.agents[ id_agent].health >= 100: continue if din_object.type == PACK_AMMOPACK and self.agents[ id_agent].ammo >= 100: continue if din_object.type == PACK_OBJPACK and din_object.is_taken and din_object.owner != 0: continue if xmin <= din_object.position.x <= xmax and zmin <= din_object.position.z <= zmax: # Agent has stepped on pack id_ = din_object.jid type_ = din_object.type owner = str(din_object.jid) content = None team = self.agents[id_agent].team self.game_statistic.pack_taken(din_object, team) if din_object.type == PACK_MEDICPACK: quantity = DEFAULT_PACK_QTY try: del self.din_objects[id_] logger.info(self.agents[id_agent].jid + ": got a medic pack " + str(din_object.jid)) content = {TYPE: type_, QTY: quantity} except KeyError: logger.error( "Could not delete the din object {}".format(id_)) elif din_object.type == PACK_AMMOPACK: quantity = DEFAULT_PACK_QTY try: del self.din_objects[id_] logger.info(self.agents[id_agent].jid + ": got an ammo pack " + str(din_object.jid)) content = {TYPE: type_, QTY: quantity} except KeyError: logger.error( "Could not delete the din object {}".format(id_)) elif din_object.type == PACK_OBJPACK: if team == TEAM_ALLIED: logger.info("{}: got the objective pack ".format( self.agents[id_agent].jid)) din_object.is_taken = True din_object.owner = id_agent din_object.position.x, din_object.position.y, din_object.position.z = 0.0, 0.0, 0.0 self.agents[id_agent].is_carrying_objective = True content = {TYPE: type_, QTY: 0, TEAM: TEAM_ALLIED} elif team == TEAM_AXIS: if din_object.is_taken: logger.info( f"{self.agents[id_agent].jid}: returned the objective pack {din_object.jid}" ) din_object.is_taken = False din_object.owner = 0 din_object.position.x = self.map.get_target_x() din_object.position.y = self.map.get_target_y() din_object.position.z = self.map.get_target_z() content = {TYPE: type_, QTY: 0, TEAM: TEAM_AXIS} # // Send a destroy/taken msg to pack and an inform msg to agent if content: content = json.dumps(content) msg = Message(to=owner) msg.set_metadata(PERFORMATIVE, PERFORMATIVE_PACK_TAKEN) msg.body = content await behaviour.send(msg) packs.append(content) return packs
async def run(self): message = Message(to="fake_receiver_agent@server") await self.send(message) self.kill()
def test_agent_in_msg_to(): msg = Message(to="agent@server") assert _agent_in_msg(JID.fromstr("agent@server"), msg)
async def run(self): msg = await self.receive(timeout=LONG_RECEIVE_WAIT) if msg: content = json.loads(msg.body) shooter_id = content[NAME] aim = int(content[AIM]) shots = int(content[SHOTS]) victim_pos = Vector3D(x=content[X], y=content[Y], z=content[Z]) try: shooter = self.agent.agents[shooter_id] except KeyError: return victim = self.agent.shoot(shooter_id, victim_pos) self.agent.game_statistic.shoot(victim, shooter.team) if victim is None: return damage = 2 if shooter.type == CLASS_SOLDIER else 1 damage *= shots victim.health -= damage logger.info("Victim hit: {}".format(victim)) if victim.health <= 0: victim.health = 0 logger.info("Agent {} died.".format(victim.jid)) if victim.is_carrying_objective: victim.is_carrying_objective = False logger.info( "Agent {} lost the ObjectivePack.".format( victim.jid)) for din_object in self.agent.din_objects.values(): if din_object.type == PACK_OBJPACK: din_object.is_taken = False din_object.owner = 0 msg_pack = Message(to=str(din_object.jid)) msg_pack.set_metadata( PERFORMATIVE, PERFORMATIVE_PACK_LOST) din_object.position.x = victim.locate.position.x din_object.position.y = victim.locate.position.y din_object.position.z = victim.locate.position.z msg_pack.body = json.dumps({ X: victim.locate.position.x, Y: victim.locate.position.y, Z: victim.locate.position.z }) await self.send(msg_pack) # Statistics self.agent.game_statistic.objective_lost( victim.team) break msg_shot = Message(to=victim.jid) msg_shot.set_metadata(PERFORMATIVE, PERFORMATIVE_SHOOT) msg_shot.body = json.dumps({DEC_HEALTH: damage}) await self.send(msg_shot)
def prepare_job_late_inform(self, date, receivers): msg = Message(to=receivers) msg.set_metadata('performative', 'inform') msg.set_metadata('type', 'job_late_inform') msg.body = json.dumps({'arrival_datetime': time_to_str(date)}) return msg
async def run(self): """Behavior main function. Sends messages to ChatAgent or ImageAgent. """ logger.debug("DispatcherBehav running") if self.agent.pipe.poll(): # Avoid blocking thread bot_msg = self.agent.pipe.recv() # Blocking logger.info( "[DispatcherBehav] Received msg from DASI Bot: {}".format( bot_msg)) assert type(bot_msg) == dict t = 10 if 'Image' in bot_msg: # Notify to ImageAgent msg = Message(to=IMAGE_JID) msg.set_metadata("performative", "request") msg.body = bot_msg['Image'] await self.send(msg) # Recive ImageAgent's response response = await self.receive(timeout=3) # Pass response to bot - notify to user if response: ingred = self.agent.INGREDIENTS[int(response.body)] self.agent.pipe.send(ingred) # else: # self.agent.pipe.send('Lo siento, el servidor tiene problemas. Prueba más tarde') elif 'CU-001' in bot_msg: # Notify CheffAgent msg = Message(to=CHEFF_JID) msg.set_metadata("performative", "request") msg.body = 'Start cooking!' await self.send(msg) # Recive cheff's response response = await self.receive(timeout=t) # Pass response to bot - notify to user if response: all_menus = np.array(json.loads(response.body)) if all_menus.max() > 0: # # JSON with best recipe # menu = { # 'Title': self.recipe_book[all_menus.argmax()]['Title'], # 'Ingredients': self.recipe_book[all_menus.argmax()]['Ingredients'], # 'Directions': self.recipe_book[all_menus.argmax()]['Steps'], # } # List with 5 best recipes menu = [] N = 5 best_menu = all_menus.argsort()[-N:][::-1] for m in best_menu: if all_menus[m] > 0: menu.append(self.recipe_book[m]['Title']) else: break else: menu = None self.agent.pipe.send(menu) else: self.agent.pipe.send( 'Lo siento, el servidor tiene problemas. Prueba más tarde' ) elif 'CU-002' in bot_msg: # Notify cheff msg = Message(to=CHEFF_JID) msg.set_metadata("performative", "query_ref") msg.body = str(self.agent.RECIPES.index(bot_msg['CU-002'])) logger.info( f"[DispatcherBehav] {bot_msg['CU-002']} - {msg.body}") await self.send(msg) # Recive cheff's response response = await self.receive(timeout=t) # Pass response to bot - notify to user if response: lst = json.loads(response.body) self.agent.pipe.send(lst) else: self.agent.pipe.send( 'Lo siento, el servidor tiene problemas. Prueba más tarde' ) elif 'CU-003' in bot_msg: prefs = bot_msg['CU-003'] f = bot_msg['factor'] logger.info( f'[DispatcherBehav] Message containing {len(prefs)} preferences' ) logger.info(f'[DispatcherBehav] Factor of prefs is {f}') msg = Message(to=CHEFF_JID) msg.set_metadata("performative", "inform_ref") v = -10 if f == 'GuardarAlergia' else 5 msgs = [] for i in prefs: logger.info(i) msgs.append({ 'Ingredient': self.agent.INGREDIENTS.index(i), 'Value': v }) msg.body = json.dumps(msgs) await self.send(msg) logger.info(f"[DispatcherBehav] Message sent: {msg.body}") elif 'CU-004' in bot_msg: choice = self.agent.RECIPES.index(bot_msg['CU-004']) menu = { 'Title': self.recipe_book[choice]['Title'], 'Ingredients': self.recipe_book[choice]['Ingredients'], 'Directions': self.recipe_book[choice]['Steps'], } self.agent.pipe.send(menu) else: # bad message logger.warning( f'[DispatcherBehav] Message recived: {bot_msg}')
async def run(self): msg = Message(to=self.agent.service_jid) msg.set_metadata("performative", "deregister_agent") await self.send(msg)
def _prepare_gossip_message(receiver, information): msg = Message(to=receiver) msg.body = information.body msg.metadata = dict(gossip_id=information.id) return msg
async def run(self): res = await self.receive(timeout=10000) msg = Message(to="pack1@localhost") msg.set_metadata("performative", "inform") msg.body = "Hello" await self.send(msg)
async def run(self): msg = Message(to=self.agent.service_jid) msg.set_metadata("performative", "register") msg.body = service_name await self.send(msg)
async def run(self): msg = Message(to=self.m_Manager) msg.set_metadata("performative", "inform") msg.body = "ID: " + self.agent.name + " DESTROY " await self.send(msg) self.agent._kill()
def __init__(self, sender_agent: AgentType, to_agent: AgentType = AgentType.COORDINATOR) -> None: self.__message = Message() self.stream_name(to_agent.value) self.to(to_agent) self.sender_name(sender_agent.value)
def test_agent_in_msg_false(): msg = Message(to="agent2@server") assert not _agent_in_msg(JID.fromstr("agent@server"), msg)
def prepare_preferences_inform(self, optimal_temperature, receivers): msg = Message(to=receivers) msg.set_metadata('performative', 'inform') msg.set_metadata('type', 'preferences_inform') msg.body = json.dumps({'optimal_temperature': optimal_temperature}) return msg
async def run(self): logging.info("adaptor is running") basejid = Configuration.parameters['userjid'] simjid = Configuration.parameters['simulator'] msg = await self.receive(timeout=5) logging.info(msg) if isinstance(msg, type(None)): for i in range(self.agent.mexToSend.qsize()): mex = Message(to=basejid+"/"+simjid) message = self.agent.mexToSend.get_nowait() mex.body = message await self.send(mex) else: # dispatched.put_nowait({"time": msg.metadata, "message": msg.body}) try: dictB = json.loads(msg.body) self.agent.last_object_type = dictB['message']['subject'] if self.agent.oldStart == 0: self.agent.oldStart = int(msg.metadata) if int(msg.metadata) < int(self.agent.oldStart) + 900: self.agent.dispatched.put_nowait({"time": msg.metadata, "message": msg.body}) if self.agent.last_object_type == "LOAD" and self.agent.interval == self.agent.nextInterval: mex = Message(to=basejid+"/"+simjid) message = "AckMessage" mex.body = message await self.send(mex) elif self.agent.last_object_type == "LOAD" and self.agent.interval != self.agent.nextInterval and self.agent.mexToSend.qsize() != 0: for i in range(self.agent.mexToSend.qsize()): mex = Message(to=basejid+"/"+simjid) message = self.agent.mexToSend.get_nowait() mex.body = message await self.send(mex) self.agent.nextInterval = self.agent.interval elif self.agent.last_object_type == "LOAD" and self.agent.interval != self.agent.nextInterval and self.agent.mexToSend.qsize() == 0: msg = Message(to=basejid+"/"+simjid) message = "AckMessage" msg.body = message await self.send(msg) self.agent.nextInterval = self.agent.interval else: self.agent.dispatched.put_nowait({"time": msg.metadata, "message": msg.body}) if self.agent.last_object_type == "LOAD" and self.agent.mexToSend.qsize() != 0: for i in range(self.agent.mexToSend.qsize()): mex = Message(to=basejid+"/"+simjid) message = self.agent.mexToSend.get_nowait() mex.body = message await self.send(mex) self.agent.interval += 1 self.agent.nextInterval = self.agent.interval elif self.agent.last_object_type == "LOAD" and self.agent.mexToSend.qsize() == 0: mex = Message(to=basejid+"/"+simjid) message = "AckMessage" mex.body = message await self.send(mex) self.agent.nextInterval = self.agent.interval else: self.agent.interval += 1 self.agent.oldStart = msg.metadata except Exception as e: logging.warning(e)
def prepare_refuse_proposal(self, guid, receivers): msg = Message(to=receivers) msg.set_metadata('performative', 'refuse_proposal') msg.set_metadata('type', 'refuse_proposal') msg.body = json.dumps({'meeting_guid': guid}) return msg
async def run(self): print("[{}] orders Partner to die".format(self.agent.jid)) msg = Message(to="partner@localhost", body="Die") await self.send(msg) self.kill(exit_code=0)
async def on_end(self): msg_to_send: Message = Message( "actionexecutor@localhost", metadata=dict(performative="inform")) msg_to_send.body = dumps(self.agent.decision) await self.send(msg_to_send)
def _prepare_respawn_notification(receiver, *, performative="inform"): msg = Message(to=receiver) msg.body = "respawn_notification" msg.thread = None msg.set_metadata("performative", performative) return msg
async def run(self): msg = Message(to=self.agent.MiddleMan, body="Registration") self.agent.say(f"Sending message: {msg.body}") await self.send(msg) self.set_next_state("AcceptMessage")
def test_agent_in_msg_sender(): msg = Message(sender="agent@server") assert _agent_in_msg(JID.fromstr("agent@server"), msg)