public Agent process(Pred directive, Agent outerContent, Agent innerContent) {
    try {
      Agent newAg = new Agent();
      newAg.initAg();

      PlanBodyImpl endofplan = null;
      Literal goal = null;

      // ListTerm annots =
      // ListTermImpl.parseList("[scheme(SchId),mission(MissionId),group(GroupId)]");

      // change all inner plans
      for (Plan p : innerContent.getPL()) {
        // create end of plan: .wait
        InternalActionLiteral wait = new InternalActionLiteral(".wait");
        wait.addTerm(directive.getTerm(0));
        endofplan = new PlanBodyImpl(PlanBody.BodyType.internalAction, wait);

        // create end of plan: !!goal[.....]
        // p.getTrigger().getLiteral().addAnnots( (ListTerm)annots.clone());
        goal = p.getTrigger().getLiteral().copy();
        endofplan.add(new PlanBodyImpl(PlanBody.BodyType.achieveNF, goal));

        // add in the end of plan
        p.getBody().add(endofplan);
        newAg.getPL().add(p, false);
      }

      // add failure plan:
      //    -!goto_near_unvisited[scheme(Sch),mission(Mission)]
      //        <- .current_intention(I);
      //           .print("ooo Failure to goto_near_unvisited ",I);
      //           .wait("+pos(_,_,_)"); // wait next cycle
      //           !!goto_near_unvisited[scheme(Sch),mission(Mission)].
      goal = goal.copy();
      goal.addAnnot(ASSyntax.parseStructure("error(EID)"));
      goal.addAnnot(ASSyntax.parseStructure("error_msg(EMsg)"));
      // goal.addAnnot(ASSyntax.parseStructure("code_line(ELine)"));
      String sp =
          "-!"
              + goal
              + " <- .current_intention(I); "
              + ".println(\"ooo Failure in organisational goal "
              + goal.getFunctor()
              + ": \", EID, \" -- \", EMsg); "
              + ".println(\"ooo intention is \",I); "
              + endofplan
              + ".";
      Plan p = ASSyntax.parsePlan(sp);
      newAg.getPL().add(p);
      return newAg;
    } catch (Exception e) {
      logger.log(Level.SEVERE, "OrgMaintenanceGoal directive error.", e);
    }
    return null;
  }
Example #2
0
  @SuppressWarnings("deprecation")
  @Override
  public void run() {
    running = true;
    while (running) {
      try {
        String value = in.readLine();

        if (value == null) {
          running = false;
          break;
        }

        String newValue = "";
        // clears the string for errors.
        for (char c : value.toCharArray()) {
          if (c != 0) {
            newValue += c;
          }
        }
        value = newValue;
        LOG.info("Received: " + value);
        Literal l = Literal.parseLiteral(value);
        try {
          l.addSource(ASSyntax.parseTerm("percept"));
        } catch (ParseException ex) {
          LOG.log(Level.SEVERE, "Could not add source", ex);
        }
        pendingBeliefs.add(l);
      } catch (IOException ex) {
        LOG.log(Level.SEVERE, "Could not read BT input.", ex);
      }
    }
  }
  /**
   * @param agentName
   * @param actionName
   * @param parameters
   * @param unifier
   * @return Maps internal Jason agent actions to camel messages
   */
  public Object agentInternallyActed(
      String agentName, String actionName, List<Term> parameters, Unifier unifier) {
    Object actionsucceeded = true;
    Exchange exchange = endpoint.createExchange();

    // Agent action can only be processed by an endpoint of type "action"
    if (endpoint.getUriOption().contains("action")) {

      try {

        List<String> paramsAsStrings = new ArrayList<String>();
        for (Term t : parameters) {
          paramsAsStrings.add(t.toString());
        }
        sendActionToCamel(agentName, actionName, paramsAsStrings, exchange, "");

      } catch (Exception e) {

      } finally {

        // log exception if an exception occurred and was not handled
        if (exchange.getException() != null) {
          getExceptionHandler()
              .handleException("Error processing exchange", exchange, exchange.getException());
          actionsucceeded = false;
        } else {
          String ep = endpoint.getExchangePattern().toString();
          // Just send out camel message and inform success to agent
          if (ep.equals("InOnly")) actionsucceeded = true;

          // Unification is applicable to InOut exchanges only. This waits for the return message
          // from the exchange
          else if (ep.equals("InOut")) {
            if (exchange.hasOut()) {
              List<String[]> mappings = getResultHeaderSplitted();
              for (String[] mapping : mappings) {
                int unPos = Integer.parseInt(mapping[1]);
                String headerVal = mapping[0];

                // ArrayList<String> l = (ArrayList<String>)exchange.getIn().getHeader(headerVal);
                // Iterator<String> it = l.iterator();
                String unVal = exchange.getIn().getHeader(headerVal).toString();
                try {
                  unifier.unifies(parameters.get(unPos), ASSyntax.parseTerm(unVal));
                } catch (jason.asSyntax.parser.ParseException e) {
                  System.out.println(
                      "Error parsing result header from synchronous InOut action: " + unVal);
                  return false;
                }
              }
              return true;
            } else actionsucceeded = false;
          }
        }
      }
    }
    return actionsucceeded;
  }
