Ejemplo n.º 1
0
  public static void main(String args[]) throws Exception {
    IAFProperties.setGraphicsOn(false);

    new Thread() {
      public void run() {
        String[] args1 = new String[4];
        args1[0] = "-port";
        args1[1] = "60000";
        args1[2] = "-file-dir";
        args1[3] = "jade/";
        jade.Boot.main(args1);
      }
    }.start();

    // Get a hold on JADE runtime
    jade.core.Runtime rt = jade.core.Runtime.instance();

    // Exit the JVM when there are no more containers around
    rt.setCloseVM(true);

    // Create a default profile
    Profile p = new ProfileImpl();
    p.setParameter("preload", "a*");
    p.setParameter(Profile.MAIN_PORT, "60000");
    p.setParameter(Profile.FILE_DIR, "jade/");

    // Waits for JADE to start
    boolean notConnected = true;

    while (notConnected) {
      try {
        Socket s = new Socket("localhost", Integer.parseInt("60000"));
        notConnected = false;
      } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {

        System.err.println("Error: " + e.getMessage());
        System.err.println("Reconnecting in one second");
        try {
          Thread.currentThread().sleep(1000);
        } catch (InterruptedException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }
      }
    }

    // Create a new non-main container, connecting to the default
    // main container (i.e. on this host, port 1099)
    final jade.wrapper.AgentContainer ac = rt.createAgentContainer(p);

    {
    }
    MainInteractionManager.getInstance().setTitle("node ");
  }
