Esempio n. 1
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. 2
0
  /**
   * 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;
  }
Esempio n. 3
0
  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());
    }
  }
  @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);
      }
    }
  }
 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;
 }
  /**
   * 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;
 }
Esempio n. 8
0
  /**
   * 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();
    }
  }
Esempio n. 9
0
 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;
  }
Esempio n. 11
0
 /** 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);
  }
Esempio n. 13
0
    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();
      }
    }
Esempio n. 14
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. 15
0
    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;
      }
    }
Esempio n. 16
0
    /** 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();
      }
    }
  @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();
    }
  }
Esempio n. 18
0
  /**
   * 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);
  }