private void handleAuctionStart(ACLMessage msg) { try { if (msg.getContentObject() != null && msg.getContentObject() instanceof Auction) { final Auction auction = (Auction) msg.getContentObject(); knownAuctions.add(auction); myAgent.addBehaviour( new OneShotBehaviour() { @Override public void action() { participatingAuctions.add(auction); Random random = new Random(); double maxFactor = ((double) (random.nextInt(60) + 30)) / 100; int maxPrice = (int) ((float) auction.getCurrentPrice() * maxFactor); int strategy = 0; int prefPrice = (int) ((float) 0.7 * maxPrice); BidSettings bs = new BidSettings(maxPrice, prefPrice, strategy); auctionSettings.put(auction.getArtifact().getId(), bs); } }); } else { block(); } } catch (UnreadableException ex) { block(); } }
@Override protected ACLMessage handleCfp(ACLMessage cfp) throws RefuseException, FailureException, NotUnderstoodException { ACLMessage reply = cfp.createReply(); reply.setPerformative(ACLMessage.PROPOSE); if (myAgent.getClass() == AGV.class) { try { if (cfp.getContentObject().getClass() == Cfp.class) reply = getAgvResponseMessage(reply, (Cfp) cfp.getContentObject(), (AGV) myAgent); } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } else if (myAgent.getClass() == Machine.class) { try { reply = getMachineMessageContent(reply, (Cfp) cfp.getContentObject()); } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } return reply; }
private void handleReject(ACLMessage msg) { try { if (msg.getContentObject() != null && msg.getContentObject() instanceof Auction) { final Auction auction = (Auction) msg.getContentObject(); } else { block(); } } catch (UnreadableException ex) { block(); } }
private void handleCFP(ACLMessage msg) { try { if (msg.getContentObject() != null && msg.getContentObject() instanceof Auction) { final Auction auction = (Auction) msg.getContentObject(); if (participatingAuctions.contains(auction)) { myAgent.addBehaviour( getStrategy(msg, curator, auctionSettings.get(auction.getArtifact().getId()))); } } else { block(); } } catch (UnreadableException ex) { block(); } }
private ACLMessage handleProfilerRequest(ACLMessage request) { AID profiler = request.getSender(); ArrayList<Integer> requestedIDs; try { requestedIDs = (ArrayList<Integer>) request.getContentObject(); // System.out.println(getName() + ": Received request from Profiler. He requested " + // requestedIDs.size() + " IDs."); } catch (UnreadableException e) { System.err.println( myAgent.getAID().getName() + ": Couldn't get IDs to look up. Will respond with an empty list..."); requestedIDs = new ArrayList<>(); } String conversationID = request.getConversationId(); ArrayList<Artifact> relatedArtifacts = new ArrayList<>(); for (Integer id : requestedIDs) for (Artifact a : artifacts) if (a.getId() == id) relatedArtifacts.add(a); ACLMessage response = new ACLMessage(ACLMessage.INFORM); response.addReceiver(profiler); response.setConversationId(conversationID); response.setOntology("tour-info"); try { response.setContentObject(relatedArtifacts); } catch (IOException e) { System.err.println( myAgent.getAID().getName() + ": Couldn't serialize the Artifact list... Will cause problems with other agents."); } return response; // System.out.println(myAgent.getAID().getName() + ":Response message sent to Profiler with " // + relatedArtifacts.size() + " artifacts."); }
@Override protected ACLMessage handleAcceptProposal(ACLMessage cfp, ACLMessage propose, ACLMessage accept) { // TODO Handle the accept Cfp content = null; try { content = (Cfp) accept.getContentObject(); } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println(myAgent.getLocalName() + ": proposta aceite:" + // propose.getConversationId() + " content = " + content.getOrigin().getLocalName() + " " + // content.getDestination().getLocalName() + " " + content.getAgv().getLocalName()); ACLMessage reply = accept.createReply(); reply.setPerformative(ACLMessage.INFORM); if (myAgent.getClass() == AGV.class) { AGV a = (AGV) myAgent; AgvTransport t = new AgvTransport((AGV) myAgent, content); a.setTransportBehaviour(t); a.addBehaviour(new AgvTransport(a, content)); } return reply; }
@Override public void action() { try { System.out.println(getBehaviourName() + " msg received"); EQRRoutingCriteria req = (EQRRoutingCriteria) message.getContentObject(); EQRRoutingResult res = null; ACLMessage reply = message.createReply(); try { System.out.println(getBehaviourName() + " Requesting route from server"); res = ((GraphHopperServer) router).setCriteria(req).requestRouting().getRoutingResult(); reply.setPerformative(ACLMessage.INFORM); } catch (EQRException e) { System.out.println(getBehaviourName() + "Error when requesting route..."); e.getMessage(); res = new EQRRoutingError(); reply.setPerformative(ACLMessage.INFORM); /* * TODO: Change this * later */ } finally { System.out.println("Routing Behaviour: Request completed....Sending reply"); reply.setContentObject(res); myAgent.send(reply); } } catch (Exception e) { e.printStackTrace(); } }
private void handleModMsg(ACLMessage msg) { myConnector.allmodelagents--; try { if (myConnector.mode) { UserModData data = (UserModData) msg.getContentObject(); myConnector.usermodset.add(data); } else { RouterModData data = (RouterModData) msg.getContentObject(); myConnector.routermodset.add(data); } } catch (Exception e) { log.log(Logger.SEVERE, "Exception:", e); } if (myConnector.allmodelagents == 0) { myConnector.finishModeling(); } }
private void handleAuctionWon(ACLMessage msg) { try { if (msg.getContentObject() != null && msg.getContentObject() instanceof Auction) { final Artifact art = ((Auction) msg.getContentObject()).getArtifact(); boughtArtifacts.add(art); for (Auction auction : participatingAuctions) { Auction match = getAuction(auction); if (match != null && match.getArtifact().getId() == art.getId()) { participatingAuctions.remove(match); knownAuctions.remove(match); break; } } } else { block(); } } catch (UnreadableException ex) { block(); } }
@Override public void action() { while ((msg = myAgent.receive(mt)) != null) { switch (msg.getPerformative()) { case ACLMessage.REQUEST: if (msg.getProtocol().equals(Constants.REQUEST_ROUTE)) { AIDPair destSrcPair; try { destSrcPair = (AIDPair) msg.getContentObject(); log.log( Logger.INFO, myAgent.getLocalName() + "# received request for path(" + destSrcPair.getFirst().getLocalName() + ", " + destSrcPair.getSecond().getLocalName() + ") from " + msg.getSender().getLocalName()); myAgent.addBehaviour( new ConnSendRoute( msg.getSender(), destSrcPair.getFirst(), destSrcPair.getSecond())); } catch (UnreadableException e) { log.log(Logger.SEVERE, "Read msg content Exception: ", e); } } break; case ACLMessage.INFORM: log.log( Logger.INFO, myAgent.getLocalName() + "#" + msg.getSender().getLocalName() + " notified about failure"); if (msg.getProtocol().equals(Constants.INFORM_COFFEE)) { AID aid = msg.getSender(); if (msg.getContent().equals("down")) myConnector.nodeStatusChange(aid, false); else myConnector.nodeStatusChange(aid, true); } break; case ACLMessage.CONFIRM: log.log( Logger.INFO, myAgent.getLocalName() + "#" + msg.getSender().getLocalName() + " finished modeling"); if (msg.getProtocol().equals(Constants.CONFIRM_FINISHMODELING)) { handleModMsg(msg); } break; } } // Блокируем поведение, пока в очереди сообщений агента // не появится хотя бы одно сообщение block(); }
@Override public void handleMessage(ACLMessage msg) { System.out.println(myAgent.getAID().getName() + " RECIEVED message: " + msg.getOntology()); if (msg != null) { Object o = null; try { o = msg.getContentObject(); if (o == null) { block(); } } catch (UnreadableException ex) { Logger.getLogger(TourGuideAgent.class.getName()).log(Level.SEVERE, null, ex); block(); } if (msg.getOntology().equalsIgnoreCase(Ontologies.PROFILER_REQUEST_TOUR_AGENT)) { UserProfile up = (UserProfile) o; tourGuide.usersLock.lock(); try { tourGuide.getUsers().put(msg.getSender(), up); } finally { tourGuide.usersLock.unlock(); } tourGuide.startTour(); } else if (msg.getOntology().equalsIgnoreCase(Ontologies.QUERY_ARTIFACTS)) { Map<String, AID> requests = tourGuide.getRequests(); final AID user = requests.get(msg.getConversationId()); List<ACLMessage> msglist = tourGuide.getResponses().get(user); msglist.add(msg); System.out.println( "added msg " + msg + " to msgList: " + tourGuide.getResponses().get(user)); requests.remove(msg.getConversationId()); } } else { System.err.println("Agent " + myAgent.getAID().getName() + " RECIEVED message: null."); block(); } myAgent.addBehaviour( new TGAMsgReceiverBehaviour(myAgent, null, deadline, getDataStore(), null)); }
public static Serializable callMethod( Class clazz, String methodName, List<Serializable> arguments) { GaiaDAOAgent daoagent = getAvailableDAOAgent(); /** thread */ DAOCallerAgent.DAOCallBehaviour request = new DAOCallerAgent.DAOCallBehaviour( daoagent.getAID(), clazz.getName(), methodName, arguments, false, false); daoCallerAgent.addBehaviour(new ThreadedBehaviourFactory().wrap(request)); ACLMessage msg = daoCallerAgent.blockingReceive(); try { if (msg.getConversationId().equals(DAO_QUERY_REPLY)) { return msg.getContentObject(); } } catch (Exception e) { logger.error(StringUtils.formatErrorMessage(e)); logger.error(msg.getConversationId()); logger.error(msg.getContent()); } return null; }
public void recieveSwapAppointmentReply() throws UnreadableException, IOException { ACLMessage reply = patientAgent.blockingReceive(reqTemplate); if (reply != null) { SwapInfo recievedSwapInfo = (SwapInfo) reply.getContentObject(); if (reply.getPerformative() == ACLMessage.ACCEPT_PROPOSAL) { System.out.println(patientAgent.getName() + " proposal was accepted, now swapping..."); System.out.println( patientAgent.getName() + " was allocated this before: " + (patientAgent.allocatedAppointment + 1) + " and now has " + (recievedSwapInfo.getCurrentSlot() + 1)); informHospital( reply.getSender(), patientAgent.allocatedAppointment, recievedSwapInfo.currentSlot); patientAgent.allocatedAppointment = recievedSwapInfo.currentSlot; // Integer.parseInt(reply.getContent()); patientAgent.highPriorityAppointmentOwner = null; state = 2; } else { System.out.println(patientAgent.getName() + "'s proposal was rejected"); patientAgent.excluded.add(recievedSwapInfo.currentSlot); patientAgent.highPriorityAppointmentOwner = null; patientAgent.swapSlot = -1; state = 2; } patientAgent.swapSlot = -1; patientAgent.addBehaviour(new FindAppointmentOwner(patientAgent)); } else { block(); } }
private ACLMessage handleTourGuideRequest(ACLMessage request) { AID tourGuide = request.getSender(); ArrayList<String> interests; try { interests = (ArrayList<String>) request.getContentObject(); // System.out.println(getName() + ": Will handle " + interests.size() + " interests. // (Successfully read message)"); } catch (UnreadableException e) { System.out.println( myAgent.getAID().getName() + ":ERROR Couldn't get interests. Will respond with an empty list..."); interests = new ArrayList<>(); } String conversationID = request.getConversationId(); ArrayList<Integer> ids = new ArrayList<>(); for (Artifact artifact : artifacts) for (String interest : interests) if (artifact.getGenre().contains(interest) || artifact.getType().equals(interest)) ids.add(artifact.getId()); ACLMessage response = new ACLMessage(ACLMessage.INFORM); response.addReceiver(tourGuide); response.setConversationId(conversationID); response.setOntology("get-artifact-ids"); try { response.setContentObject(ids); } catch (IOException e) { System.err.println( myAgent.getAID().getName() + ": Couldn't serialize the ID-list... Will cause problems with other agents."); } return response; // System.out.println(myAgent.getAID().getName() + ":Response message sent to TourGuide with " // + ids.size() + " IDs."); }
@Override public void action() { // System.out.println(getName() + ": state=Handle_CFP"); informed = false; MessageTemplate template_cfp = MessageTemplate.MatchPerformative(ACLMessage.CFP); MessageTemplate template_nobids = MessageTemplate.MatchContent("no-bids"); ACLMessage cfp = receive(template_cfp); ACLMessage nobids = receive(template_nobids); if (cfp != null && cfp.getConversationId().equals(convID)) { // CFP received try { receivedItem = (Artifact) cfp.getContentObject(); // System.out.println(getName() + ": Received CFP - " + receivedItem.getName()); ACLMessage proposal = new ACLMessage(ACLMessage.PROPOSE); proposal.addReceiver(marketAgent); proposal.setConversationId(convID); if (acceptOffer(receivedItem)) proposal.setContent("yes"); else proposal.setContent("no"); send(proposal); // System.out.println(getName() + ": Proposal sent to Auctioneer. Proposal= " + // proposal.getContent()); } catch (UnreadableException e) { ACLMessage notUnderstood = new ACLMessage(ACLMessage.NOT_UNDERSTOOD); notUnderstood.addReceiver(marketAgent); notUnderstood.setConversationId(convID); send(notUnderstood); } informed = true; status = CFP_RECEIVED; } else if (nobids != null && nobids.getConversationId().equals(convID)) { // System.out.println(getName() + ": No-bids received..."); informed = true; status = NO_BIDS; } else block(); }
/* * Only receive message coming from the patientTODO: Also send out status * messages */ @Override public void action() { MessageTemplate template = MessageTemplate.MatchConversationId(TrafficUpdateMessage.TRAFFIC_SUBSCRIBERS_CONV); List<EQRPoint> points = route.getPoints(); long duration = route.getDuration(); double distance = route.getDistance(); double delay = 0; double rate = 1; if (traffic != null) { delay = traffic.getDelay(); rate = traffic.getSimulationRate(); } double sim_speed = distance / (duration * rate); EQRLogger.log( logger, null, myAgent.getLocalName(), getBehaviourName() + ": Attending to Fire " + fire.getAID().getLocalName()); for (int i = 0; i < points.size() - 1; i++) { ACLMessage up = myAgent.receive(template); if (up != null) { try { Object content = up.getContentObject(); if (content instanceof TrafficUpdateMessage) { traffic = (TrafficUpdateMessage) content; delay = traffic.getDelay(); rate = traffic.getSimulationRate(); sim_speed = distance / (duration * rate); } } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); } } EQRPoint curr = points.get(i); EQRPoint nxt = points.get(i + 1); engine.setCurrentLocation(curr); double dist = EQRAgentsHelper.getDistanceFromGPSCood(curr, nxt); double st = (dist / sim_speed) + delay * rate; try { Thread.sleep((long) st); } catch (InterruptedException e) { e.printStackTrace(); } } engine.setCurrentLocation(points.get(points.size() - 1)); ACLMessage msg = new ACLMessage(ACLMessage.INFORM); ACLMessage msg2 = new ACLMessage(ACLMessage.INFORM); msg2.addReceiver(myAgent.getAID()); msg.addReceiver(fire.getAID()); AttendToFireMessage atf = new AttendToFireMessage(AttendToFireMessage.TO_FIRE); AttendToFireMessage atf2 = new AttendToFireMessage(AttendToFireMessage.TO_FIRE_ENGINE); atf.setEngine(engine); atf2.setFire(fire); try { System.out.println( myAgent.getLocalName() + " Sending msgs out to FireEngine and Fire " + fire.getAID()); msg.setContentObject(atf); msg2.setContentObject(atf2); EQRLogger.log(logger, msg, myAgent.getLocalName(), getBehaviourName() + ": Message sent"); EQRLogger.log(logger, msg2, myAgent.getLocalName(), getBehaviourName() + ": Message sent"); myAgent.send(msg2); myAgent.send(msg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* TODO: send msg to patient and */ done = true; }
@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(); } }
/** * Performs the result reception event, eighter blocking or non-blocking (see constructor), and * outputs result to given strem. Also keeps track of pending requests and manages completion of * the process. */ protected void onWake() { ACLMessage msg; if (Blocking) { msg = myAgent.blockingReceive(); } else if ((msg = myAgent.receive()) == null) { myAgent.addBehaviour(new ReceiveResultBehaviour(myAgent, Interval, pOut, Blocking)); return; } CalcResults caRes = null; SimilarityArray saRes = null; if (msg != null) { try { // Check if not results if (msg.getPerformative() != ACLMessage.INFORM) { // Check if activation if (msg.getPerformative() == ACLMessage.AGREE) { Object oAgentInfo = msg.getContentObject(); synchronized (myAgent) { myAgent.InitializedAgents.remove(oAgentInfo); myAgent.ActiveAgents.add(oAgentInfo); } // Wait for messages synchronized (System.err) { if (!myAgent.Silent) System.err.println("Received move complete message from " + oAgentInfo); } } return; } // Results Object oTemp = msg.getContentObject(); caRes = (CalcResults) oTemp; saRes = caRes.Simil; if (saRes != null) { // pOut.print(msg.getSender().getLocalName().substring("CalcAgent".length() + // myAgent.AgentUniqueIDLength) + // "\t"); pOut.print(caRes.ID + "\t"); // pOut.print(msg.getSender().getLocalName().substring("CalcAgent".length() + // myAgent.AgentUniqueIDLength) + // "\t"); try { pOut.print( saRes.SimpleTextGraphSimil.ContainmentSimilarity + "\t" + saRes.SimpleTextGraphSimil.ValueSimilarity + "\t" + saRes.SimpleTextGraphSimil.SizeSimilarity + "\t" + saRes.SimpleTextHistoSimil.ContainmentSimilarity + "\t" + saRes.SimpleTextHistoSimil.ValueSimilarity + "\t" + saRes.SimpleTextHistoSimil.SizeSimilarity + "\t" + saRes.SimpleTextOverallSimil.getOverallSimilarity() + "\t"); } catch (NullPointerException ne) { // Ignore pOut.print( "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t"); } try { pOut.print( saRes.NGramGraphSimil.ContainmentSimilarity + "\t" + saRes.NGramGraphSimil.ValueSimilarity + "\t" + saRes.NGramGraphSimil.SizeSimilarity + "\t" + saRes.NGramHistoSimil.ContainmentSimilarity + "\t" + saRes.NGramHistoSimil.ValueSimilarity + "\t" + saRes.NGramHistoSimil.SizeSimilarity + "\t" + saRes.NGramOverallSimil.getOverallSimilarity()); } catch (NullPointerException ne) { pOut.print( "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0"); } pOut.println(); } } catch (UnreadableException ex) { System.err.println("Invalid result returned..."); ex.printStackTrace(System.err); } // Decrease pending requests synchronized (myAgent) { myAgent.PendingRequests--; myAgent.CompletedRequests++; if ((!myAgent.Silent) || (myAgent.ShowProgress)) System.err.println( "Completed " + String.format( "%7.4f", (double) myAgent.CompletedRequests / myAgent.AllRequests * 100) + "%"); if (myAgent.CompletedRequests == myAgent.AllRequests) myAgent.complete(); // Finished // DEBUG LINES // System.err.println("Pending " + myAgent.PendingRequests + " requests..."); ////////////// } ; } }
/** The interesting stuff */ public void action() { // increment number of attempts attempts++; // Don't enlist if adding a subject will exceed the allowed units if (schedule.getUnitsObtained() + 3 > (schedule.getWriteIn().getUnitsAllowed())) { done = true; } if (attempts > THRESH || done) { return; } logger.info(getLocalName() + ":" + "Attempting to enlist in " + sub.getName()); // Search for the enlistor of the subject DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(sub.getName()); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(myAgent, template); // Ok we got the enlistor if (result.length != 0) { logger.info(getLocalName() + ": " + sub.getName() + " agent found."); enlistorAgent = result[0].getName(); // Request for sections with available slots at this moment msg = new ACLMessage(ACLMessage.REQUEST); msg.setContentObject(new EnlistorMessage(ACTION_GET_SECTIONS_WITH_SLOTS, null)); msg.addReceiver(enlistorAgent); send(msg); reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM)); Vector sections = (Vector) reply.getContentObject(); // Oops, all sections for this subject are full if (sections.size() == 0) { logger.info(getLocalName() + ":" + "No slots available for " + sub.getName()); } else { // ok we have some sections // Randomize the sections. Collections.shuffle(sections); NoConflictConstraint constraint = new NoConflictConstraint(schedule.getSectionAssignments()); // Look for the first section assignment that does not // conflict with the current form 5 for (Iterator ite = sections.iterator(); ite.hasNext(); ) { SectionAssignment sectAss = (SectionAssignment) ite.next(); if (!constraint.isSatisfied(sectAss.getLecture())) { // System.out.println(getLocalName()+":"+"Conflict in lecture of // "+sectAss.getLecture().getSectionName()); continue; } else if ((sectAss.getLab() != null) && (!constraint.isSatisfied(sectAss.getLab()))) { // System.out.println(getLocalName()+":"+"Conflict in lab of // "+sectAss.getLab().getSectionName()); continue; } else { // Ok no conflict in lab or lecture // send message to enlist to this section assingment // msg. msg = new ACLMessage(ACLMessage.REQUEST); msg.setContentObject(new EnlistorMessage(ACTION_ENLIST, sectAss)); msg.addReceiver(enlistorAgent); send(msg); reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM)); if (reply != null && reply.getContent().equals(MSG_CONFIRM)) { logger.info( getLocalName() + ":" + "enlist to " + sectAss.getSection().getSubject().getName() + " " + sectAss.getSection().getSectionName()); schedule.addSectionAssignment(sectAss); done = true; } break; } } } } } catch (Exception fe) { fe.printStackTrace(); } }
public void action() { // TODO: Implement deliberation of for the next action // action=deliberate(Desire, Beliefs); switch (action) { case ACTION_SEARCH_MAIN_SCHEDULER: logger.info(getLocalName() + " searching for main scheduler..."); DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("scheduler"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(myAgent, template); if (result.length != 0) { logger.info(getLocalName() + ":scheduler agent found."); schedulerAgent = result[0].getName(); } } catch (FIPAException fe) { fe.printStackTrace(); } action = ACTION_GET_FORM5; break; case ACTION_GET_FORM5: try { logger.info(getLocalName() + " requesting for Form 5.."); msg = new ACLMessage(ACLMessage.REQUEST); msg.setContent(MSG_GET_FORM5); msg.addReceiver(schedulerAgent); send(msg); reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM)); if (reply != null) { schedule = (IForm5) reply.getContentObject(); logger.info( getLocalName() + " schedule received, units obtained: " + schedule.getUnitsObtained() + ", units allowed: " + schedule.getWriteIn().getUnitsAllowed()); for (Iterator ite = schedule.getWriteIn().getSubjects().iterator(); ite.hasNext(); ) { ISubject sub = (ISubject) ite.next(); SectionAssignment sectAss = (SectionAssignment) schedule.getSectionAssignment(sub.getName()); if (sectAss != null) { logger.info(sub.getName() + " " + sectAss.getSection().getSectionName()); toCancel = sectAss; } else { logger.info(sub.getName() + " NOT ENLISTED"); } } } } catch (Exception ioe) { ioe.printStackTrace(); } // action=ACTION_POST_SWAP_REQUEST; action = ACTION_ENLIST; break; case ACTION_ENLIST: List unassigned = schedule.getUnassigned(); passCount++; if (unassigned.size() == 0) { action = ACTION_HAPPY; break; } else if (passCount == 1) { Map assignments = schedule.getSectionAssignments(); List subjects = new ArrayList(assignments.keySet()); if (subjects.size() > 1) { Collections.shuffle(subjects); for (int i = 0; i < (subjects.size() - 1); i++) { String subject = (String) subjects.get(i); SectionAssignment sectAss = schedule.getSectionAssignment(subject); myAgent.addBehaviour(new CancelSlotBehaviour(sectAss)); } } /* for(Iterator ite2=assignments.keySet().iterator();ite2.hasNext();){ String subject=(String)ite2.next(); SectionAssignment sectAss=schedule.getSectionAssignment(subject); myAgent.addBehaviour(new CancelSlotBehaviour(sectAss)); } */ // for each unassigned subject, attempt to enlist for (Iterator ite = unassigned.iterator(); ite.hasNext(); ) { ISubject sub = (ISubject) ite.next(); myAgent.addBehaviour(new EnlistBehaviour(sub)); } } else { action = ACTION_HAPPY; } break; case ACTION_CANCEL_SLOT: myAgent.addBehaviour(new CancelSlotBehaviour(toCancel)); action = ACTION_END; break; case ACTION_POST_SWAP_REQUEST: SwapEntry entry = new SwapEntry(getLocalName(), toCancel.getSection(), null); myAgent.addBehaviour(new PostSwapRequestBehaviour(entry)); action = ACTION_END; break; case ACTION_HAPPY: // At this point student agent submits his schedule /* System.out.println("HAPPY"); for (Iterator ite=schedule.getSectionAssignments().keySet().iterator();ite.hasNext();){ String key=(String)ite.next(); SectionAssignment sectAss = schedule.getSectionAssignment(key); String sectName=sectAss.getSection().getSectionName(); System.out.println(getLocalName()+":"+key+" "+sectName); } */ try { msg = new ACLMessage(ACLMessage.REQUEST); msg.setContentObject(schedule); msg.addReceiver(schedulerAgent); send(msg); } catch (Exception e) { e.printStackTrace(); } action = ACTION_END; myAgent.doDelete(); break; } }
protected void onTick() { listaAgentesComunicacion = paginasAmarillas.buscarServicio("envio-coordenadas", myAgent); listaAgentesDeteccionColisiones = paginasAmarillas.buscarServicio("deteccion-colisiones", myAgent); // Estamos a la escucha para recibir algun mansaje procedente del Agente Servidor ACLMessage mensajeEntrante = myAgent.receive(); if (mensajeEntrante != null) { if (mensajeEntrante.getPerformative() == ACLMessage.REQUEST) { // Recibimos un mensaje InfoCollision try { InfoCollision info = (InfoCollision) mensajeEntrante.getContentObject(); // Dentro del try está la parte relativa a la toma de decisiones: String decision; if (this.decisionAnterior.equals("perseguir")) decision = DecisionMaker.tomaDeDecisionesGato( info.getTipoAgente(), info.getOrientacion(), info.getClaridadPercepcion(), info.getDistancia(), this.decisionAnterior, 0.3, 0.1, 0.1, 0.1, 0.4); else decision = DecisionMaker.tomaDeDecisionesGato( info.getTipoAgente(), info.getOrientacion(), info.getClaridadPercepcion(), info.getDistancia(), this.decisionAnterior, 0.5, 0.1, 0.1, 0.1, 0.2); logger.info("--> DECISION TOMADA POR EL GATO: " + decision); String contenido; if (decision.equals("perseguir")) { contenido = generaCoordenadasPerseguir(info); comportamientoTrayectorias = null; } else if (decision.equals("esquivar")) { contenido = generaCoordenadasEsquivar(info); comportamientoTrayectorias = null; } else { // "no hacer nada" switch (tipoTrayectoria) { case PathsBehaviour.OCTOGONAL: camino.setOrientacion(Orientation.E); break; case PathsBehaviour.DIAMANTE: camino.setOrientacion(Orientation.NE); break; case PathsBehaviour.CUADRADA: camino.setOrientacion(Orientation.E); break; case PathsBehaviour.TRIANGULAR: camino.setOrientacion(Orientation.O); break; case PathsBehaviour.ZIGZAG: camino.setOrientacion(Orientation.NO); break; case PathsBehaviour.BARRIDO: camino.setOrientacion(Orientation.E); break; // nuevo } contenido = generaCoordenadas(); } for (int i = 0; i < listaAgentesComunicacion.length && listaAgentesDeteccionColisiones.length > 0; i++) { if (activado) nuevoMensaje(listaAgentesComunicacion[i].getLocalName(), contenido); mensajeInfoAgente(listaAgentesDeteccionColisiones[i].getLocalName()); logger.info( "GATO EN " + camino.getPunto().getX() + " " + camino.getPunto().getY() + " " + camino.getPunto().getZ() + " " + camino.getOrientacion()); } // Almacenamos la decisión para tenerla en cuenta la vez siguiente: es un criterio. this.decisionAnterior = decision; } catch (UnreadableException e) { e.printStackTrace(); } } else { logger.info("Mensaje entrante del gato: " + mensajeEntrante.getContent()); String contenidoMensaje = mensajeEntrante.getContent(); if (contenidoMensaje.contains("morir")) { // Matamos a los agentes myAgent.doDelete(); } else if (contenidoMensaje.contains( "comunicacion-lista")) { // Permitimos que empiecen a generar coordenadas activado = true; } else if (contenidoMensaje.contains( "genera")) { // Permitimos que sigan generando coordenadas String contenido = generaCoordenadas(); for (int i = 0; i < listaAgentesComunicacion.length && listaAgentesDeteccionColisiones.length > 0; i++) { if (activado) nuevoMensaje(listaAgentesComunicacion[i].getLocalName(), contenido); mensajeInfoAgente(listaAgentesDeteccionColisiones[i].getLocalName()); logger.info( "GATO EN " + camino.getPunto().getX() + " " + camino.getPunto().getY() + " " + camino.getPunto().getZ() + " " + camino.getOrientacion()); } } } } else { // Permanecemos a la espera de que llegue un mensaje block(); } }
@Override public void action() { // We have to use a timeout to allow the WakerBehaviour to take place final ACLMessage msg = this.myAgent.blockingReceive(100); if (msg == null) { return; } final AID sender = msg.getSender(); Message message = null; try { message = (Message) msg.getContentObject(); } catch (final UnreadableException e) { System.err.println("[" + this.myAgent.getAID() + "] Error receiving message from " + sender); e.printStackTrace(System.err); return; } System.err.println( "INFO: [" + this.myAgent.getAID() + "] ReceiveMessage (" + message.getType() + ")"); switch (message.getType()) { case FIRST_ASSIGNATION_REQUEST: // TODO: This should maybe be an INFORM message, with reply this.teacher.sendMessage( sender, new FirstAssignationMessage(this.firstAssignation(sender))); this.alumnCount += 1; assert this.alumnCount <= TeacherBehaviour.EXPECTED_ALUMN_COUNT; if (TeacherBehaviour.EXPECTED_ALUMN_COUNT == this.alumnCount) { this.teacher.sendMessageToType("alumn", new InitMessage()); } return; case TEACHER_GROUP_CHANGE_REQUEST: final TeacherGroupChangeRequestMessage requestMessage = (TeacherGroupChangeRequestMessage) message; assert requestMessage.fromAlumn.equals(sender); // Ensure those alumns haven't been changed previously if (this.groups.get(requestMessage.fromAlumn) == requestMessage.fromGroup && this.groups.get(requestMessage.toAlumn) == requestMessage.toGroup) { this.groups.put(requestMessage.fromAlumn, requestMessage.toGroup); this.groups.put(requestMessage.toAlumn, requestMessage.fromGroup); this.teacher.sendMessageToType( "alumn", new TeacherGroupChangeMessage( requestMessage.fromAlumn, requestMessage.toAlumn, requestMessage.fromGroup, requestMessage.toGroup)); } else { this.teacher.sendMessage( requestMessage.fromAlumn, new TeacherGroupChangeRequestDenegationMessage()); } return; default: System.err.println( "ERROR: Unexpected message of type " + message.getType() + " received in TeacherBehaviour. Sender: " + sender + "; Receiver: " + this.teacher.getAID()); return; } }