@Override
    public void action() {
      //			System.out.println(getName() + ": state=HandleResponse");
      receivedResponse = false;
      MessageTemplate template_accepted =
          MessageTemplate.MatchPerformative(ACLMessage.ACCEPT_PROPOSAL);
      MessageTemplate template_rejected =
          MessageTemplate.MatchPerformative(ACLMessage.REJECT_PROPOSAL);
      ACLMessage acceptMessage = receive(template_accepted);
      ACLMessage rejectMessage = receive(template_rejected);

      if (acceptMessage != null && acceptMessage.getConversationId().equals(convID)) {
        // System.out.println(getName() + ": My proposal was accepted! Content: " +
        // acceptMessage.getContent());
        accepted = PROPOSAL_ACCEPTED;
        receivedResponse = true;
        artifacts.add(receivedItem);
        money -= receivedItem.getPrice(); // subtract item's cost from bank balance
        System.out.print(getName() + ": ARTIFACT STOCK: ");
        for (int i = 0; i < artifacts.size(); i++)
          System.out.print(
              "\"" + artifacts.get(i).getName() + "\"" + ((i != artifacts.size() - 1) ? ", " : ""));
        System.out.print("\n\n");

      } else if (rejectMessage != null && rejectMessage.getConversationId().equals(convID)) {
        // System.out.println(getName() + ": My proposal was rejected... Content: " +
        // rejectMessage.getContent());
        accepted = PROPOSAL_REJECTED;
        receivedResponse = true;
      } else block();
    }
Esempio n. 2
0
  public void requestSwapAppointments() {
    String conversationId = "request-swap";

    if (patientAgent.highPriorityAppointmentOwner != null) {

      System.out.println(
          patientAgent.getName()
              + " proposing to swap slot "
              + (patientAgent.allocatedAppointment + 1)
              + " with "
              + (patientAgent.swapSlot + 1));
      ACLMessage request = new ACLMessage(ACLMessage.PROPOSE);
      request.addReceiver(patientAgent.highPriorityAppointmentOwner);
      try {
        request.setContentObject(
            new SwapInfo(patientAgent.allocatedAppointment, patientAgent.swapSlot));
      } catch (IOException e) {
        e.printStackTrace();
      }
      request.setSender(patientAgent.getAID());
      request.setConversationId(conversationId);
      request.setReplyWith(conversationId + " " + System.currentTimeMillis());
      patientAgent.send(request);
      reqTemplate =
          MessageTemplate.and(
              MessageTemplate.MatchConversationId(conversationId),
              MessageTemplate.MatchInReplyTo(request.getReplyWith()));
      state = 1;
    }
  }
  /**
   *
   *
   * <h2>Add plans for </h2>
   *
   * Registering customer on blackboard </br> Dispatching generated batch </br> Sending confirmed
   * batch ( after negotiation) </br> Canceling the order </br> Receiving completed batch </br>
   * changing due date of batch </br> handling rejected order from GSA </br>
   *
   * @return Set of plans for this agent
   */
  public static Set<Plan> getPlans() {
    Set<Plan> plans = new HashSet<Plan>();

    plans.add(
        new SimplePlan(
            RegisterAgentToBlackboardGoal.class, RegisterCustomerAgentToBlackboardPlan.class));

    plans.add(new SimplePlan(DispatchBatchGoal.class, DispatchJobPlan.class));
    plans.add(new SimplePlan(SendConfirmedOrderGoal.class, SendConfirmedOrderPlan.class));
    plans.add(new SimplePlan(CancelOrderGoal.class, CancelOrderPlan.class));

    plans.add(
        new SimplePlan(
            MessageTemplate.MatchConversationId(MessageIds.msgOrderCompletion),
            ReceiveCompletedBatchPlan.class));

    plans.add(
        new SimplePlan(
            MessageTemplate.MatchConversationId(MessageIds.msgOrderCancellation),
            ReceiveCancelledBatchPlan.class));

    plans.add(
        new SimplePlan(
            MessageTemplate.MatchConversationId(MessageIds.msgChangeDueDate), ChangeDueDate.class));

    plans.add(
        new SimplePlan(
            MessageTemplate.MatchConversationId(MessageIds.RejectedOrder),
            HandleRejectedOrder.class));

    return plans;
  }
  @Override
  public void action() {
    ACLMessage messageServeur =
        myAgent.receive(
            MessageTemplate.and(
                MessageTemplate.MatchPerformative(ACLMessage.PROPAGATE),
                MessageTemplate.MatchSender(getServerAID())));
    if (messageServeur != null) {
      System.out.println(myAgent.getLocalName() + " reçu -> " + messageServeur.getContent());
      // On déséréalise le message
      ObjectMapper omap = new ObjectMapper();
      try {
        ServerLiaisonMessage msg =
            omap.readValue(messageServeur.getContent(), ServerLiaisonMessage.class);

      } catch (IOException e1) {
        e1.printStackTrace();
      }
      // Ecriture de message
      ACLMessage message =
          createMessageToDevices(messageServeur.getContent(), messageServeur.getConversationId());
      myAgent.send(message);
      System.out.println(myAgent.getLocalName() + " envoyé -> " + message.getContent());
    }
  }
 private MessageTemplate getMessageFilter() {
   Seller mySeller = (Seller) super.myAgent;
   return MessageTemplate.and(
       this.myFSM.getMessageFilter(),
       MessageTemplate.and(
           MessageTemplate.MatchContent(String.valueOf(mySeller.getCurrentPrice())),
           MessageTemplate.MatchPerformative(FishMarketProtocol.Performatives.TO_BID)));
 }