Example #4
0
  @Override
  public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
    checkArguments(args);

    StringTerm st = (StringTerm) args[0];
    HouseModel hm = getTerrain(ts);
    if (hm == null) return false;
    String[] array = hm.planRoute(ts.getUserAgArch().getAgName(), st.getString());
    if (array == null) return false;

    ListTerm ln = new ListTermImpl();
    ListTerm tail = ln;

    for (String orientation : array) {
      tail = tail.append(ASSyntax.createString(orientation));
    }

    return un.unifies(args[1], ln);
  }
  private ListTerm[] coordinateGroup(
      int group, List<List<Vertex>> actualZones, List<Vertex> bestZone) {
    ListTerm positions = new ListTermImpl();
    ListTerm agents = new ListTermImpl();

    String[] missions;
    if (group == 1) {
      missions = new String[] {"mOccupyZone1", "mRepairZone1"};
    } else if (group == 2) {
      missions = new String[] {"mOccupyZone2", "mRepairZone2"};
    } else {
      missions = new String[] {"mOccupyZone1", "mRepairZone1", "mOccupyZone2", "mRepairZone2"};
    }

    List<Entity> coworkers = model.getCoworkersWithMission(Arrays.asList(missions));

    Graph graph = model.getGraph();

    List<Vertex> groupZone = null;
    if (bestZone != null && !bestZone.isEmpty()) {
      for (List<Vertex> zone : actualZones) {
        if (graph.hasAtLeastOneVertexOnZone(zone, bestZone)) {
          groupZone = zone;
          continue;
        }
      }
    } else if (actualZones != null && !actualZones.isEmpty()) {
      groupZone = actualZones.get(0);
    }

    List<Vertex> targets = new ArrayList<Vertex>();
    if (groupZone == null || groupZone.isEmpty()) {
      if (bestZone != null && !bestZone.isEmpty()) {
        targets.addAll(bestZone);
      }
    } else {
      if (bestZone != null && !bestZone.isEmpty()) {
        bestZone.removeAll(groupZone);
        targets.addAll(bestZone);
      }

      // zone neighbors
      List<Vertex> zoneNeighbors = model.getZoneNeighbors(groupZone);
      // order neighbors by vertex value
      Collections.sort(zoneNeighbors, comparator);

      targets.addAll(zoneNeighbors);
    }

    if (targets.isEmpty()) {
      return new ListTerm[] {agents, positions};
    }

    for (Entity coworker : coworkers) {
      if (coworker.getStatus().equals(Percept.STATUS_DISABLED)) {
        continue;
      }
      Vertex target = null;
      Vertex agentPosition = coworker.getVertex();
      if (bestZone.contains(agentPosition)
          && model.isFrontier(agentPosition)) { // the agent is part of the best zone's frontier
        List<Entity> agsOnSameVertex = model.getCoworkersOnSameVertex(coworker);
        if (!agsOnSameVertex.isEmpty()) { // if there are other agents on the same vertex
          boolean canMove = true;
          for (Entity ag : agsOnSameVertex) {
            if (ag.getId() > coworker.getId()) {
              canMove = false; // only the agent with the lower id can move
              break;
            }
          }
          if (!canMove) {
            continue;
          }
        } else {
          if (model.hasActiveCoworkersOnNeighbors(
              coworker)) { // go to a free neighbor if has two or more coworkers on neighbors
            Vertex neighbor = model.getFreeNeighborOutOfZone(agentPosition);
            if (null != neighbor) {
              agents.add(ASSyntax.createString(coworker.getName()));
              positions.add(ASSyntax.createString("vertex" + neighbor.getId()));
            }
            continue;
          } else {
            continue; // the agent must not move if he is in the frontier and has no other agent on
                      // the same vertex
          }
        }
      }

      if (null != targets && !targets.isEmpty()) {
        //				target = model.closerVertex(agentPosition, targets);
        target = targets.get(0);
        if (null != target) {
          targets.remove(target);
        }
      }

      if (null != target) {
        agents.add(ASSyntax.createString(coworker.getName()));
        positions.add(ASSyntax.createString("vertex" + target.getId()));
      }
    }
    return new ListTerm[] {agents, positions};
  }