/**
     * Overrides the TickerBehaviour, defining how to update the location on the df (registration to
     * DF has already been performed during agent setup). Three properties are defined for storing
     * latitude/longitude/altitude. Only latitude and longitude are used, though.
     */
    protected void onTick() {

      try {
        MsnAgent agent = (MsnAgent) myAgent;
        DFAgentDescription description = agent.getAgentDescription();

        ServiceDescription serviceDescription =
            (ServiceDescription) description.getAllServices().next();
        serviceDescription.clearAllProperties();

        // retrieve
        ContactLocation curMyLoc = ContactManager.getInstance().getMyContactLocation();
        if (!curMyLoc.equals(myContactLocation)) {

          Property p = new Property(PROPERTY_NAME_LOCATION_LAT, new Double(curMyLoc.getLatitude()));
          serviceDescription.addProperties(p);
          p = new Property(PROPERTY_NAME_LOCATION_LONG, new Double(curMyLoc.getLongitude()));
          serviceDescription.addProperties(p);
          p = new Property(PROPERTY_NAME_LOCATION_ALT, new Double(curMyLoc.getAltitude()));
          serviceDescription.addProperties(p);
          DFService.modify(myAgent, description);
          myContactLocation = curMyLoc;
        }

      } catch (FIPAException fe) {
        myLogger.log(Logger.SEVERE, "Error in updating DF", fe);
      } catch (Exception e) {
        myLogger.log(
            Logger.SEVERE,
            "***  Uncaught Exception for agent " + myAgent.getLocalName() + "  ***",
            e);
      }
    }
Esempio n. 2
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. 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());
    }
  }
Esempio n. 4
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;
  }
  @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);
      }
    }
  }
Esempio n. 6
0
  /** entry point of agent */
  protected void setup() {
    claimDropdownID = false;
    holdingItem = new Point(0, 0);
    // nextDestination.add(IDLE);
    movementVerified = false;
    awaitingRelease = false;
    // uiMap = new Map();
    updateGuiAgents(); // Robot agent wont start without an active GuiAgent
    if (guiAgents.length == 0) {
      /*System.out.println("No gui agent found, robot agent is terminating");*/
      doDelete();
    }

    // RobotAgent wont start without coordination arguments (looks like: 1,1
    // ) on startup
    Object[] args = getArguments();
    if (args != null && args.length > 0) {
      location = new Point(Integer.parseInt((String) args[0]), Integer.parseInt((String) args[1]));
      /*System.out.println(getAID().getName() + " is positioned at "
      + location.x + "," + location.y);*/
    } else {
      // Make the agent terminate
      /*System.out.println("No position defined, closing down");*/
      doDelete();
    }

    //		System.out.println("Hallo! Robot-agent " + getAID().getName()
    //				+ " is ready.");

    // register at yellow pages serivce
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());
    ServiceDescription sd = new ServiceDescription();
    sd.setType("Warehouse-RobotAgent");
    sd.setName("Warehouse-RobotAutomation");
    dfd.addServices(sd);
    try {
      DFService.register(this, dfd);

    } catch (FIPAException e) {
      //			System.out.println("catch");
      e.printStackTrace();
    }

    addBehaviour(new OfferRequestsServer()); // bid on current requests
    addBehaviour(new AcceptRequestServer()); // accept an incomming request
    addBehaviour(new MapReceiver()); // awaits a map message from guiAgent
    addBehaviour(new MapRequest()); // one shot behaviour to load the map
    addBehaviour(new MovementBehaviour(this, 500)); // every second the
    // robot is allowed to
    // move a spot
    addBehaviour(new HopReply()); // Behaviour which awaits incomming
    // accept/decline after a hop claim
    // request
    addBehaviour(new ArrivalReply()); // Behaviour which awaits incomming go
    // after arriving at a storage agent

    this.calculateNextHopSetup();
  }
