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)
async def CallForBackup(self, behaviour): msg = Message() msg.set_metadata("performative", "get") msg.to = self.service_jid msg.body = self.BACKUP_SERVICE await behaviour.send(msg) result = await behaviour.receive(timeout=10000) if result: self.m_iSoldiersCount = len(result) ## Fill the REQUEST message msg = Message() msg.set_metadata("performative", "cfb") msg.body = " ( " + str(self.m_Movement.m_Position.x) + " , " + str(self.m_Movement.m_Position.y) + " , " + \ str(self.m_Movement.m_Position.z) + " ) ( " + str(self.m_iHealth) + " ) " for backup in result.body: msg.to = backup await behaviour.send(msg) print(self.name + ": Need a Backup! (v32)") else: self.m_iSoldiersCount = 0
def test_match_xor(): t1 = Template() t1.sender = "sender1@host" t2 = Template() t2.to = "recv1@host" t2.metadata = {"performative": "query"} m1 = Message() m1.sender = "sender1@host" assert (t1 ^ t2).match(m1) m2 = Message() m2.to = "recv1@host" m2.metadata = {"performative": "query"} assert (t1 ^ t2).match(m2) m3 = Message() m3.sender = "sender2@host" m3.to = "recv1@host" m3.metadata = {"performative": "inform"} assert not (t1 ^ t2).match(m3) t1 = Template() t1.sender = "sender1@host" t2 = Template() t2.sender = "sender1@host" m4 = Message() m4.sender = "sender1@host" assert not (t1 ^ t2).match(m4)
async def CallForAmmo(self, behaviour): msg = Message() msg.set_metadata("performative", "get") msg.to = self.service_jid msg.body = self.AMMO_SERVICE await behaviour.send(msg) result = await behaviour.receive(timeout=10000) if result: self.m_iFieldOpsCount = len(result) # Fill the REQUEST message msg = Message() msg.set_metadata("performative", "cfa") msg.body = " ( " + str(self.m_Movement.m_Position.x) + " , " + str(self.m_Movement.m_Position.y) + " , " +\ str(self.m_Movement.m_Position.z) + " ) ( " + str(self.m_iHealth) + " ) " for ammo in result: msg.to = ammo await behaviour.send(msg) print(self.name + ": Need a Ammo! (v22)") else: self.m_iFieldOpsCount = 0
async def CallForMedic(self, behaviour): msg = Message() msg.set_metadata("performative", "get") msg.to = self.service_jid msg.body = self.MEDIC_SERVICE await behaviour.send(msg) result = await behaviour.receive(timeout=10000) if result: self.m_iMedicsCount = len(result) # Fill the REQUEST message msg = Message() msg.set_metadata("performative", "cfm") msg.body = " ( " + str(self.m_Movement.m_Position.x) + " , " + str(self.m_Movement.m_Position.y) + " , " +\ str(self.m_Movement.m_Position.z) + " ) ( " + str(self.m_iHealth) + " ) " for medic in result: msg.to = medic await behaviour.send(msg) print(self.name + ": Need a Medic! (v21)") else: self.m_iMedicsCount = 0
async def send_request(self, content=None): """ Sends an ``spade.message.Message`` to the coordinator to request a taxi. It uses the REQUEST_PROTOCOL and the REQUEST_PERFORMATIVE. If no content is set a default content with the passenger_id, origin and target coordinates is used. Args: content (dict): Optional content dictionary """ if content is None or len(content) == 0: content = { "passenger_id": str(self.agent.jid), "origin": self.agent.current_pos, "dest": self.agent.dest } if not self.agent.dest: self.agent.dest = random_position() msg = Message() msg.to = self.agent.coordinator_id msg.set_metadata("protocol", REQUEST_PROTOCOL) msg.set_metadata("performative", REQUEST_PERFORMATIVE) msg.body = json.dumps(content) await self.send(msg) self.logger.debug("Passenger {} asked for a taxi to {}.".format(self.agent.name, self.agent.dest))
async def refuse(self, bid=Bid, content=None): """ """ reply = Message() reply.to = str(self.agent.opponent_id) reply.set_metadata("protocol", NEGOTIATION_PROTOCOL) reply.set_metadata("performative", BID_REFUSE_PERFORMATIVE) if content is None or len(content) == 0: content = { "jinn_id": str(self.agent.agent_id), "jinn_name": str(self.agent.name), "opponent_id": str(self.agent.opponent_id), "opponent_name": str(self.agent.opponent_name), "bid": jsonpickle.encode(bid), "bid_index": str(bid.index), "bid_id": str(bid.id) } self.agent.last_action = BID_REFUSE_PERFORMATIVE self.agent.last_content = content reply.body = json.dumps(content) await self.send(reply) print('content', content['bid_id']) logger.info("Jinn {} refused bid {} from {}.".format( self.agent.name, content['bid_id'], self.agent.opponent_name))
async def deassigning_place(self): """ Leave a space of the charging station, when the station has free spaces, the status will change to FREE_STATION """ if self.waiting_list: transport_id = self.waiting_list.pop(0) # time statistics update if len(self.waiting_list) == 0: self.empty_queue_time = time.time() self.total_busy_time += (self.empty_queue_time - self.transports_in_queue_time) logger.debug( "Station {} has a place to charge transport {}".format( self.agent_id, transport_id)) # confirm EXPLICITLY to transport it can start charging reply = Message() reply.to = str(transport_id) reply.set_metadata("protocol", REQUEST_PROTOCOL) reply.set_metadata("performative", ACCEPT_PERFORMATIVE) content = {"station_id": self.agent_id} reply.body = json.dumps(content) await self.send(reply) # await send_confirmation_to_transport(transport_id) else: p = self.get_available_places() if p + 1: self.set_status(FREE_STATION) self.set_available_places(p + 1)
async def go_to_the_station(self, station_id, dest): """ Starts a TRAVEL_PROTOCOL to pick up a customer and get him to his destination. It automatically launches all the travelling process until the customer is delivered. This travelling process includes to update the transport coordinates as it moves along the path at the specified speed. Args: customer_id (str): the id of the customer origin (list): the coordinates of the current location of the customer dest (list): the coordinates of the target destination of the customer """ logger.info("Transport {} on route to station {}".format(self.agent.name, station_id)) reply = Message() reply.to = station_id reply.set_metadata("performative", INFORM_PERFORMATIVE) reply.set_metadata("protocol", TRAVEL_PROTOCOL) content = { "status": TRANSPORT_MOVING_TO_STATION } reply.body = json.dumps(content) self.set("current_station", station_id) self.agent.current_station_dest = dest await self.send(reply) self.agent.num_charges += 1 travel_km = self.agent.calculate_km_expense(self.get("current_pos"), dest) self.agent.set_km_expense(travel_km) try: logger.info("{} going to station {}".format(self.agent.name, station_id)) await self.agent.move_to(self.agent.current_station_dest) except AlreadyInDestination: await self.agent.arrived_to_station()
async def pick_up_customer(self, customer_id, origin, dest): """ Starts a TRAVEL_PROTOCOL to pick up a customer and get him to his destination. It automatically launches all the travelling process until the customer is delivered. This travelling process includes to update the transport coordinates as it moves along the path at the specified speed. Args: customer_id (str): the id of the customer origin (list): the coordinates of the current location of the customer dest (list): the coordinates of the target destination of the customer """ logger.info("Transport {} on route to customer {}".format(self.agent.name, customer_id)) reply = Message() reply.to = customer_id reply.set_metadata("performative", INFORM_PERFORMATIVE) reply.set_metadata("protocol", TRAVEL_PROTOCOL) content = { "status": TRANSPORT_MOVING_TO_CUSTOMER } reply.body = json.dumps(content) self.set("current_customer", customer_id) self.agent.current_customer_orig = origin self.agent.current_customer_dest = dest await self.send(reply) self.agent.num_assignments += 1 try: await self.agent.move_to(self.agent.current_customer_orig) except AlreadyInDestination: await self.agent.arrived_to_destination()
async def send_confirmation_travel(self, station_id): logger.info("Transport {} sent confirmation to station {}".format(self.agent.name, station_id)) reply = Message() reply.to = station_id reply.set_metadata("protocol", REQUEST_PROTOCOL) reply.set_metadata("performative", ACCEPT_PERFORMATIVE) await self.send(reply)
async def send_request(self, content=None): """ Sends an ``spade.message.Message`` to the fleetmanager to request a transport. It uses the REQUEST_PROTOCOL and the REQUEST_PERFORMATIVE. If no content is set a default content with the customer_id, origin and target coordinates is used. Args: content (dict): Optional content dictionary """ if not self.agent.dest: self.agent.dest = random_position() if content is None or len(content) == 0: content = { "customer_id": str(self.agent.jid), "origin": self.agent.current_pos, "dest": self.agent.dest } for fleetmanager in self.agent.fleetmanagers.keys(): # Send a message to all FleetManagers msg = Message() msg.to = str(fleetmanager) msg.set_metadata("protocol", REQUEST_PROTOCOL) msg.set_metadata("performative", REQUEST_PERFORMATIVE) msg.body = json.dumps(content) await self.send(msg) logger.info("Customer {} asked for a transport to {}.".format(self.agent.name, self.agent.dest))
async def send_confirmation(self, agent_id): """ Send a ``spade.message.Message`` with an acceptance to manager/station to register in the dictionary """ reply = Message() reply.to = str(agent_id) reply.set_metadata(PROTOCOL, REGISTER_PROTOCOL) reply.set_metadata(PERFORMATIVE, ACCEPT_PERF) await self.send(reply)
async def InformObjectives(self, behaviour): msg = Message() msg.set_metadata("performative", "objective") msg.body = " ( " + str(self.m_Map.GetTargetX()) + " , " + str(self.m_Map.GetTargetY()) + " , " + str( self.m_Map.GetTargetZ()) + " ) " for agent in self.m_AgentList.values(): msg.to = agent.m_JID await behaviour.send(msg) print("Manager: Sending Objective notification to agents")
async def reject_registration(self, agent_id): """ Send a ``spade.message.Message`` with an acceptance to transport to register in the fleet. """ reply = Message() reply.to = str(agent_id) reply.set_metadata("protocol", REGISTER_PROTOCOL) reply.set_metadata("performative", REFUSE_PERFORMATIVE) reply.body = "" await self.send(reply)
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)
async def accept_registration(self, agent_id): """ Send a ``spade.message.Message`` with an acceptance to transport to register in the fleet. """ reply = Message() content = {"icon": self.agent.fleet_icon, "fleet_type": self.agent.fleet_type} reply.to = str(agent_id) reply.set_metadata("protocol", REGISTER_PROTOCOL) reply.set_metadata("performative", ACCEPT_PERFORMATIVE) reply.body = json.dumps(content) await self.send(reply)
async def charging_complete(self): """ Send a message to the transport agent that the vehicle load has been completed """ reply = Message() reply.to = str(self.transport_id) reply.set_metadata("protocol", REQUEST_PROTOCOL) reply.set_metadata("performative", INFORM_PERFORMATIVE) content = {"status": TRANSPORT_CHARGED} reply.body = json.dumps(content) await self.send(reply)
def formMessage(sender, to, performative, ontology, other=None): message = Message() message.sender = sender message.to = to message.set_metadata("performative", performative) message.set_metadata("ontology", ontology) if other: for value in other.items(): message.set_metadata(value[0], value[1]) return message
async def ask_last_modification_date(self): logger.info("Asking for last modification date") request = Message() request.to = "commitment_store@localhost" request.set_metadata(PROTOCOL, REQUEST_PROTOCOL) request.set_metadata(PERFORMATIVE, LAST_MODIFICATION_DATE_PERF) await self.send(request) msg = await self.receive(timeout=5) if msg: return MessageCodification.get_decoded_message_content(msg) else: return None
async def send_negative(self, agent_id): """ Sends a message to the current assigned manager/station to cancel the registration. Args: agent_id (str): the id of the manager/station """ reply = Message() reply.to = str(agent_id) reply.set_metadata("protocol", QUERY_PROTOCOL) reply.set_metadata("performative", CANCEL_PERFORMATIVE) await self.send(reply)
async def request_access_station(self): reply = Message() reply.to = self.get("current_station") reply.set_metadata("protocol", REQUEST_PROTOCOL) reply.set_metadata("performative", ACCEPT_PERFORMATIVE) logger.debug("{} requesting access to {}".format( self.name, self.get("current_station"), reply.body)) await self.send(reply) # time waiting in station queue update self.waiting_in_queue_time = time.time()
async def send_get_stations(self, content=None): if content is None or len(content) == 0: content = self.agent.request msg = Message() msg.to = str(self.agent.directory_id) msg.set_metadata("protocol", QUERY_PROTOCOL) msg.set_metadata("performative", REQUEST_PERFORMATIVE) msg.body = content await self.send(msg) logger.info("Transport {} asked for stations to Directory {} for type {}.".format(self.agent.name, self.agent.directory_id, self.agent.request))
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())
async def accept(self, bid=Bid, content=None): """ """ if content is None or len(content) == 0: content = { "jinn_id": str(self.agent.agent_id), "jinn_name": str(self.agent.name), "opponent_id": str(self.agent.opponent_id), "opponent_name": str(self.agent.opponent_name), "bid": jsonpickle.encode(bid), "bid_index": str(bid.index), "bid_id": str(bid.id) } # for fleetmanager in self.agent.fleetmanagers.keys(): # Send a message to all FleetManagers msg = Message() msg.to = str(self.agent.opponent_id) msg.set_metadata("protocol", NEGOTIATION_PROTOCOL) msg.set_metadata("performative", BID_ACCEPT_PERFORMATIVE) msg.body = json.dumps(content) self.agent.last_action = BID_ACCEPT_PERFORMATIVE self.agent.last_content = content await self.send(msg) analysis_msg = Message() analysis_msg.to = str(self.agent.analyzer_jid) analysis_msg.set_metadata("protocol", ANALYSIS_PROTOCOL) analysis_msg.set_metadata("performative", ACCEPTANCE_PERFORMATIVE) analysis_msg.body = str(bid.index) await self.send(analysis_msg) logger.info("Jinn {} accepted bid {} from {}.".format( self.agent.name, str(content['bid_id']), self.agent.opponent_name))
async def rate_transport(self, transport_id): reply = Message() reply.to = str(transport_id) reply.set_metadata('protocol', REQUEST_PROTOCOL) reply.set_metadata('performative', RATE_PERFORMATIVE) rate = self.agent.rate() content = { 'customer_id': str(self.agent.jid), 'rate': rate } reply.body = json.dumps(content) await self.send(reply) self.agent.transport_assigned = str(transport_id) logger.info('Customer {} rate the taxi {} with {}'.format(self.agent.name, transport_id, rate))
async def send_registration(self): """ Send a ``spade.message.Message`` with a proposal to directory to register. """ logger.info( "Manager {} sent proposal to register to directory {}".format( self.agent.name, self.agent.directory_id)) content = {"jid": str(self.agent.jid), "type": self.agent.fleet_type} msg = Message() msg.to = str(self.agent.directory_id) msg.set_metadata("protocol", REGISTER_PROTOCOL) msg.set_metadata("performative", REQUEST_PERFORMATIVE) msg.body = json.dumps(content) await self.send(msg)
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)
async def send_services(self, agent_id, type_service): """ Send a message to the customer or transport with the current information of the type of service they need. Args: agent_id (str): the id of the manager/station type_service (str): the type of service """ reply = Message() reply.to = str(agent_id) reply.set_metadata("protocol", QUERY_PROTOCOL) reply.set_metadata("performative", INFORM_PERFORMATIVE) reply.body = json.dumps(self.get("service_agents")[type_service]) await self.send(reply)
async def ask_for_registration(self): logger.info("Asking for registration") request = Message() request.to = "commitment_store@localhost" request.set_metadata(PROTOCOL, REGISTER_PROTOCOL) request.set_metadata(PERFORMATIVE, REQUEST_PERF) await self.send(request) msg = await self.receive(timeout=5) if msg: if msg.get_metadata(PERFORMATIVE) == ACCEPT_PERF: logger.success( "YAHOO! I have been accepted and registered!") self.accepted = True else: logger.error("YIKES! I have been regret")
def create_message( self, agent_jid: str, performative: str, conversation_id: str, content_object ) -> Message: msg = Message() msg.to = agent_jid msg.sender = self.agent_id msg.set_metadata(CONVERSATION, conversation_id) msg.set_metadata(PERFORMATIVE, performative) msg.body = MessageCodification.pickle_object(content_object) logger.info( "{}: message to send to: {} | dialogue_id: {}".format( self.name, msg.to, msg.get_metadata(CONVERSATION) ) ) return msg
async def inform_objectives(self, behaviour): msg = Message() msg.set_metadata(PERFORMATIVE, PERFORMATIVE_OBJECTIVE) content = { X: self.map.get_target_x(), Y: self.map.get_target_y(), Z: self.map.get_target_z(), } msg.body = json.dumps(content) for agent in self.agents.values(): msg.to = agent.jid logger.info("Sending objective to {}: {}".format(agent.jid, msg)) await behaviour.send(msg) logger.info("Manager: Sending Objective notification to agents")
def test_behaviour_match_without_template(): class TestBehaviour(OneShotBehaviour): async def run(self): pass behaviour = TestBehaviour() msg = Message() msg.sender = "sender1@host" msg.to = "recv1@host" msg.body = "Hello World" msg.thread = "thread-id" msg.set_metadata("performative", "query") assert behaviour.match(msg)
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
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_to_set_string(): msg = Message() msg.to = "agent@fakeserver"
def test_to_set_not_string(): msg = Message() with pytest.raises(TypeError): msg.to = 1000
def test_to_set_none(): msg = Message() msg.to = None