Esempio n. 6
0
 public HandleInform(Agent a, AID provider) {
   super(a);
   this.myAgent = (VendeurAgent) a;
   finished = false;
   mtProvider = MessageTemplate.MatchSender(provider);
   mt = MessageTemplate.and(mtpPerformative, mtProvider);
   // countAttente = 0;
 }
Esempio n. 7
0
 public void action() {
   MessageTemplate mt =
       MessageTemplate.and(
           MessageTemplate.MatchPerformative(ACLMessage.INFORM),
           MessageTemplate.MatchConversationId("map-request"));
   ACLMessage msg = myAgent.receive(mt);
   if (msg != null) { // this agent received a map after his map request
     String response = msg.getContent();
     wantsCleanMap = false;
     createUIGraph(response);
   } else {
     block();
   }
 }
Esempio n. 8
0
    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();
      }
    }
Esempio n. 9
0
    protected void setup() {
      Object[] args = getArguments();
      if (args != null && args.length == 1) {
        myReceiver = new AID((String) args[0], AID.ISLOCALNAME);
      } else {
        System.out.println("Missing receiver name !!!!!");
        doDelete();
        return;
      }
      msg.addReceiver(myReceiver);
      msg.setByteSequenceContent(content);
      myTemplate = MessageTemplate.MatchSender(myReceiver);

      System.out.println(
          "RTT-Sender " + getName() + " ready: my receiver is " + myReceiver.getName());
      notifyReady();

      if (timeInterval > 0) {
        addBehaviour(
            new TickerBehaviour(this, timeInterval) {
              public void onTick() {
                job();
              }
            });
      } else {
        addBehaviour(
            new CyclicBehaviour(this) {
              public void run() {
                job();
              }
            });
      }
    }
Esempio n. 10
0
 public AgentImage removeAgentImage(AID id) {
   AgentImage img = (AgentImage) agentImages.remove(id);
   // If there are messages that were waiting to be delivered to the
   // real agent on the FrontEnd, notify failure to sender
   removePendingMessages(MessageTemplate.MatchReceiver(new AID[] {id}), true);
   return img;
 }
Esempio n. 11
0
  private class ChessBoardBehavior extends CyclicBehaviour {
    private MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.INFORM);

    public void action() {
      final ACLMessage msg = myAgent.receive(mt);
      if (msg != null) {
        log.info("Receive ChessBoard update request: " + msg.getContent());
        String[] parsedMsg = msg.getContent().split(",");
        boolean update = Boolean.valueOf(parsedMsg[0]);
        int row = Integer.valueOf(parsedMsg[1]);
        int col = Integer.valueOf(parsedMsg[2]);
        gui.update(row, col, update);

        if (update) {
          final String nextQueenToStart = "Queen" + (col + 1);
          addBehaviour(
              new WakerBehaviour(myAgent, SLEEP_TIME) {
                protected void onWake() {
                  proposeMove(nextQueenToStart);
                }
              });
        }
      }
    }
  }