Esempio n. 7
0
 /** Subscribing to the first finding service */
 protected void subscribe() {
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Building");
   sd.setName("Building");
   DFAgentDescription template = new DFAgentDescription();
   template.addServices(sd);
   addBehaviour(new NRJStationRegisterBehaviour(template, this, 1000));
 }
  private AID findClientAgent(String agent) {
    DFAgentDescription[] result = Utils.agentSearch(myAgent, Constants.CLIENT_AGENT);

    for (DFAgentDescription df : result) {
      if (df.getName().getName().equals(agent)) {
        return df.getName();
      }
    }
    return null;
  }
 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;
 }
Esempio n. 10
0
 private void register() {
   DFAgentDescription dfd = new DFAgentDescription();
   dfd.setName(getAID());
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Publish-chessboard");
   sd.setName("Chessboard");
   dfd.addServices(sd);
   try {
     DFService.register(this, dfd);
   } catch (FIPAException e) {
     log.severe(e.getMessage());
   }
 }
 /** Registers a WSIG into a DF */
 private void registerIntoDF() {
   DFAgentDescription dfad = new DFAgentDescription();
   dfad.setName(this.getAID());
   dfad.addLanguages(FIPANames.ContentLanguage.FIPA_SL);
   dfad.addProtocols(FIPANames.InteractionProtocol.FIPA_REQUEST);
   ServiceDescription sd = new ServiceDescription();
   sd.setType(AGENT_TYPE);
   sd.setName(getLocalName());
   dfad.addServices(sd);
   try {
     DFService.register(this, dfad);
   } catch (Exception e) {
     log.error("Agent " + getLocalName() + " - Error during DF registration", e);
   }
 }
  /**
   * Overrides the Behaviour.action() method. This method is executed by the agent thread. It
   * basically defines two sub behaviours, which are in charge of periodically updating the DF and
   * receiving DF notifications.
   */
  public void action() {
    try {
      // first thing to do is to register on the df and save current location if any
      DFAgentDescription myDescription = new DFAgentDescription();
      // fill a msn service description
      ServiceDescription msnServiceDescription = new ServiceDescription();
      msnServiceDescription.setName(MsnAgent.msnDescName);
      msnServiceDescription.setType(MsnAgent.msnDescType);
      myDescription.addServices(msnServiceDescription);

      ContactManager.getInstance().resetModifications();

      DFAgentDescription[] onlineContacts = DFService.search(myAgent, myDescription);

      updateContactList(onlineContacts);

      MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT);

      Map<String, Contact> cMap = ContactManager.getInstance().getAllContacts();
      Map<String, ContactLocation> cLocMap = ContactManager.getInstance().getAllContactLocations();
      ContactListChanges changes = ContactManager.getInstance().getModifications();

      myLogger.log(
          Logger.FINE,
          "Thread "
              + Thread.currentThread().getId()
              + "After reading local contacts and first df query: "
              + "Adding to VIEW_REFRESH_EVENT this list of changes: "
              + changes.toString());
      event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LISTOFCHANGES, changes);
      event.addParam(MsnEvent.VIEW_REFRESH_CONTACTSMAP, cMap);
      event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LOCATIONMAP, cLocMap);
      MsnEventMgr.getInstance().fireEvent(event);

      DFUpdaterBehaviour updater =
          new DFUpdaterBehaviour(myAgent, msnUpdateTime, myContactLocation);
      MsnAgent agent = (MsnAgent) myAgent;
      DFSubscriptionBehaviour subBh =
          new DFSubscriptionBehaviour(myAgent, agent.getSubscriptionMessage());

      myAgent.addBehaviour(updater);
      myAgent.addBehaviour(subBh);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      myLogger.log(Logger.SEVERE, "Severe error: ", e);
      e.printStackTrace();
    }
  }
 private List<AID> addDevicesRecivers() {
   DFAgentDescription template = new DFAgentDescription();
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Device");
   template.addServices(sd);
   List<AID> aids = new ArrayList<>();
   try {
     DFAgentDescription[] result = DFService.search(myAgent, template);
     for (DFAgentDescription agentd : result) {
       aids.add(agentd.getName());
     }
   } catch (FIPAException fe) {
     fe.printStackTrace();
   }
   return aids;
 }
  private synchronized void deregisterAgent(DFAgentDescription dfad) throws Exception {

    log.info("Start wsigs's deregistration from agent: " + dfad.getName());

    WSIGService wsigService;

    AID agentId = dfad.getName();
    for (WSIGService wsigService1 : wsigStore.getServices(agentId)) {
      wsigService = wsigService1;

      // Deregister service
      deregisterService(wsigService);
    }

    log.info("End wsigs's deregistration from agent: " + dfad.getName());
  }
