@Override
  protected ACLMessage handleAcceptProposal(ACLMessage cfp, ACLMessage propose, ACLMessage accept) {
    // TODO Handle the accept
    Cfp content = null;
    try {
      content = (Cfp) accept.getContentObject();
    } catch (UnreadableException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    //		System.out.println(myAgent.getLocalName() + ": proposta aceite:" +
    // propose.getConversationId() + " content = " + content.getOrigin().getLocalName() + " " +
    // content.getDestination().getLocalName() + " " + content.getAgv().getLocalName());
    ACLMessage reply = accept.createReply();
    reply.setPerformative(ACLMessage.INFORM);
    if (myAgent.getClass() == AGV.class) {
      AGV a = (AGV) myAgent;
      AgvTransport t = new AgvTransport((AGV) myAgent, content);
      a.setTransportBehaviour(t);
      a.addBehaviour(new AgvTransport(a, content));
    }

    return reply;
  }
  @Override
  protected ACLMessage handleCfp(ACLMessage cfp)
      throws RefuseException, FailureException, NotUnderstoodException {

    ACLMessage reply = cfp.createReply();
    reply.setPerformative(ACLMessage.PROPOSE);

    if (myAgent.getClass() == AGV.class) {
      try {
        if (cfp.getContentObject().getClass() == Cfp.class)
          reply = getAgvResponseMessage(reply, (Cfp) cfp.getContentObject(), (AGV) myAgent);
      } catch (UnreadableException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
      }
    } else if (myAgent.getClass() == Machine.class) {
      try {
        reply = getMachineMessageContent(reply, (Cfp) cfp.getContentObject());
      } catch (UnreadableException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
      }
    }
    return reply;
  }
Exemple #3
0
 @Override
 public void action() {
   switch (state) {
     case 0:
       requestSwapAppointments();
       break;
     case 1:
       try {
         recieveSwapAppointmentReply();
       } catch (UnreadableException e) {
         e.printStackTrace();
       } catch (IOException e) {
         e.printStackTrace();
       }
       break;
   }
 }
  /*
   * Only receive message coming from the patientTODO: Also send out status
   * messages
   */
  @Override
  public void action() {
    MessageTemplate template =
        MessageTemplate.MatchConversationId(TrafficUpdateMessage.TRAFFIC_SUBSCRIBERS_CONV);
    List<EQRPoint> points = route.getPoints();

    long duration = route.getDuration();
    double distance = route.getDistance();
    double delay = 0;
    double rate = 1;
    if (traffic != null) {
      delay = traffic.getDelay();
      rate = traffic.getSimulationRate();
    }

    double sim_speed = distance / (duration * rate);
    EQRLogger.log(
        logger,
        null,
        myAgent.getLocalName(),
        getBehaviourName() + ": Attending to Fire  " + fire.getAID().getLocalName());
    for (int i = 0; i < points.size() - 1; i++) {

      ACLMessage up = myAgent.receive(template);
      if (up != null) {
        try {
          Object content = up.getContentObject();
          if (content instanceof TrafficUpdateMessage) {
            traffic = (TrafficUpdateMessage) content;
            delay = traffic.getDelay();
            rate = traffic.getSimulationRate();
            sim_speed = distance / (duration * rate);
          }

        } catch (UnreadableException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      EQRPoint curr = points.get(i);
      EQRPoint nxt = points.get(i + 1);
      engine.setCurrentLocation(curr);
      double dist = EQRAgentsHelper.getDistanceFromGPSCood(curr, nxt);
      double st = (dist / sim_speed) + delay * rate;
      try {
        Thread.sleep((long) st);

      } catch (InterruptedException e) {

        e.printStackTrace();
      }
    }

    engine.setCurrentLocation(points.get(points.size() - 1));

    ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
    ACLMessage msg2 = new ACLMessage(ACLMessage.INFORM);
    msg2.addReceiver(myAgent.getAID());
    msg.addReceiver(fire.getAID());

    AttendToFireMessage atf = new AttendToFireMessage(AttendToFireMessage.TO_FIRE);
    AttendToFireMessage atf2 = new AttendToFireMessage(AttendToFireMessage.TO_FIRE_ENGINE);
    atf.setEngine(engine);
    atf2.setFire(fire);
    try {
      System.out.println(
          myAgent.getLocalName() + " Sending msgs out to FireEngine and Fire " + fire.getAID());
      msg.setContentObject(atf);
      msg2.setContentObject(atf2);
      EQRLogger.log(logger, msg, myAgent.getLocalName(), getBehaviourName() + ": Message sent");
      EQRLogger.log(logger, msg2, myAgent.getLocalName(), getBehaviourName() + ": Message sent");
      myAgent.send(msg2);
      myAgent.send(msg);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    /* TODO: send msg to patient and */
    done = true;
  }
  @Override
  public void action() {
    // Receive information update from world
    HashMap<Integer, ConnectionInfo> queryResponses = new HashMap<Integer, ConnectionInfo>();
    boolean worldMsg = false;
    TrafficLightInfoPacket packet = null;
    while (!worldMsg) {
      ACLMessage msg = myAgent.blockingReceive();
      while (msg.getPerformative() != ACLMessage.INFORM_REF) msg = myAgent.blockingReceive();
      try {
        packet = (TrafficLightInfoPacket) msg.getContentObject();
        worldMsg = true;
      } catch (Exception e) {
        try {
          ConnectionInfo conn = (ConnectionInfo) msg.getContentObject();
          queryResponses.put(conn.getRoadId(), conn);
        } catch (Exception e1) {
          e.printStackTrace();
        }
      }
    }

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

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

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

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

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

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

      // Send register inform to world agent
      ACLMessage replyMsg = new ACLMessage(ACLMessage.INFORM_REF);
      replyMsg.setContentObject(reply);
      replyMsg.addReceiver(result[0].getName());
      myAgent.send(replyMsg);
    } catch (FIPAException | IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Performs the result reception event, eighter blocking or non-blocking (see constructor), and
   * outputs result to given strem. Also keeps track of pending requests and manages completion of
   * the process.
   */
  protected void onWake() {
    ACLMessage msg;
    if (Blocking) {
      msg = myAgent.blockingReceive();
    } else if ((msg = myAgent.receive()) == null) {
      myAgent.addBehaviour(new ReceiveResultBehaviour(myAgent, Interval, pOut, Blocking));
      return;
    }

    CalcResults caRes = null;
    SimilarityArray saRes = null;
    if (msg != null) {
      try {
        // Check if not results
        if (msg.getPerformative() != ACLMessage.INFORM) {
          // Check if activation
          if (msg.getPerformative() == ACLMessage.AGREE) {
            Object oAgentInfo = msg.getContentObject();
            synchronized (myAgent) {
              myAgent.InitializedAgents.remove(oAgentInfo);
              myAgent.ActiveAgents.add(oAgentInfo);
            }
            // Wait for messages
            synchronized (System.err) {
              if (!myAgent.Silent)
                System.err.println("Received move complete message from " + oAgentInfo);
            }
          }
          return;
        }
        // Results
        Object oTemp = msg.getContentObject();
        caRes = (CalcResults) oTemp;
        saRes = caRes.Simil;
        if (saRes != null) {
          // pOut.print(msg.getSender().getLocalName().substring("CalcAgent".length() +
          // myAgent.AgentUniqueIDLength) +
          // "\t");
          pOut.print(caRes.ID + "\t");

          // pOut.print(msg.getSender().getLocalName().substring("CalcAgent".length() +
          // myAgent.AgentUniqueIDLength) +
          // "\t");
          try {
            pOut.print(
                saRes.SimpleTextGraphSimil.ContainmentSimilarity
                    + "\t"
                    + saRes.SimpleTextGraphSimil.ValueSimilarity
                    + "\t"
                    + saRes.SimpleTextGraphSimil.SizeSimilarity
                    + "\t"
                    + saRes.SimpleTextHistoSimil.ContainmentSimilarity
                    + "\t"
                    + saRes.SimpleTextHistoSimil.ValueSimilarity
                    + "\t"
                    + saRes.SimpleTextHistoSimil.SizeSimilarity
                    + "\t"
                    + saRes.SimpleTextOverallSimil.getOverallSimilarity()
                    + "\t");
          } catch (NullPointerException ne) {
            // Ignore
            pOut.print(
                "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0"
                    + "\t" + "0.0" + "\t");
          }
          try {
            pOut.print(
                saRes.NGramGraphSimil.ContainmentSimilarity
                    + "\t"
                    + saRes.NGramGraphSimil.ValueSimilarity
                    + "\t"
                    + saRes.NGramGraphSimil.SizeSimilarity
                    + "\t"
                    + saRes.NGramHistoSimil.ContainmentSimilarity
                    + "\t"
                    + saRes.NGramHistoSimil.ValueSimilarity
                    + "\t"
                    + saRes.NGramHistoSimil.SizeSimilarity
                    + "\t"
                    + saRes.NGramOverallSimil.getOverallSimilarity());
          } catch (NullPointerException ne) {
            pOut.print(
                "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0" + "\t" + "0.0"
                    + "\t" + "0.0");
          }
          pOut.println();
        }

      } catch (UnreadableException ex) {
        System.err.println("Invalid result returned...");
        ex.printStackTrace(System.err);
      }

      // Decrease pending requests
      synchronized (myAgent) {
        myAgent.PendingRequests--;
        myAgent.CompletedRequests++;

        if ((!myAgent.Silent) || (myAgent.ShowProgress))
          System.err.println(
              "Completed "
                  + String.format(
                      "%7.4f", (double) myAgent.CompletedRequests / myAgent.AllRequests * 100)
                  + "%");
        if (myAgent.CompletedRequests == myAgent.AllRequests) myAgent.complete(); // Finished

        // DEBUG LINES
        // System.err.println("Pending " + myAgent.PendingRequests + " requests...");
        //////////////
      }
      ;
    }
  }
Exemple #7
0
  @Override
  public void action() {
    // We have to use a timeout to allow the WakerBehaviour to take place
    final ACLMessage msg = this.myAgent.blockingReceive(100);

    if (msg == null) {
      return;
    }

    final AID sender = msg.getSender();
    Message message = null;

    try {
      message = (Message) msg.getContentObject();
    } catch (final UnreadableException e) {
      System.err.println("[" + this.myAgent.getAID() + "] Error receiving message from " + sender);
      e.printStackTrace(System.err);
      return;
    }

    System.err.println(
        "INFO: [" + this.myAgent.getAID() + "] ReceiveMessage (" + message.getType() + ")");

    switch (message.getType()) {
      case FIRST_ASSIGNATION_REQUEST:
        // TODO: This should maybe be an INFORM message, with reply
        this.teacher.sendMessage(
            sender, new FirstAssignationMessage(this.firstAssignation(sender)));

        this.alumnCount += 1;

        assert this.alumnCount <= TeacherBehaviour.EXPECTED_ALUMN_COUNT;

        if (TeacherBehaviour.EXPECTED_ALUMN_COUNT == this.alumnCount) {
          this.teacher.sendMessageToType("alumn", new InitMessage());
        }

        return;
      case TEACHER_GROUP_CHANGE_REQUEST:
        final TeacherGroupChangeRequestMessage requestMessage =
            (TeacherGroupChangeRequestMessage) message;

        assert requestMessage.fromAlumn.equals(sender);

        // Ensure those alumns haven't been changed previously
        if (this.groups.get(requestMessage.fromAlumn) == requestMessage.fromGroup
            && this.groups.get(requestMessage.toAlumn) == requestMessage.toGroup) {
          this.groups.put(requestMessage.fromAlumn, requestMessage.toGroup);
          this.groups.put(requestMessage.toAlumn, requestMessage.fromGroup);
          this.teacher.sendMessageToType(
              "alumn",
              new TeacherGroupChangeMessage(
                  requestMessage.fromAlumn, requestMessage.toAlumn,
                  requestMessage.fromGroup, requestMessage.toGroup));
        } else {
          this.teacher.sendMessage(
              requestMessage.fromAlumn, new TeacherGroupChangeRequestDenegationMessage());
        }
        return;
      default:
        System.err.println(
            "ERROR: Unexpected message of type "
                + message.getType()
                + " received in TeacherBehaviour. Sender: "
                + sender
                + "; Receiver: "
                + this.teacher.getAID());
        return;
    }
  }
  protected void onTick() {

    listaAgentesComunicacion = paginasAmarillas.buscarServicio("envio-coordenadas", myAgent);
    listaAgentesDeteccionColisiones =
        paginasAmarillas.buscarServicio("deteccion-colisiones", myAgent);

    // Estamos a la escucha para recibir algun mansaje procedente del Agente Servidor
    ACLMessage mensajeEntrante = myAgent.receive();
    if (mensajeEntrante != null) {
      if (mensajeEntrante.getPerformative()
          == ACLMessage.REQUEST) { // Recibimos un mensaje InfoCollision
        try {
          InfoCollision info = (InfoCollision) mensajeEntrante.getContentObject();
          // Dentro del try está la parte relativa a la toma de decisiones:
          String decision;
          if (this.decisionAnterior.equals("perseguir"))
            decision =
                DecisionMaker.tomaDeDecisionesGato(
                    info.getTipoAgente(),
                    info.getOrientacion(),
                    info.getClaridadPercepcion(),
                    info.getDistancia(),
                    this.decisionAnterior,
                    0.3,
                    0.1,
                    0.1,
                    0.1,
                    0.4);
          else
            decision =
                DecisionMaker.tomaDeDecisionesGato(
                    info.getTipoAgente(),
                    info.getOrientacion(),
                    info.getClaridadPercepcion(),
                    info.getDistancia(),
                    this.decisionAnterior,
                    0.5,
                    0.1,
                    0.1,
                    0.1,
                    0.2);

          logger.info("--> DECISION TOMADA POR EL GATO: " + decision);
          String contenido;
          if (decision.equals("perseguir")) {
            contenido = generaCoordenadasPerseguir(info);
            comportamientoTrayectorias = null;
          } else if (decision.equals("esquivar")) {
            contenido = generaCoordenadasEsquivar(info);
            comportamientoTrayectorias = null;
          } else { // "no hacer nada"
            switch (tipoTrayectoria) {
              case PathsBehaviour.OCTOGONAL:
                camino.setOrientacion(Orientation.E);
                break;
              case PathsBehaviour.DIAMANTE:
                camino.setOrientacion(Orientation.NE);
                break;
              case PathsBehaviour.CUADRADA:
                camino.setOrientacion(Orientation.E);
                break;
              case PathsBehaviour.TRIANGULAR:
                camino.setOrientacion(Orientation.O);
                break;
              case PathsBehaviour.ZIGZAG:
                camino.setOrientacion(Orientation.NO);
                break;
              case PathsBehaviour.BARRIDO:
                camino.setOrientacion(Orientation.E);
                break; // nuevo
            }
            contenido = generaCoordenadas();
          }

          for (int i = 0;
              i < listaAgentesComunicacion.length && listaAgentesDeteccionColisiones.length > 0;
              i++) {
            if (activado) nuevoMensaje(listaAgentesComunicacion[i].getLocalName(), contenido);
            mensajeInfoAgente(listaAgentesDeteccionColisiones[i].getLocalName());
            logger.info(
                "GATO EN "
                    + camino.getPunto().getX()
                    + " "
                    + camino.getPunto().getY()
                    + " "
                    + camino.getPunto().getZ()
                    + " "
                    + camino.getOrientacion());
          }

          // Almacenamos la decisión para tenerla en cuenta la vez siguiente: es un criterio.
          this.decisionAnterior = decision;

        } catch (UnreadableException e) {
          e.printStackTrace();
        }
      } else {
        logger.info("Mensaje entrante del gato: " + mensajeEntrante.getContent());
        String contenidoMensaje = mensajeEntrante.getContent();
        if (contenidoMensaje.contains("morir")) { // Matamos a los agentes
          myAgent.doDelete();
        } else if (contenidoMensaje.contains(
            "comunicacion-lista")) { // Permitimos que empiecen a generar coordenadas
          activado = true;
        } else if (contenidoMensaje.contains(
            "genera")) { // Permitimos que sigan generando coordenadas
          String contenido = generaCoordenadas();
          for (int i = 0;
              i < listaAgentesComunicacion.length && listaAgentesDeteccionColisiones.length > 0;
              i++) {
            if (activado) nuevoMensaje(listaAgentesComunicacion[i].getLocalName(), contenido);
            mensajeInfoAgente(listaAgentesDeteccionColisiones[i].getLocalName());
            logger.info(
                "GATO EN "
                    + camino.getPunto().getX()
                    + " "
                    + camino.getPunto().getY()
                    + " "
                    + camino.getPunto().getZ()
                    + " "
                    + camino.getOrientacion());
          }
        }
      }
    } else { // Permanecemos a la espera de que llegue un mensaje
      block();
    }
  }