Esempio n. 12
0
  public List removePendingMessages(MessageTemplate template) {
    synchronized (pendingCommands) {
      List messages = new ArrayList();
      List commands = new ArrayList();
      Enumeration e = pendingCommands.elements();
      while (e.hasMoreElements()) {
        PostponedCommand pc = (PostponedCommand) e.nextElement();
        Command c = pc.getCommand();
        if (c.getCode() == FrontEndSkel.MESSAGE_IN) {
          ACLMessage msg = (ACLMessage) c.getParamAt(0);
          if (template.match(msg)) {
            Object[] oo = new Object[] {msg, c.getParamAt(1)};
            messages.add(oo);
            commands.add(c);
          }
        }
      }
      // Remove all the commands carrying matching messages
      Iterator it = commands.iterator();
      while (it.hasNext()) {
        pendingCommands.remove(it.next());
      }

      // Return the list of matching messages
      return messages;
    }
  }
Esempio n. 13
0
    public void action() {

      MessageTemplate mt =
          MessageTemplate.and(
              MessageTemplate.MatchPerformative(ACLMessage.INFORM),
              MessageTemplate.MatchConversationId("arrival-inform"));
      ACLMessage msg = myAgent.receive(mt);
      if (msg != null) { // this agent received a YES or NO after his
        // movement request
        String response = msg.getContent();
        if (response.contains("go")) {
          awaitingRelease = false;
        }
      } else {
        awaitingRelease = false;
        block();
      }
    }
  private DetalleProducto getSupermarketInform(UUID conversationId) {

    try {
      ACLMessage msgInform =
          myAgent.blockingReceive(
              MessageTemplate.and(
                  MessageTemplate.MatchConversationId(conversationId.toString()),
                  MessageTemplate.MatchPerformative(ACLMessage.INFORM)));

      DetalleProducto informContent =
          (DetalleProducto) myAgent.getContentManager().extractContent(msgInform);

      System.out.println(String.format("Received INFORM: %s", informContent));

      return informContent;
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }
Esempio n. 15
0
  public void onStart() {
    if (ignoredConversations == null) {
      ignoredConversations = new ConversationList(myAgent);
    }

    // Unless a template is explicitly set, we get messages matching the ontology, the served
    // performatives.
    if (template == null) {
      if (servedPerformatives != null) {
        template =
            MessageTemplate.and(
                MessageTemplate.MatchOntology(onto.getName()),
                new MessageTemplate(
                    new MatchExpression() {
                      public boolean match(ACLMessage msg) {
                        int perf = msg.getPerformative();
                        for (int p : servedPerformatives) {
                          if (p == perf) {
                            return true;
                          }
                        }
                        return false;
                      }
                    }));
      } else {
        // No performative specified --> Match all
        template = MessageTemplate.MatchOntology(onto.getName());
      }
    }
    // Whatever template is used we avoid intercepting messages belonging to external conversations
    template = MessageTemplate.and(template, ignoredConversations.getMessageTemplate());

    // Register Ontology and Language
    ContentManager cm = myAgent.getContentManager();
    if (cm.lookupOntology(onto.getName()) == null) {
      cm.registerOntology(onto);
    }
    this.codec = (codec != null ? codec : new SLCodec());
    if (cm.lookupLanguage(codec.getName()) == null) {
      cm.registerLanguage(codec);
    }
  }
  @Override
  public void action() {

    MessageTemplate messageTemplate = MessageTemplate.MatchConversationId(CONVID_ACL_MESSAGE);
    ACLMessage messageRecu = myAgent.receive(messageTemplate);

    if (messageRecu != null) {
      // Si le problème n'est pas chargé, refuser
      if (((AgentGestionPopulation) myAgent).getMonProbleme() == null) {
        ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
        gererMessage(refuse, messageRecu, "problem is not loaded");
      }
      // Si l'acte est de type REQUEST, analyser le message
      if (messageRecu.getPerformative() == ACLMessage.REQUEST) {
        // Si le language est correct, traiter la demande de génération
        if (messageRecu.getLanguage() != null
            && messageRecu.getLanguage().equals(LANGUAGE_ACL_MESSAGE)) {
          String content = messageRecu.getContent();
          // Si le contenu est conforme (nb d'individus), les générer
          if (content != null) {
            try {
              int nbIndividu = Integer.parseInt(content); // throw NumberFormatException

              ACLMessage agreeMessage = new ACLMessage(ACLMessage.AGREE);
              gererMessage(agreeMessage, messageRecu, "");

              ProblemeCARP p = ((AgentGestionPopulation) myAgent).getMonProbleme();
              ((AgentGestionPopulation) myAgent)
                  .getPopulationGlobale()
                  .genererIndividus(nbIndividu, p);

              ACLMessage informMessage = new ACLMessage(ACLMessage.INFORM);
              gererMessage(informMessage, messageRecu, "done");
            } catch (NumberFormatException nfException) {
              ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
              gererMessage(refuse, messageRecu, "invalid arguments");
            }

          } else {
            ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
            gererMessage(refuse, messageRecu, "invalid arguments");
          }
        } else {
          ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
          gererMessage(refuse, messageRecu, "invalid ACL language");
        }
      } else {
        ACLMessage notUnderstoodMessage = new ACLMessage(ACLMessage.NOT_UNDERSTOOD);
        gererMessage(notUnderstoodMessage, messageRecu, "AGPop only serves request");
      }
    } else block();
  }
Esempio n. 17
0
 public void onStart() {
   // Subscribe as a chat participant to the ChatManager agent
   ACLMessage subscription = new ACLMessage(ACLMessage.SUBSCRIBE);
   subscription.setLanguage(codec.getName());
   subscription.setOntology(onto.getName());
   String convId = "C-" + myAgent.getLocalName();
   subscription.setConversationId(convId);
   subscription.addReceiver(new AID(CHAT_MANAGER_NAME, AID.ISLOCALNAME));
   myAgent.send(subscription);
   // Initialize the template used to receive notifications
   // from the ChatManagerAgent
   template = MessageTemplate.MatchConversationId(convId);
 }
 @Override
 public void action() {
   //			System.out.println(getName() + ": state=Waiting...");
   newAuctionStarted = false;
   MessageTemplate template = MessageTemplate.MatchContent("inform-start-of-auction");
   ACLMessage message = receive(template);
   if (message != null) {
     marketAgent = message.getSender();
     newAuctionStarted = true;
     convID = message.getConversationId();
     // System.out.println(getName() + ": Received Auction start message!");
   } else block();
 }
Esempio n. 19
0
  @Override
  public void action() {
    MessageTemplate template =
        MessageTemplate.and(
            MessageTemplate.MatchPerformative(ACLMessage.REQUEST),
            MessageTemplate.MatchConversationId("1"));
    ACLMessage message = myAgent.receive(template);

    if (message != null) {
      try {
        RequestCellsMessage requestMessage =
            mapper.readValue(message.getContent(), RequestCellsMessage.class);
        List<Cellule> cellules =
            EnvironnementAgent.sudoku.getCellulesForRank(requestMessage.getRank());
        CellsMessage cellsMessage = new CellsMessage(cellules, requestMessage.getRank());
        StringWriter stringWriter = new StringWriter();
        try {
          mapper.writeValue(stringWriter, cellsMessage);
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        String messageString = stringWriter.toString();
        if (messageString != null) {
          ACLMessage response = new ACLMessage(ACLMessage.INFORM);
          response.setContent(messageString);
          response.setConversationId("1");
          response.addReceiver(new AID("AgentSimulation", AID.ISLOCALNAME));
          myAgent.send(response);
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    } else {
      block();
    }
  }
    @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();
    }
  @Override
  public void action() {

    // message templte for dutch auction
    MessageTemplate mt =
        MessageTemplate.and(
            MessageTemplate.MatchPerformative(ACLMessage.INFORM),
            MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_DUTCH_AUCTION));

    msg = myAgent.receive(mt);

    if (msg != null) {
      if (msg.getPerformative() == ACLMessage.INFORM) {
        if (msg.getOntology().equals("AUCTION")) {
          if (msg.getContent().startsWith("AUCTION")) {
            System.out.println(myAgent.getLocalName() + ": auction has started");
            // Auction with 100 as this agents highest buying price
            int price = 40000 + rand.nextInt(15000);
            myAgent.addBehaviour(new NewAuctionBehaviour(Integer.toString(price)));
          } else myAgent.putBack(msg);
        }
      }
    }
  }
Esempio n. 22
0
    public void action() { // listen to incomming CFP from storageAgents

      MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
      ACLMessage msg = myAgent.receive(mt);

      /*System.out.println("REQUEST RECEIVED");
      System.out.println(msg);*/
      if (msg != null) { // only respond to CFP messages
        // CFP Message received. Process it
        // System.out.println("Got request");
        String requestedLocation = msg.getContent();
        ACLMessage reply = msg.createReply(); // add the sender as
        // recipient
        Integer x =
            Integer.parseInt(
                requestedLocation.substring(
                    0, requestedLocation.lastIndexOf(','))); // parse the x of
        // product
        Integer y =
            Integer.parseInt(
                requestedLocation.substring(
                    requestedLocation.lastIndexOf(',') + 1,
                    requestedLocation.length())); // parse the y of product
        Integer price = calculatePathCost(new Point(x, y));
        if (holdingItem.x == x && holdingItem.y == y) { // robot is
          // carrying the
          // requested
          // item
          price = 1;
        }
        if (price != null) {
          reply.setPerformative(ACLMessage.PROPOSE);
          reply.setContent(String.valueOf(price.intValue()));
          // System.out.println(getAID().getName() + ": My cost is " +
          // price + ". To get to location: " +x + ","+y);//debugging
          // purpose
        } else {
          reply.setPerformative(ACLMessage.REFUSE);
          reply.setContent("Pathplanning error");
        }
        myAgent.send(reply);
      } else {
        block();
      }
    }
Esempio n. 23
0
  /**
   * Inner class ChatListener. This behaviour registers as a chat participant and keeps the list of
   * participants up to date by managing the information received from the ChatManager agent.
   */
  class ChatListener extends CyclicBehaviour {
    private MessageTemplate template = MessageTemplate.MatchConversationId(CHAT_ID);

    ChatListener(Agent a) {
      super(a);
    }

    public void action() {
      ACLMessage msg = myAgent.receive(template);
      if (msg != null) {
        if (msg.getPerformative() == ACLMessage.INFORM) {
          myGui.notifySpoken(msg.getSender().getLocalName(), msg.getContent());
        } else {
          handleUnexpected(msg);
        }
      } else {
        block();
      }
    }
  } // END of inner class ChatListener
Esempio n. 24
0
 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();
   }
 }