Esempio n. 15
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. 16
0
  /**
   * Enregistrement des services
   *
   * @param type le type de son agent (TypeAgent)
   */
  protected void registerService(String type) {
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(this.getAID());

    ServiceDescription sd = new ServiceDescription();
    sd.setType(type);
    sd.setName(type);

    dfd.addServices(sd);

    try {
      DFService.register(this, dfd);
    } catch (FIPAException e) {
      System.err.println(
          getLocalName() + " registration with DF unsucceeded. Reason: " + e.getMessage());
      doDelete();
    }
  }
  /**
   * 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. 18
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();
   }
 }
Esempio n. 19
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. 21
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. 22
0
  private Cfp calculateCosts(Cfp cfpContent, AGV agent) {
    HashMap<AID, Integer> mapCost = new HashMap<AID, Integer>();
    // TODO improve cost calculation according products in the agv
    for (DFAgentDescription dfAgent : agent.getAgentListWithService("ProcessProduct")) {

      // check if origin is diferent than the destination to calculate the cost
      if (dfAgent.getName().getName().compareTo(cfpContent.getOrigin().getName()) != 0) {
        cfpContent = cfpContent.clone();
        cfpContent.setType(ObjectType.Agv);
        cfpContent.setAgv(myAgent.getAID());
        mapCost.put(
            dfAgent.getName(),
            (int)
                calculateCost(
                    cfpContent.getOrigin().getName(), dfAgent.getName().getName(), agent));
      }
    }

    cfpContent.setMachineCostMap(mapCost);
    return cfpContent;
  }
  private synchronized void registerAgent(DFAgentDescription dfad) throws Exception {

    log.info("Start wsigs's registration from agent: " + dfad.getName());

    // Loop all services of agent
    ServiceDescription sd;
    WSIGService wsigService;

    AID agentId = dfad.getName();
    Iterator it = dfad.getAllServices();
    while (it.hasNext()) {
      sd = (ServiceDescription) it.next();

      // Create wsdl & wsig service
      wsigService = createWSIGService(agentId, sd);

      // Register new service
      registerService(wsigService);
    }

    log.info("End wsigs's registration from agent: " + dfad.getName());
  }
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();
   }
 }
  private void publishServices() {
    /** ************************************************************** */
    /** ************ Publish the two services to DF **************** */
    /** ************************************************************** */
    ServiceDescription artifactInformation = new ServiceDescription();
    artifactInformation.setType("artifact-lookup");
    artifactInformation.setName("get-artifact-info");
    artifactInformation.addOntologies("get-item-information");
    Property args =
        new Property("args", "Send a Profile and use the ontology: get-item-information");
    artifactInformation.addProperties(args);

    ServiceDescription artifactSearch = new ServiceDescription();
    artifactSearch.setType("artifact-search");
    artifactSearch.setName("search-for-artifacts");
    artifactSearch.addOntologies("request-ids");
    args =
        new Property("args", "Send an ArrayList<Integer> of IDs and use the ontology: request-ids");
    artifactSearch.addProperties(args);

    ServiceDescription buyingArtifacts = new ServiceDescription();
    buyingArtifacts.setName("buying-artifacts");
    buyingArtifacts.setType("buying-artifacts");

    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());
    dfd.addServices(artifactInformation);
    dfd.addServices(artifactSearch);
    dfd.addServices(buyingArtifacts);
    try {
      DFService.register(this, dfd);
      // System.out.println(getName() + ": Successfully registered services.");
    } catch (FIPAException e) {
      e.printStackTrace();
    }
    /** ************************************************************* */
  }