Ejemplo n.º 2
0
  /**
   * The intialization, first, starts the GUI components that will show internal agent information
   * to the user. Later on, it starts the locks manager which is responsible of preventing some
   * information to be removed before transmited to other agents. Following, the agent is registered
   * into JADE yellow pages service with the descriptors extracted from method getDescription. Next,
   * an agent model diagram is created to show the mental state of the agent. It also register
   * action listener to react accordingly to user actions on the diagram. Next, it uses the transfer
   * object utility functions to assert information passed to the agent at construction time. Some
   * operations cannot be performed until the agent is fully connected to JADE. For those
   * operations, they require data that can only be passed in the constructor of the agent. To make
   * these data available in the setup method, we use the method setEnabledO2ACommunication and
   * getO2AObject. After these initializations, the agent is ready to initialize its internal
   * behaviors to handle incoming messages. For more details, look at the comments in the method
   * body.
   */
  public void setup() {
    try {
      super.setup();
      if (IAFProperties.getGraphicsOn()) {
        this.graphics = new AgentGraphics(this.getName());
      }

      this.lman = new LocksManager(this.getAID().getLocalName(), cl);

      /**
       * Registers the agent in the yellow pages services. It uses the getDescription to obtain a
       * list of services the agent can provide
       */
      DFAgentDescription[] roles = this.getDescription();
      for (int k = 0; k < roles.length; k++) {
        try {
          synchronized (synRegister) {
            // System.err.println("iniciando registro");
            jade.domain.DFService.register(this, roles[k]);
            // System.err.println("registrado");
          }

        } catch (FIPAException fe) {
          if (!(fe.getMessage().toLowerCase().indexOf("already") >= 0)) {
            System.out.println(
                fe.getACLMessage().getPerformative(fe.getACLMessage().getPerformative()));
          } else {
            try {
              synchronized (synRegister) {
                //	System.err.println("iniciando registro 2");
                jade.domain.DFService.register(this, roles[k]);
                //	System.err.println("registrado 2");
              }
            } catch (FIPAException fe1) {
              // No more exception should be produced
            }
          }
        }
      }

      /** Creates the GUI for the Mental State Manager */
      AgentModelPanelIAF amm = null;
      if (IAFProperties.getGraphicsOn()) {
        ids = IDEState.emptyIDEState();
        amm =
            new AgentModelPanelIAF(
                new ingenias.editor.entities.AgentModelDataEntity("1"), "1", new Model(ids));
        amm.setMarqueeHandler(new AgentModelMarqueeHandlerIAF(amm));
      }
      /**
       * Initializes the Mental State Manager and the Mental State Processor. The mental state
       * processor is associated to the GUI of the agents.
       */
      if (IAFProperties.getGraphicsOn())
        this.msm = new MentalStateManager(ids, amm, this.getAID().getLocalName());
      else this.msm = new MentalStateManager(ids, this.getAID().getLocalName());
      //	this.addBehaviour(this.msm.getConvTracker());
      if (IAFProperties.getGraphicsOn())
        this.graphics.setMentalStatePanel(this.getLocalName(), amm);
      if (IAFProperties.getGraphicsOn())
        this.msp = new ingenias.jade.MentalStateProcessor(msm, this, this.getGraphics());
      else this.msp = new ingenias.jade.MentalStateProcessor(msm, this);
      this.lman.register(msp); // To get notifications of locks removal/addition
      /**
       * Creates handlers to deal with operations made on the GUI representing the Mental State
       * Manager
       */
      /*this.msm.registerChangeListener(new GraphModelListener(){

      	public void graphChanged(GraphModelEvent arg0) {
      		MainInteractionManager.logMSM("Evaluating changes in mental state",getLocalName());
      		if (arg0!=null){
      			if (arg0.getChange().getInserted()!=null)
      				for (int k=0;k<arg0.getChange().getInserted().length;k++){
      					MainInteractionManager.logMSM("Inserted "+arg0.getChange().getInserted()[k],getLocalName());
      				}
      			if (arg0.getChange().getRemoved()!=null){

      				for (int k=0;k<arg0.getChange().getRemoved().length;k++){
      					getMSM().remove(arg0.getChange().getRemoved()[k].toString()); // removes the entity if removed from the panel
      					MainInteractionManager.logMSM("Removed "+arg0.getChange().getRemoved()[k],getLocalName());
      				}
      			}
      			if (arg0.getChange().getChanged()!=null)
      				for (int k=0;k<arg0.getChange().getChanged().length;k++){
      					MainInteractionManager.logMSM("Changed "+arg0.getChange().getChanged()[k],getLocalName());
      				}
      		}
      		msp.doReplan();


      	}

      });*/

      /**
       * It creates the initial mental state of the agent. It retrieves elements from the
       * getO2AObject method, a data transfer method.
       */
      MentalEntity queue = null;
      do {
        queue = (MentalEntity) this.getO2AObject();
        if (queue != null) {
          try {
            this.msm.addMentalEntity(queue);
          } catch (InvalidEntity e) {

            e.printStackTrace();
          }
        }
      } while (queue != null);

      /**
       * This behavior takes incoming acl messages and distributes them into two groups: messages
       * being processed and messages not being processed. Messages being processed are added again
       * to the messages queue so that they can be processed by a specialized behavior
       *
       * @return
       */
      final LifeCycleThread vthread = new LifeCycleThread(this);

      getMSM().registerChangeListener(vthread);

      vthread.setName("Lifecycle " + this.getAID().getLocalName());
      vthread.start(); // The thread is constantly running so that no new
      // threads are needed;
      StateBehaviorChangesListener behaviorChangesListener = null;

      behaviorChangesListener =
          new StateBehaviorChangesListener() {
            private void wakeUpCommsManagementBehavior() {
              /*while (!mainBehavior.getExecutionState().equalsIgnoreCase(CyclicBehaviour.STATE_BLOCKED)){
              	//System.out.println(mainBehavior.getExecutionState());
              	try {
              		Thread.sleep(100);
              	} catch (InterruptedException e) {
              		// TODO Auto-generated catch block
              		e.printStackTrace();
              	}
              }*/
              if (mainBehavior.getExecutionState().equalsIgnoreCase(CyclicBehaviour.STATE_BLOCKED))
                mainBehavior.restart();
            }

            @Override
            public void protocolFinished() {
              new Thread("waking up comms from " + getAID().getLocalName()) {
                public void run() {
                  wakeUpCommsManagementBehavior();
                }
              }.start();
            }

            @Override
            public void protocolStarted() {
              new Thread("waking up comms from " + getAID().getLocalName()) {
                public void run() {
                  wakeUpCommsManagementBehavior();
                }
              }.start();
            }

            @Override
            public void stateTransitionExecuted(String fromState, String toState) {
              new Thread("waking up comms from " + getAID().getLocalName()) {
                public void run() {
                  wakeUpCommsManagementBehavior();
                }
              }.start();
            }
          };

      mainBehavior = new CommsManagementBehavior(this, behaviorChangesListener);
      mainBehavior.setBehaviourName("LifeCycle");
      this.addBehaviour(mainBehavior);
      this.getMainBehavior();

    } catch (Throwable t) {
      t.printStackTrace();
    }
  }