Esempio n. 25
0
public class ResponderBehaviour extends SimpleBehaviour {

  private static final MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST);

  public ResponderBehaviour(Agent agent) {
    super(agent);
  }

  public void action() {
    ACLMessage aclMessage = myAgent.receive(mt);

    if (aclMessage != null) {
      System.out.println(
          myAgent.getLocalName() + ": I receive message.\n" + aclMessage.getContent());
    } else {
      this.block();
    }
  }

  public boolean done() {
    return false;
  }
}
Esempio n. 26
0
  /*
   * 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;
  }
 public MessageTemplate getMessageFilter() {
   return MessageTemplate.and(
       MessageTemplate.MatchTopic(MarketFSMBehaviourAuctionProgress.MESSAGE_TOPIC),
       MessageTemplate.MatchConversationId(this.conversationId));
 }
Esempio n. 28
0
 public ConnRecvMsg(Connector a) {
   super();
   this.myConnector = a;
   log = Logger.getMyLogger(this.getClass().getName());
   mt = MessageTemplate.MatchConversationId(Constants.NULL_CID);
 }
Esempio n. 29
0
    public void action() {
      MessageTemplate mt =
          MessageTemplate.and(
              MessageTemplate.MatchPerformative(ACLMessage.INFORM),
              MessageTemplate.MatchConversationId("hop-request"));
      ACLMessage msg = myAgent.receive(mt);
      if (msg != null) { // this agent received a YES or NO after his
        // movement request
        String response = msg.getContent();
        // System.out.println("Response to my request: " + response);
        if (response.contains("yes")) {
          if (lastClaimRejected) {
            uiMap = null;
            /*ACLMessage mapReq = new ACLMessage(ACLMessage.QUERY_IF);
            mapReq.addReceiver(guiAgents[0]);
            mapReq.setContent("Give me map");
            mapReq.setConversationId("map-request");
            myAgent.send(mapReq);*/
            addBehaviour(new MapUpdateRequest());
            movementVerified = true;
            // lastClaimRejected = false;
            mapUpdatedAfterSuccesfullRequest = true;

          } else {
            /*for (int j = 0; j < occupiedPoints.size(); j++) {// after a
            													// hop
            													// request
            													// is
            													// accepted
            													// clear
            													// the
            													// list
            													// with
            													// occupied
            													// points
            	occupiedPoints.remove(0);

            }*/
            movementVerified = true;
            lastClaimRejected = false;
          }
        } else {
          // request new map
          // System.out.println("Cant walk here " + this.myAgent.getAID());

          uiMap = null;
          /*ACLMessage mapReq = new ACLMessage(ACLMessage.QUERY_IF);
          mapReq.addReceiver(guiAgents[0]);
          mapReq.setContent("Give me map");
          mapReq.setConversationId("map-request");
          myAgent.send(mapReq);*/
          addBehaviour(new MapUpdateRequest());

          // boolean lastClaimeRejected = true;
          lastClaimRejected = true;
          movementVerified = false;
          // moveMentQueue.clear();

          /*
           * for(int i = 0;i<moveMentQueue.size();i++) {
           * occupiedPoints.add(moveMentQueue.get(i)); }
           */
          // calculateNextHop();
        }
      } else {
        block();
      }
    }