Esempio n. 26
0
  /** Initialization */
  protected void setup() {
    // INitialize the logger
    logger = jade.util.Logger.getMyLogger(this.getClass().getName());
    logger.setLevel(Logger.SEVERE);

    logger.info("Student agent started: " + getLocalName());
    // studentNumber = (String)(String)getArguments()[0];

    /** Register the agent to the directory facilitator */
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());
    ServiceDescription sd = new ServiceDescription();
    sd.setType(getLocalName());
    sd.setName("Student Agent");
    dfd.addServices(sd);
    try {
      DFService.register(this, dfd);
    } catch (FIPAException fe) {
      fe.printStackTrace();
    }

    // Add main student agent behaviour
    addBehaviour(new StudentAgentBehaviour());
  }
  @Override
  public void action() {
    // Receive information update from world
    HashMap<Integer, ConnectionInfo> queryResponses = new HashMap<Integer, ConnectionInfo>();
    boolean worldMsg = false;
    TrafficLightInfoPacket packet = null;
    while (!worldMsg) {
      ACLMessage msg = myAgent.blockingReceive();
      while (msg.getPerformative() != ACLMessage.INFORM_REF) msg = myAgent.blockingReceive();
      try {
        packet = (TrafficLightInfoPacket) msg.getContentObject();
        worldMsg = true;
      } catch (Exception e) {
        try {
          ConnectionInfo conn = (ConnectionInfo) msg.getContentObject();
          queryResponses.put(conn.getRoadId(), conn);
        } catch (Exception e1) {
          e.printStackTrace();
        }
      }
    }

    // Inform all dependent agents
    ArrayList<ConnectionInfo> info = packet.getInfo();
    for (ConnectionInfo conn : info) {
      // Send register inform to world agent
      ACLMessage msg2 = new ACLMessage(ACLMessage.INFORM_REF);
      try {
        msg2.setContentObject(conn);
        msg2.addReceiver(conn.getAgentAID());
        myAgent.send(msg2);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // Receive responses
    boolean receiving = false;
    for (ConnectionInfo conn2 : packet.getInfo()) {
      if (queryResponses.get(conn2.getNextRoadId()) == null) {
        receiving = true;
        break;
      }
    }
    while (receiving) {
      ACLMessage msg3 = myAgent.blockingReceive();
      if (msg3.getPerformative() == ACLMessage.INFORM_REF) {
        try {
          ConnectionInfo conn = (ConnectionInfo) msg3.getContentObject();
          queryResponses.put(conn.getRoadId(), conn);
          receiving = false;
          for (ConnectionInfo conn2 : packet.getInfo()) {
            if (queryResponses.get(conn2.getNextRoadId()) == null) {
              receiving = true;
              break;
            }
          }
        } catch (UnreadableException e) {
          e.printStackTrace();
        }
      }
    }

    int verticalSend = 0;
    int horizontalSend = 0;
    HashMap<Integer, ConnectionInfo> connections = new HashMap<Integer, ConnectionInfo>();
    for (ConnectionInfo conn : packet.getInfo()) {
      int localMin = Math.min(conn.getMaxCarSpeed(), conn.getCarCount());
      connections.put(conn.getNextRoadId(), conn);
      if (conn.getRoadOrientation() == Orientation.UP
          || conn.getRoadOrientation() == Orientation.DOWN) verticalSend += localMin;
      else horizontalSend += localMin;
    }
    for (Entry<Integer, ConnectionInfo> entry : queryResponses.entrySet()) {
      Orientation ori = connections.get(entry.getValue().getRoadId()).getRoadOrientation();
      if (ori == Orientation.UP || ori == Orientation.DOWN)
        verticalSend -= (entry.getValue().getRoadCapacity() - entry.getValue().getCarCount());
      else horizontalSend -= (entry.getValue().getRoadCapacity() - entry.getValue().getCarCount());
    }
    boolean openVertical;
    if (verticalSend < horizontalSend) openVertical = true;
    else openVertical = false;

    // Build response to world
    ++cycleCount;
    boolean stateChanged = true;
    WorldUpdatePacket reply = new WorldUpdatePacket();
    for (ConnectionInfo conn : packet.getInfo()) {
      UpdateInfo uInfo = new UpdateInfo();
      uInfo.setRoadId(conn.getRoadId());
      uInfo.setNextRoadId(conn.getNextRoadId());
      if (cycleCount >= MAX_CYCLES_WITHOUT_CHANGE) {
        uInfo.setCurrentState(!conn.isCurrentState());
      } else if (cycleCount <= MIN_CYCLES_WITHOUT_CHANGE) {
        uInfo.setCurrentState(conn.isCurrentState());
      } else {
        if (openVertical
            && (conn.getRoadOrientation() == Orientation.UP
                || conn.getRoadOrientation() == Orientation.DOWN)) uInfo.setCurrentState(true);
        else if (!openVertical
            && (conn.getRoadOrientation() == Orientation.LEFT
                || conn.getRoadOrientation() == Orientation.RIGHT)) uInfo.setCurrentState(true);
        else uInfo.setCurrentState(false);
      }
      if (uInfo.isCurrentState() == conn.isCurrentState()) stateChanged = false;
      reply.addUpdateInfo(uInfo);
    }
    if (stateChanged) cycleCount = 0;

    // Reply to world
    DFAgentDescription template = new DFAgentDescription();
    ServiceDescription sd1 = new ServiceDescription();
    sd1.setType(Vocabulary.WORLD_AGENT_TYPE);
    template.addServices(sd1);
    DFAgentDescription[] result = {};
    try {
      result = DFService.search(myAgent, template);
      while (result.length <= 0) {
        result = DFService.search(myAgent, template);
      }

      // Clear message queue before responding
      while (myAgent.receive() != null) {}

      // Send register inform to world agent
      ACLMessage replyMsg = new ACLMessage(ACLMessage.INFORM_REF);
      replyMsg.setContentObject(reply);
      replyMsg.addReceiver(result[0].getName());
      myAgent.send(replyMsg);
    } catch (FIPAException | IOException e) {
      e.printStackTrace();
    }
  }
    /**
     * Overrides SubscriptionInitiator.handleInform(), defining what to do each time the DF is
     * modified by a contact Basically it adds/removes/updates contacts from ContactList according
     * to what has happened to DF. It also fires events on the GUI any time a view refresh is
     * needed.
     *
     * @param inform the message from DF containing a list of changes
     */
    protected void handleInform(ACLMessage inform) {

      myLogger.log(
          Logger.FINE,
          "Thread " + Thread.currentThread().getId() + ": Notification received from DF");
      ContactManager.getInstance().resetModifications();

      try {

        DFAgentDescription[] results = DFService.decodeNotification(inform.getContent());

        if (results.length > 0) {

          for (int i = 0; i < results.length; ++i) {
            DFAgentDescription dfd = results[i];
            AID contactAID = dfd.getName();
            // Do something only if the notification deals with an agent different from the current
            // one
            if (!contactAID.equals(myAgent.getAID())) {

              myLogger.log(
                  Logger.INFO,
                  "Thread "
                      + Thread.currentThread().getId()
                      + ":df says that agent "
                      + myAgent.getAID().getLocalName()
                      + " updates or registers");
              Iterator serviceIter = dfd.getAllServices();

              // Registered or updated
              if (serviceIter.hasNext()) {
                ServiceDescription serviceDesc = (ServiceDescription) serviceIter.next();
                Iterator propertyIt = serviceDesc.getAllProperties();
                Location loc = Helper.extractLocation(propertyIt);
                String phoneNum = contactAID.getLocalName();
                ContactManager.getInstance().addOrUpdateOnlineContact(phoneNum, loc);
              } else {
                myLogger.log(
                    Logger.INFO,
                    "Thread "
                        + Thread.currentThread().getId()
                        + ":df says that agent "
                        + myAgent.getAID().getLocalName()
                        + " deregisters");
                String phoneNumber = contactAID.getLocalName();
                Contact c = ContactManager.getInstance().getContact(phoneNumber);
                ContactManager.getInstance().setContactOffline(phoneNumber);
                MsnEvent event =
                    MsnEventMgr.getInstance().createEvent(MsnEvent.CONTACT_DISCONNECT_EVENT);
                event.addParam(MsnEvent.CONTACT_DISCONNECT_PARAM_CONTACTNAME, c.getName());
                MsnEventMgr.getInstance().fireEvent(event);
              }

              MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT);
              ContactListChanges changes = ContactManager.getInstance().getModifications();
              Map<String, Contact> cMap = ContactManager.getInstance().getAllContacts();
              Map<String, ContactLocation> cLocMap =
                  ContactManager.getInstance().getAllContactLocations();

              myLogger.log(
                  Logger.FINE,
                  "Thread "
                      + Thread.currentThread().getId()
                      + ":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);
            }
          }
        }

      } catch (Exception e) {
        myLogger.log(Logger.WARNING, "See printstack for Exception.", e);
        e.printStackTrace();
      }
    }
Esempio n. 29
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);
  }
