public void action() { attempts++; logger.info(getLocalName() + ":" + "Attempting to cancel " + subjectName + ":" + sectionName); DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(subjectName); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(myAgent, template); if (result.length != 0) { logger.info(getLocalName() + ": " + result[0].getName().getLocalName() + " agent found."); enlistorAgent = result[0].getName(); msg = new ACLMessage(ACLMessage.REQUEST); msg.setContentObject(new EnlistorMessage(ACTION_CANCEL_SLOT, sectAss)); msg.addReceiver(enlistorAgent); send(msg); reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM)); if (reply != null && reply.getContent().equals(MSG_CONFIRM)) { schedule.removeSectionAssignment(subjectName); } } } catch (Exception fe) { fe.printStackTrace(); } }
/** * Permet de trouver tous les agents en fonction d'un service * * @param service * @return tableau d'adresses d'agents */ protected AID[] findAgentsFromService(String service) { DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(service); dfd.addServices(sd); SearchConstraints ALL = new SearchConstraints(); ALL.setMaxResults(new Long(-1)); AID[] agents = null; try { DFAgentDescription[] result = DFService.search(this, dfd, ALL); agents = new AID[result.length]; for (int i = 0; i < result.length; i++) { agents[i] = result[i].getName(); } } catch (FIPAException fe) { fe.printStackTrace(); } return agents; }
private void proposeMove(String queenName) { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("Publish-queen"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(this, template); if (result != null && result.length > 0) { ACLMessage msg = new ACLMessage(ACLMessage.PROPOSE); for (int i = 0; i < result.length; ++i) { if (result[i].getName().getLocalName().equals(queenName)) { msg.addReceiver(result[i].getName()); } } msg.setContent(ChessCommand.MOVE); send(msg); } else { log.severe("Queen is not registred or not available"); } } catch (FIPAException e) { log.severe(e.getMessage()); } }
/** * Overrides the TickerBehaviour, defining how to update the location on the df (registration to * DF has already been performed during agent setup). Three properties are defined for storing * latitude/longitude/altitude. Only latitude and longitude are used, though. */ protected void onTick() { try { MsnAgent agent = (MsnAgent) myAgent; DFAgentDescription description = agent.getAgentDescription(); ServiceDescription serviceDescription = (ServiceDescription) description.getAllServices().next(); serviceDescription.clearAllProperties(); // retrieve ContactLocation curMyLoc = ContactManager.getInstance().getMyContactLocation(); if (!curMyLoc.equals(myContactLocation)) { Property p = new Property(PROPERTY_NAME_LOCATION_LAT, new Double(curMyLoc.getLatitude())); serviceDescription.addProperties(p); p = new Property(PROPERTY_NAME_LOCATION_LONG, new Double(curMyLoc.getLongitude())); serviceDescription.addProperties(p); p = new Property(PROPERTY_NAME_LOCATION_ALT, new Double(curMyLoc.getAltitude())); serviceDescription.addProperties(p); DFService.modify(myAgent, description); myContactLocation = curMyLoc; } } catch (FIPAException fe) { myLogger.log(Logger.SEVERE, "Error in updating DF", fe); } catch (Exception e) { myLogger.log( Logger.SEVERE, "*** Uncaught Exception for agent " + myAgent.getLocalName() + " ***", e); } }
@Override public void action() { block(15000); if (Biblioteca.podeTrocarDia()) { Biblioteca.quantidadeClientesAtendidos = 0; Biblioteca.quantidadeClientesInicioDia = Biblioteca.clienteIndex; DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(Cliente.TIPO_SERVICO_ACORDAR); sd.setName(Cliente.NOME_SERVICO_ACORDAR); template.addServices(sd); Ambiente.HOJE.add(Calendar.DATE, 1); System.out.println("Passou o dia, data atual: " + Ambiente.HOJE.getTime()); Biblioteca.data.setText(new SimpleDateFormat("dd/MM/yyyy").format(Ambiente.HOJE.getTime())); try { DFAgentDescription[] result = DFService.search(myAgent, template); if (result != null && result.length > 0) { ACLMessage message = new ACLMessage(ACLMessage.REQUEST); message.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST); message.setConversationId(ID_MENSAGEM_ACORDAR_CLIENTE); for (int i = 0; i < result.length; i++) { message.addReceiver(result[i].getName()); } myAgent.addBehaviour(new IniciarAcordarCliente(myAgent, message)); } } catch (FIPAException ex) { Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex); } } }
/** entry point of agent */ protected void setup() { claimDropdownID = false; holdingItem = new Point(0, 0); // nextDestination.add(IDLE); movementVerified = false; awaitingRelease = false; // uiMap = new Map(); updateGuiAgents(); // Robot agent wont start without an active GuiAgent if (guiAgents.length == 0) { /*System.out.println("No gui agent found, robot agent is terminating");*/ doDelete(); } // RobotAgent wont start without coordination arguments (looks like: 1,1 // ) on startup Object[] args = getArguments(); if (args != null && args.length > 0) { location = new Point(Integer.parseInt((String) args[0]), Integer.parseInt((String) args[1])); /*System.out.println(getAID().getName() + " is positioned at " + location.x + "," + location.y);*/ } else { // Make the agent terminate /*System.out.println("No position defined, closing down");*/ doDelete(); } // System.out.println("Hallo! Robot-agent " + getAID().getName() // + " is ready."); // register at yellow pages serivce DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); ServiceDescription sd = new ServiceDescription(); sd.setType("Warehouse-RobotAgent"); sd.setName("Warehouse-RobotAutomation"); dfd.addServices(sd); try { DFService.register(this, dfd); } catch (FIPAException e) { // System.out.println("catch"); e.printStackTrace(); } addBehaviour(new OfferRequestsServer()); // bid on current requests addBehaviour(new AcceptRequestServer()); // accept an incomming request addBehaviour(new MapReceiver()); // awaits a map message from guiAgent addBehaviour(new MapRequest()); // one shot behaviour to load the map addBehaviour(new MovementBehaviour(this, 500)); // every second the // robot is allowed to // move a spot addBehaviour(new HopReply()); // Behaviour which awaits incomming // accept/decline after a hop claim // request addBehaviour(new ArrivalReply()); // Behaviour which awaits incomming go // after arriving at a storage agent this.calculateNextHopSetup(); }
@Override protected void takeDown() { try { DFService.deregister(this); } catch (FIPAException e) { e.printStackTrace(); } System.out.println(getName() + ": I'm going down..."); }
/* * Remember to deregister the services offered by the agent upon shutdown, * because the JADE platform does not do it by itself! */ @Override protected void takeDown() { try { log("De-registering myself from the default DF..."); DFService.deregister(this); } catch (FIPAException fe) { fe.printStackTrace(); } log("I'm done."); }
protected void takeDown() { // Deregister from the yellow pages try { DFService.deregister(this); } catch (FIPAException fe) { fe.printStackTrace(); } // Printout a dismissal message // System.out.println("Robot-agent " + getAID().getName() // + " terminating."); }
public void action() { ServiceDescription sd = new ServiceDescription(); sd.setType(TOUR_GUIDE_AGENT); sd.setName(getName()); DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); dfd.addServices(sd); try { DFAgentDescription[] dfds = DFService.search(myAgent, dfd); if (dfds.length > 0) { DFService.deregister(myAgent, dfd); } DFService.register(myAgent, dfd); System.out.println(getLocalName() + " is ready."); } catch (Exception ex) { System.out.println("Failed registering with DF! Shutting down..."); ex.printStackTrace(); doDelete(); } }
private void register() { DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); ServiceDescription sd = new ServiceDescription(); sd.setType("Publish-chessboard"); sd.setName("Chessboard"); dfd.addServices(sd); try { DFService.register(this, dfd); } catch (FIPAException e) { log.severe(e.getMessage()); } }
/** To shutdown the agent, it deregisters itself from the address services of the platform */ protected void takeDown() { System.out.println("Killing agent " + this.getName()); DFAgentDescription[] roles = this.getDescription(); for (int k = 0; k < roles.length; k++) { try { jade.domain.DFService.deregister(this, roles[k]); } catch (FIPAException fe) { // fe.printStackTrace(); } } MSMRepository.getInstance().remove(this.getLocalName()); MSPRepository.getInstance().remove(this.getLocalName()); }
private AID getSynchroAgent() { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("Synchro"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(myAgent, template); return result[0].getName(); } catch (FIPAException fe) { fe.printStackTrace(); } return null; }
/** Registers a WSIG into a DF */ private void registerIntoDF() { DFAgentDescription dfad = new DFAgentDescription(); dfad.setName(this.getAID()); dfad.addLanguages(FIPANames.ContentLanguage.FIPA_SL); dfad.addProtocols(FIPANames.InteractionProtocol.FIPA_REQUEST); ServiceDescription sd = new ServiceDescription(); sd.setType(AGENT_TYPE); sd.setName(getLocalName()); dfad.addServices(sd); try { DFService.register(this, dfad); } catch (Exception e) { log.error("Agent " + getLocalName() + " - Error during DF registration", e); } }
/** * Overrides the Behaviour.action() method. This method is executed by the agent thread. It * basically defines two sub behaviours, which are in charge of periodically updating the DF and * receiving DF notifications. */ public void action() { try { // first thing to do is to register on the df and save current location if any DFAgentDescription myDescription = new DFAgentDescription(); // fill a msn service description ServiceDescription msnServiceDescription = new ServiceDescription(); msnServiceDescription.setName(MsnAgent.msnDescName); msnServiceDescription.setType(MsnAgent.msnDescType); myDescription.addServices(msnServiceDescription); ContactManager.getInstance().resetModifications(); DFAgentDescription[] onlineContacts = DFService.search(myAgent, myDescription); updateContactList(onlineContacts); MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT); Map<String, Contact> cMap = ContactManager.getInstance().getAllContacts(); Map<String, ContactLocation> cLocMap = ContactManager.getInstance().getAllContactLocations(); ContactListChanges changes = ContactManager.getInstance().getModifications(); myLogger.log( Logger.FINE, "Thread " + Thread.currentThread().getId() + "After reading local contacts and first df query: " + "Adding to VIEW_REFRESH_EVENT this list of changes: " + changes.toString()); event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LISTOFCHANGES, changes); event.addParam(MsnEvent.VIEW_REFRESH_CONTACTSMAP, cMap); event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LOCATIONMAP, cLocMap); MsnEventMgr.getInstance().fireEvent(event); DFUpdaterBehaviour updater = new DFUpdaterBehaviour(myAgent, msnUpdateTime, myContactLocation); MsnAgent agent = (MsnAgent) myAgent; DFSubscriptionBehaviour subBh = new DFSubscriptionBehaviour(myAgent, agent.getSubscriptionMessage()); myAgent.addBehaviour(updater); myAgent.addBehaviour(subBh); } catch (Exception e) { // TODO Auto-generated catch block myLogger.log(Logger.SEVERE, "Severe error: ", e); e.printStackTrace(); } }
private List<AID> addDevicesRecivers() { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("Device"); template.addServices(sd); List<AID> aids = new ArrayList<>(); try { DFAgentDescription[] result = DFService.search(myAgent, template); for (DFAgentDescription agentd : result) { aids.add(agentd.getName()); } } catch (FIPAException fe) { fe.printStackTrace(); } return aids; }
/** * Request for medicine. * * <p>This method sends a <b> FIPA REQUEST </b> message to all agents who offers the <tt> * m_sMedicService </tt> service. * * <p>The content of message is: <tt> ( x , y , z ) ( health ) </tt>. * * <p>Variable <tt> m_iMedicsCount </tt> is updated. * * <p><em> It's very useful to overload this method. </em> */ protected void CallForMedic() { try { DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(m_sMedicService); dfd.addServices(sd); DFAgentDescription[] result = DFService.search(this, dfd); if (result.length > 0) { m_iMedicsCount = result.length; // Fill the REQUEST message ACLMessage msg = new ACLMessage(ACLMessage.REQUEST); for (int i = 0; i < result.length; i++) { DFAgentDescription dfdMedic = result[i]; AID Medic = dfdMedic.getName(); if (!Medic.equals(getName())) msg.addReceiver(dfdMedic.getName()); else m_iMedicsCount--; } msg.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST); msg.setConversationId("CFM"); msg.setContent( " ( " + m_Movement.getPosition().x + " , " + m_Movement.getPosition().y + " , " + m_Movement.getPosition().z + " ) ( " + GetHealth() + " ) "); send(msg); System.out.println(getLocalName() + ": Need a Medic! (v21)"); } else { m_iMedicsCount = 0; } } catch (FIPAException fe) { fe.printStackTrace(); } }
/** * Enregistrement des services * * @param type le type de son agent (TypeAgent) */ protected void registerService(String type) { DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(this.getAID()); ServiceDescription sd = new ServiceDescription(); sd.setType(type); sd.setName(type); dfd.addServices(sd); try { DFService.register(this, dfd); } catch (FIPAException e) { System.err.println( getLocalName() + " registration with DF unsucceeded. Reason: " + e.getMessage()); doDelete(); } }
void buscarMensajeros() { try { DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("Mensajero_Axis"); dfd.addServices(sd); DFAgentDescription[] result = DFService.search(this, dfd); if (result.length > 0) { for (int i = 0; i < result.length; i++) { DFAgentDescription dfdMensajero = result[i]; AID mensajero = dfdMensajero.getName(); if (!mensajero.equals(getName())) m_AidListaMensajeros.add(mensajero); } } } catch (FIPAException fe) { fe.printStackTrace(); } }
/** * Help method to search in the DF * * @param request * @return */ private DFAgentDescription[] searchForBidders(ACLMessage request) { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("IR-enterprise-agent"); sd.setName("Bidder"); template.addServices(sd); DFAgentDescription[] results = null; try { results = DFService.search(myAgent, template); } catch (FIPAException fe) { fe.printStackTrace(); System.err.println("AuctionInit.searchForBidders() : " + fe.getMessage()); } return results; }
/** refreshes the list of current active StorageAgents */ public void updateStorageAgents() { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("Warehouse-StorageAgent"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(this, template); storageAgents = new AID[result.length]; /*System.out.println("Search performed, result amount: " + result.length);*/ for (int i = 0; i < result.length; ++i) { storageAgents[i] = result[i].getName(); /*System.out.println(storageAgents[i].getName());*/ } } catch (FIPAException e) { e.printStackTrace(); /*System.out.println("in the catch");*/ } }
private void solicitarProduto(SolicitacaoPedido solicitacaoPedido) throws FIPAException, IOException { DFAgentDescription df = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(Servicos.Fornecedor); df.addServices(sd); DFAgentDescription[] result = DFService.search(this, df); int i = RandomNumber.rand(0, result.length - 1); AID aid = null; try { aid = result[i].getName(); } catch (Exception ex) { ex.printStackTrace(); } this.enviaSolicitacaoProduto(aid, solicitacaoPedido); }
public void action() { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(swapEntry.getSubject().getName()); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(myAgent, template); if (result.length != 0) { enlistorAgent = result[0].getName(); msg = new ACLMessage(ACLMessage.REQUEST); msg.setContentObject(swapEntry); msg.addReceiver(enlistorAgent); send(msg); reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM)); if (reply != null && reply.getContent().equals(MSG_CONFIRM)) { logger.info(getLocalName() + " swap request added."); } } } catch (Exception fe) { fe.printStackTrace(); } }
/** takes down this agent. A configuration used is stored. */ @Override protected void takeDown() { // Deregister all service try { WSIGService wsigService; for (WSIGService wsigService1 : wsigStore.getAllServices()) { wsigService = wsigService1; deregisterService(wsigService); } } catch (Exception e) { log.error("Agent " + getLocalName() + " - Error during service deregistration", e); } // Deregister WSIG agent try { DFService.deregister(this, getDefaultDF()); } catch (Exception e) { log.error("Agent " + getLocalName() + " - Error during DF deregistration", e); } log.info("Agent " + getLocalName() + " - Taken down now"); }
private void publishServices() { /** ************************************************************** */ /** ************ Publish the two services to DF **************** */ /** ************************************************************** */ ServiceDescription artifactInformation = new ServiceDescription(); artifactInformation.setType("artifact-lookup"); artifactInformation.setName("get-artifact-info"); artifactInformation.addOntologies("get-item-information"); Property args = new Property("args", "Send a Profile and use the ontology: get-item-information"); artifactInformation.addProperties(args); ServiceDescription artifactSearch = new ServiceDescription(); artifactSearch.setType("artifact-search"); artifactSearch.setName("search-for-artifacts"); artifactSearch.addOntologies("request-ids"); args = new Property("args", "Send an ArrayList<Integer> of IDs and use the ontology: request-ids"); artifactSearch.addProperties(args); ServiceDescription buyingArtifacts = new ServiceDescription(); buyingArtifacts.setName("buying-artifacts"); buyingArtifacts.setType("buying-artifacts"); DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); dfd.addServices(artifactInformation); dfd.addServices(artifactSearch); dfd.addServices(buyingArtifacts); try { DFService.register(this, dfd); // System.out.println(getName() + ": Successfully registered services."); } catch (FIPAException e) { e.printStackTrace(); } /** ************************************************************* */ }
/** Initialization */ protected void setup() { // INitialize the logger logger = jade.util.Logger.getMyLogger(this.getClass().getName()); logger.setLevel(Logger.SEVERE); logger.info("Student agent started: " + getLocalName()); // studentNumber = (String)(String)getArguments()[0]; /** Register the agent to the directory facilitator */ DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); ServiceDescription sd = new ServiceDescription(); sd.setType(getLocalName()); sd.setName("Student Agent"); dfd.addServices(sd); try { DFService.register(this, dfd); } catch (FIPAException fe) { fe.printStackTrace(); } // Add main student agent behaviour addBehaviour(new StudentAgentBehaviour()); }
@Override public void action() { // Receive information update from world HashMap<Integer, ConnectionInfo> queryResponses = new HashMap<Integer, ConnectionInfo>(); boolean worldMsg = false; TrafficLightInfoPacket packet = null; while (!worldMsg) { ACLMessage msg = myAgent.blockingReceive(); while (msg.getPerformative() != ACLMessage.INFORM_REF) msg = myAgent.blockingReceive(); try { packet = (TrafficLightInfoPacket) msg.getContentObject(); worldMsg = true; } catch (Exception e) { try { ConnectionInfo conn = (ConnectionInfo) msg.getContentObject(); queryResponses.put(conn.getRoadId(), conn); } catch (Exception e1) { e.printStackTrace(); } } } // Inform all dependent agents ArrayList<ConnectionInfo> info = packet.getInfo(); for (ConnectionInfo conn : info) { // Send register inform to world agent ACLMessage msg2 = new ACLMessage(ACLMessage.INFORM_REF); try { msg2.setContentObject(conn); msg2.addReceiver(conn.getAgentAID()); myAgent.send(msg2); } catch (IOException e) { e.printStackTrace(); } } // Receive responses boolean receiving = false; for (ConnectionInfo conn2 : packet.getInfo()) { if (queryResponses.get(conn2.getNextRoadId()) == null) { receiving = true; break; } } while (receiving) { ACLMessage msg3 = myAgent.blockingReceive(); if (msg3.getPerformative() == ACLMessage.INFORM_REF) { try { ConnectionInfo conn = (ConnectionInfo) msg3.getContentObject(); queryResponses.put(conn.getRoadId(), conn); receiving = false; for (ConnectionInfo conn2 : packet.getInfo()) { if (queryResponses.get(conn2.getNextRoadId()) == null) { receiving = true; break; } } } catch (UnreadableException e) { e.printStackTrace(); } } } int verticalSend = 0; int horizontalSend = 0; HashMap<Integer, ConnectionInfo> connections = new HashMap<Integer, ConnectionInfo>(); for (ConnectionInfo conn : packet.getInfo()) { int localMin = Math.min(conn.getMaxCarSpeed(), conn.getCarCount()); connections.put(conn.getNextRoadId(), conn); if (conn.getRoadOrientation() == Orientation.UP || conn.getRoadOrientation() == Orientation.DOWN) verticalSend += localMin; else horizontalSend += localMin; } for (Entry<Integer, ConnectionInfo> entry : queryResponses.entrySet()) { Orientation ori = connections.get(entry.getValue().getRoadId()).getRoadOrientation(); if (ori == Orientation.UP || ori == Orientation.DOWN) verticalSend -= (entry.getValue().getRoadCapacity() - entry.getValue().getCarCount()); else horizontalSend -= (entry.getValue().getRoadCapacity() - entry.getValue().getCarCount()); } boolean openVertical; if (verticalSend < horizontalSend) openVertical = true; else openVertical = false; // Build response to world ++cycleCount; boolean stateChanged = true; WorldUpdatePacket reply = new WorldUpdatePacket(); for (ConnectionInfo conn : packet.getInfo()) { UpdateInfo uInfo = new UpdateInfo(); uInfo.setRoadId(conn.getRoadId()); uInfo.setNextRoadId(conn.getNextRoadId()); if (cycleCount >= MAX_CYCLES_WITHOUT_CHANGE) { uInfo.setCurrentState(!conn.isCurrentState()); } else if (cycleCount <= MIN_CYCLES_WITHOUT_CHANGE) { uInfo.setCurrentState(conn.isCurrentState()); } else { if (openVertical && (conn.getRoadOrientation() == Orientation.UP || conn.getRoadOrientation() == Orientation.DOWN)) uInfo.setCurrentState(true); else if (!openVertical && (conn.getRoadOrientation() == Orientation.LEFT || conn.getRoadOrientation() == Orientation.RIGHT)) uInfo.setCurrentState(true); else uInfo.setCurrentState(false); } if (uInfo.isCurrentState() == conn.isCurrentState()) stateChanged = false; reply.addUpdateInfo(uInfo); } if (stateChanged) cycleCount = 0; // Reply to world DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd1 = new ServiceDescription(); sd1.setType(Vocabulary.WORLD_AGENT_TYPE); template.addServices(sd1); DFAgentDescription[] result = {}; try { result = DFService.search(myAgent, template); while (result.length <= 0) { result = DFService.search(myAgent, template); } // Clear message queue before responding while (myAgent.receive() != null) {} // Send register inform to world agent ACLMessage replyMsg = new ACLMessage(ACLMessage.INFORM_REF); replyMsg.setContentObject(reply); replyMsg.addReceiver(result[0].getName()); myAgent.send(replyMsg); } catch (FIPAException | IOException e) { e.printStackTrace(); } }
/* * Method that register the room agent to the df and defines requests managment */ protected void registerRoom() { // Create the agent description. DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); // Create the services description. ServiceDescription deviceListSD = new ServiceDescription(); deviceListSD.setType(HomeAutomation.SERVICE_ROOM_DEVICE_LIST); deviceListSD.setName("JADE-room-device-list"); ServiceDescription deviceRegistrationSD = new ServiceDescription(); deviceRegistrationSD.setType("room-device-registration"); deviceRegistrationSD.setType(HomeAutomation.SERVICE_ROOM_DEVICE_REGISTRATION); deviceRegistrationSD.setName("JADE-room-device-registration"); // Add the services description to the agent description. // TODO add here other Sevice Descriptions dfd.addServices(deviceListSD); dfd.addServices(deviceRegistrationSD); try { // Register the service log( "Registering '" + deviceListSD.getType() + "' service named '" + deviceListSD.getName() + "'" + "to the default DF..."); DFService.register(this, dfd); log("Waiting for request..."); } catch (FIPAException fe) { fe.printStackTrace(); } // Add the behaviour serving queries from controller agents. MessageTemplate template = AchieveREResponder.createMessageTemplate(FIPANames.InteractionProtocol.FIPA_REQUEST); addBehaviour( new AchieveREResponder(this, template) { @Override protected ACLMessage handleRequest(ACLMessage request) throws NotUnderstoodException, RefuseException { log("Handle request with content"); return new ACLMessage(ACLMessage.AGREE); } @Override protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage response) { // log("Prepare result notification with content: " + request.getContent()); response.setPerformative(ACLMessage.INFORM); Message message = null; try { message = (Message) request.getContentObject(); } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (message != null) { if (message.getService().equals(HomeAutomation.SERVICE_ROOM_DEVICE_LIST)) { try { // send device array response.setContentObject(devices); } catch (IOException e) { e.printStackTrace(); } } else if (message .getService() .equals(HomeAutomation.SERVICE_ROOM_DEVICE_REGISTRATION)) { RegistrationMessage regMessage = (RegistrationMessage) message; if (regMessage.getParentId().equals(id)) { AgentMessage agentDesc = new AgentMessage( regMessage.getAid(), regMessage.getParentId(), regMessage.getName(), regMessage.getDescription()); devices.add(agentDesc); log( "Device " + request.getSender() + " successfully added to room's device list."); } else { // send refuse.. log("Wrong room!!"); response.setPerformative(ACLMessage.REFUSE); } } } return response; } }); }
/** * The intialization, first, starts the GUI components that will show internal agent information * to the user. Later on, it starts the locks manager which is responsible of preventing some * information to be removed before transmited to other agents. Following, the agent is registered * into JADE yellow pages service with the descriptors extracted from method getDescription. Next, * an agent model diagram is created to show the mental state of the agent. It also register * action listener to react accordingly to user actions on the diagram. Next, it uses the transfer * object utility functions to assert information passed to the agent at construction time. Some * operations cannot be performed until the agent is fully connected to JADE. For those * operations, they require data that can only be passed in the constructor of the agent. To make * these data available in the setup method, we use the method setEnabledO2ACommunication and * getO2AObject. After these initializations, the agent is ready to initialize its internal * behaviors to handle incoming messages. For more details, look at the comments in the method * body. */ public void setup() { try { super.setup(); if (IAFProperties.getGraphicsOn()) { this.graphics = new AgentGraphics(this.getName()); } this.lman = new LocksManager(this.getAID().getLocalName(), cl); /** * Registers the agent in the yellow pages services. It uses the getDescription to obtain a * list of services the agent can provide */ DFAgentDescription[] roles = this.getDescription(); for (int k = 0; k < roles.length; k++) { try { synchronized (synRegister) { // System.err.println("iniciando registro"); jade.domain.DFService.register(this, roles[k]); // System.err.println("registrado"); } } catch (FIPAException fe) { if (!(fe.getMessage().toLowerCase().indexOf("already") >= 0)) { System.out.println( fe.getACLMessage().getPerformative(fe.getACLMessage().getPerformative())); } else { try { synchronized (synRegister) { // System.err.println("iniciando registro 2"); jade.domain.DFService.register(this, roles[k]); // System.err.println("registrado 2"); } } catch (FIPAException fe1) { // No more exception should be produced } } } } /** Creates the GUI for the Mental State Manager */ AgentModelPanelIAF amm = null; if (IAFProperties.getGraphicsOn()) { ids = IDEState.emptyIDEState(); amm = new AgentModelPanelIAF( new ingenias.editor.entities.AgentModelDataEntity("1"), "1", new Model(ids)); amm.setMarqueeHandler(new AgentModelMarqueeHandlerIAF(amm)); } /** * Initializes the Mental State Manager and the Mental State Processor. The mental state * processor is associated to the GUI of the agents. */ if (IAFProperties.getGraphicsOn()) this.msm = new MentalStateManager(ids, amm, this.getAID().getLocalName()); else this.msm = new MentalStateManager(ids, this.getAID().getLocalName()); // this.addBehaviour(this.msm.getConvTracker()); if (IAFProperties.getGraphicsOn()) this.graphics.setMentalStatePanel(this.getLocalName(), amm); if (IAFProperties.getGraphicsOn()) this.msp = new ingenias.jade.MentalStateProcessor(msm, this, this.getGraphics()); else this.msp = new ingenias.jade.MentalStateProcessor(msm, this); this.lman.register(msp); // To get notifications of locks removal/addition /** * Creates handlers to deal with operations made on the GUI representing the Mental State * Manager */ /*this.msm.registerChangeListener(new GraphModelListener(){ public void graphChanged(GraphModelEvent arg0) { MainInteractionManager.logMSM("Evaluating changes in mental state",getLocalName()); if (arg0!=null){ if (arg0.getChange().getInserted()!=null) for (int k=0;k<arg0.getChange().getInserted().length;k++){ MainInteractionManager.logMSM("Inserted "+arg0.getChange().getInserted()[k],getLocalName()); } if (arg0.getChange().getRemoved()!=null){ for (int k=0;k<arg0.getChange().getRemoved().length;k++){ getMSM().remove(arg0.getChange().getRemoved()[k].toString()); // removes the entity if removed from the panel MainInteractionManager.logMSM("Removed "+arg0.getChange().getRemoved()[k],getLocalName()); } } if (arg0.getChange().getChanged()!=null) for (int k=0;k<arg0.getChange().getChanged().length;k++){ MainInteractionManager.logMSM("Changed "+arg0.getChange().getChanged()[k],getLocalName()); } } msp.doReplan(); } });*/ /** * It creates the initial mental state of the agent. It retrieves elements from the * getO2AObject method, a data transfer method. */ MentalEntity queue = null; do { queue = (MentalEntity) this.getO2AObject(); if (queue != null) { try { this.msm.addMentalEntity(queue); } catch (InvalidEntity e) { e.printStackTrace(); } } } while (queue != null); /** * This behavior takes incoming acl messages and distributes them into two groups: messages * being processed and messages not being processed. Messages being processed are added again * to the messages queue so that they can be processed by a specialized behavior * * @return */ final LifeCycleThread vthread = new LifeCycleThread(this); getMSM().registerChangeListener(vthread); vthread.setName("Lifecycle " + this.getAID().getLocalName()); vthread.start(); // The thread is constantly running so that no new // threads are needed; StateBehaviorChangesListener behaviorChangesListener = null; behaviorChangesListener = new StateBehaviorChangesListener() { private void wakeUpCommsManagementBehavior() { /*while (!mainBehavior.getExecutionState().equalsIgnoreCase(CyclicBehaviour.STATE_BLOCKED)){ //System.out.println(mainBehavior.getExecutionState()); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ if (mainBehavior.getExecutionState().equalsIgnoreCase(CyclicBehaviour.STATE_BLOCKED)) mainBehavior.restart(); } @Override public void protocolFinished() { new Thread("waking up comms from " + getAID().getLocalName()) { public void run() { wakeUpCommsManagementBehavior(); } }.start(); } @Override public void protocolStarted() { new Thread("waking up comms from " + getAID().getLocalName()) { public void run() { wakeUpCommsManagementBehavior(); } }.start(); } @Override public void stateTransitionExecuted(String fromState, String toState) { new Thread("waking up comms from " + getAID().getLocalName()) { public void run() { wakeUpCommsManagementBehavior(); } }.start(); } }; mainBehavior = new CommsManagementBehavior(this, behaviorChangesListener); mainBehavior.setBehaviourName("LifeCycle"); this.addBehaviour(mainBehavior); this.getMainBehavior(); } catch (Throwable t) { t.printStackTrace(); } }
/** * Prints a hello message and creates a sequential behavior. * * <p>First sub-behavior is a finite state machine, which tries to get tour information. It * contacts tour guide agent to get the tour guide. In case of failure, machine ends. If a * response is received, it contacts curator agent to get tour details. * * <p>Second sub-behavior prints goodbye message. */ protected void setup() { /* * Hello message. */ System.out.println(this.getAID().getLocalName() + ": begin operation"); /* * Request sent to the tour guide. It uses TourGuideInitiator class to * make communication easier. */ ACLMessage initTourRequest = new ACLMessage(ACLMessage.REQUEST); initTourRequest.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST); initTourRequest.setContent("request-tour-guide"); /* * The Profiler looks for the registered Tour Guides. */ DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("tour-guide"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(this, template); for (int i = 0; i < result.length; ++i) { initTourRequest.addReceiver(result[i].getName()); } } catch (FIPAException fe) { fe.printStackTrace(); } TourGuideInitiator initGuide = new TourGuideInitiator(this, initTourRequest); /* * Same as above, but with curator agent. */ ACLMessage detailTourRequest = new ACLMessage(ACLMessage.REQUEST); detailTourRequest.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST); detailTourRequest.setContent("request-tour-details"); /* * The Profiler looks for the registered curators. */ template = new DFAgentDescription(); sd = new ServiceDescription(); sd.setType("curator"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(this, template); for (int i = 0; i < result.length; ++i) { detailTourRequest.addReceiver(result[i].getName()); } } catch (FIPAException fe) { fe.printStackTrace(); } CuratorInitiator initCurator = new CuratorInitiator(this, detailTourRequest); /* * State machine consists of two states: * 1. Communication with tour guide agent * 2. Communication with curator agent * 3. Final state * * It is constructed below. */ OneShotBehaviour lastState = new OneShotBehaviour(this) { public void action() {} }; FSMBehaviour fsm = new FSMBehaviour(this); fsm.registerFirstState(initGuide, STATE_GET_GUIDE); fsm.registerState(initCurator, STATE_GET_DETAILS); fsm.registerLastState(lastState, STATE_LAST); fsm.registerTransition(STATE_GET_GUIDE, STATE_GET_DETAILS, 0); fsm.registerTransition(STATE_GET_GUIDE, STATE_LAST, 1); fsm.registerDefaultTransition(STATE_GET_DETAILS, STATE_LAST); /* * Sequential behavior is constructed and added as default agent * behavior. */ SequentialBehaviour seqBeh = new SequentialBehaviour(this); seqBeh.addSubBehaviour(fsm); seqBeh.addSubBehaviour( new OneShotBehaviour(this) { public void action() { System.out.println(myAgent.getAID().getLocalName() + ": closing"); } public int onEnd() { myAgent.doDelete(); return super.onEnd(); } }); addBehaviour(seqBeh); }