Esempio n. 30
0
    public void action() { // confirm that this agent will pick up the item
      MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.ACCEPT_PROPOSAL);
      ACLMessage msg = myAgent.receive(mt);
      if (msg != null) { // this agent is chosen to pick up the item
        // ACCEPT_PROPOSAL Message received. Process it
        String requestedLocation = msg.getContent();

        String[] locs = requestedLocation.split(":");

        String[] locItem = locs[0].split(",");
        Integer itemX = Integer.parseInt(locItem[0]);
        Integer itemY = Integer.parseInt(locItem[1]);

        String[] locStor = locs[1].split(",");
        Integer storageAgentX = Integer.parseInt(locStor[0]);
        Integer storageAgentY = Integer.parseInt(locStor[1]);

        /*Integer itemX = Integer.parseInt(requestedLocation.substring(0,
        		requestedLocation.indexOf(',', 1)));
        Integer itemY = Integer.parseInt(requestedLocation.substring(
        		requestedLocation.indexOf(',', 1) + 1,
        		requestedLocation.indexOf(':', 1)));
        Integer storageAgentX = Integer.parseInt(requestedLocation
        		.substring(requestedLocation.indexOf(':', 1) + 1,
        				requestedLocation.indexOf(',', 2)));
        Integer storageAgentY = Integer.parseInt(requestedLocation
        		.substring(requestedLocation.indexOf(',', 2) + 1,
        				requestedLocation.length()));*/

        ACLMessage reply = msg.createReply();

        reply.setPerformative(ACLMessage.INFORM);
        /*System.out.println(getAID().getName()
        + " will pick up the item at " + itemX + "," + itemY
        + " and bring it to storage agent: " + (storageAgentX)
        + "," + storageAgentY);*/
        myAgent.send(reply);

        boolean isAlreadyGoingThere = false;
        for (int i = 0; i < travelPoints.size(); i++) {
          if (travelPoints.get(i).x == itemX && travelPoints.get(i).y == itemY) {
            isAlreadyGoingThere = true;
          }
        }

        if ((holdingItem.x == itemX && holdingItem.y == itemY)) { // robot
          // is
          // carrying
          // the
          // requested
          // item
          if (nextDestination.get(0) == ITEMDROPDOWN) // stop dropdown
          // go deliver
          // the item
          {
            travelPoints.remove(0);
            nextDestination.remove(0);
            travelPoints.add(0, new Point(storageAgentX - 11, storageAgentY));
            travelPoints.add(1, new Point(storageAgentX - 1, storageAgentY));
            travelPoints.add(2, new Point(storageAgentX - 1, storageAgentY - 1));
            travelPoints.add(3, new Point(storageAgentX - 11, storageAgentY - 1));
            travelPoints.add(4, new Point(itemX, itemY));
            nextDestination.add(0, STORAGEAGENT);
            nextDestination.add(1, STORAGEAGENT);
            nextDestination.add(2, ITEMDROPDOWN);
            nextDestination.add(3, ITEMDROPDOWN);
            nextDestination.add(4, ITEMDROPDOWN);

          } else if (nextDestination.get(0) == STORAGEAGENT) {
            System.out.print(travelPoints.size());
            travelPoints.remove(4);
            nextDestination.remove(4);
            travelPoints.add(4, new Point(storageAgentX - 11, storageAgentY));
            travelPoints.add(5, new Point(storageAgentX - 1, storageAgentY));
            travelPoints.add(6, new Point(storageAgentX - 1, storageAgentY - 1));
            travelPoints.add(7, new Point(storageAgentX - 11, storageAgentY - 1));
            travelPoints.add(8, new Point(itemX, itemY));
            nextDestination.add(4, STORAGEAGENT);
            nextDestination.add(5, STORAGEAGENT);
            nextDestination.add(6, ITEMDROPDOWN);
            nextDestination.add(7, ITEMDROPDOWN);
            nextDestination.add(8, ITEMDROPDOWN);
          } else if (nextDestination.get(0) == ITEMPICKUP) {
            // at some unknown time, the robot agent has already planned to pick up the item
            travelPoints.remove(4);
            nextDestination.remove(4);
            travelPoints.add(4, new Point(storageAgentX - 11, storageAgentY));
            travelPoints.add(5, new Point(storageAgentX - 1, storageAgentY));
            travelPoints.add(6, new Point(storageAgentX - 1, storageAgentY - 1));
            travelPoints.add(7, new Point(storageAgentX - 11, storageAgentY - 1));
            travelPoints.add(8, new Point(itemX, itemY));
            nextDestination.add(4, STORAGEAGENT);
            nextDestination.add(5, STORAGEAGENT);
            nextDestination.add(6, ITEMDROPDOWN);
            nextDestination.add(7, ITEMDROPDOWN);
            nextDestination.add(8, ITEMDROPDOWN);
          }
        } else if (isAlreadyGoingThere) {
          boolean isInsert = false;
          for (int i = 0; i < travelPoints.size(); i++) {
            if (isInsert == false) {
              if (travelPoints.get(i).x == itemX && travelPoints.get(i).y == itemY) {
                isInsert = true;
                // travelPoints.remove(4);
                travelPoints.add(i + 5, new Point(storageAgentX - 11, storageAgentY));
                nextDestination.add(i + 5, STORAGEAGENT);
                travelPoints.add(i + 6, new Point(storageAgentX - 1, storageAgentY));
                nextDestination.add(i + 6, STORAGEAGENT);
                travelPoints.add(i + 7, new Point(storageAgentX - 1, storageAgentY - 1));
                nextDestination.add(i + 7, ITEMDROPDOWN);
                travelPoints.add(i + 8, new Point(storageAgentX - 11, storageAgentY - 1));
                nextDestination.add(i + 8, ITEMDROPDOWN);
              }
            }
          }

        } else {
          travelPoints.add(new Point(itemX, itemY));
          travelPoints.add(new Point(storageAgentX - 11, storageAgentY));
          travelPoints.add(new Point(storageAgentX - 1, storageAgentY));
          travelPoints.add(new Point(storageAgentX - 1, storageAgentY - 1));
          travelPoints.add(new Point(storageAgentX - 11, storageAgentY - 1));
          travelPoints.add(new Point(itemX, itemY));
          nextDestination.add(ITEMPICKUP);
          nextDestination.add(STORAGEAGENT);
          nextDestination.add(STORAGEAGENT);
          nextDestination.add(ITEMDROPDOWN);
          nextDestination.add(ITEMDROPDOWN);
          nextDestination.add(ITEMDROPDOWN);
          // nextDestination.add(ITEMDROPDOWN);
        }
      } else {
        block();
      }
    }