Esempio n. 30
0
  /*
   * Method that register the room agent to the df and defines requests managment
   */
  protected void registerRoom() {
    // Create the agent description.
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());

    // Create the services description.
    ServiceDescription deviceListSD = new ServiceDescription();
    deviceListSD.setType(HomeAutomation.SERVICE_ROOM_DEVICE_LIST);
    deviceListSD.setName("JADE-room-device-list");

    ServiceDescription deviceRegistrationSD = new ServiceDescription();
    deviceRegistrationSD.setType("room-device-registration");
    deviceRegistrationSD.setType(HomeAutomation.SERVICE_ROOM_DEVICE_REGISTRATION);
    deviceRegistrationSD.setName("JADE-room-device-registration");

    // Add the services description to the agent description.
    // TODO add here other Sevice Descriptions
    dfd.addServices(deviceListSD);
    dfd.addServices(deviceRegistrationSD);

    try {
      // Register the service
      log(
          "Registering '"
              + deviceListSD.getType()
              + "' service named '"
              + deviceListSD.getName()
              + "'"
              + "to the default DF...");

      DFService.register(this, dfd);

      log("Waiting for request...");
    } catch (FIPAException fe) {
      fe.printStackTrace();
    }

    // Add the behaviour serving queries from controller agents.
    MessageTemplate template =
        AchieveREResponder.createMessageTemplate(FIPANames.InteractionProtocol.FIPA_REQUEST);
    addBehaviour(
        new AchieveREResponder(this, template) {

          @Override
          protected ACLMessage handleRequest(ACLMessage request)
              throws NotUnderstoodException, RefuseException {

            log("Handle request with content");
            return new ACLMessage(ACLMessage.AGREE);
          }

          @Override
          protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage response) {

            //						log("Prepare result notification with content: " + request.getContent());
            response.setPerformative(ACLMessage.INFORM);

            Message message = null;
            try {
              message = (Message) request.getContentObject();

            } catch (UnreadableException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            if (message != null) {
              if (message.getService().equals(HomeAutomation.SERVICE_ROOM_DEVICE_LIST)) {
                try {
                  // send device array
                  response.setContentObject(devices);

                } catch (IOException e) {
                  e.printStackTrace();
                }
              } else if (message
                  .getService()
                  .equals(HomeAutomation.SERVICE_ROOM_DEVICE_REGISTRATION)) {
                RegistrationMessage regMessage = (RegistrationMessage) message;

                if (regMessage.getParentId().equals(id)) {
                  AgentMessage agentDesc =
                      new AgentMessage(
                          regMessage.getAid(),
                          regMessage.getParentId(),
                          regMessage.getName(),
                          regMessage.getDescription());
                  devices.add(agentDesc);

                  log(
                      "Device "
                          + request.getSender()
                          + " successfully added to room's device list.");
                } else {
                  // send refuse..
                  log("Wrong room!!");
                  response.setPerformative(ACLMessage.REFUSE);
                }
              }
            }

            return response;
          }
        });
  }