public void controlState() {
    final Mat image = camera.getLastFrame();
    final ComputerVisionSummary summaryOfImage = ComputerVisionSummary.produceFullSummary(image);

    final double wallThresholdDistance = 10;

    // if wall is close, and we are not currently avoiding walls, then avoid walls
    if ((summaryOfImage.getDistanceToBlueWall() <= wallThresholdDistance)
        && !(currentStateController.getStateMachineType() == StateMachineType.AVOID_WALLS
            && !currentStateController.isDone())) {
      avoidWalls();
    }

    // else if see ball, and not currently collecting one, then collect ball
    else if ((summaryOfImage.isGreenBall() || summaryOfImage.isRedBall())
        && !(currentStateController.getStateMachineType() == StateMachineType.COLLECT_GROUND_BALLS
            && !currentStateController.isDone())) {
      collectGroundBalls();
    }

    // if see reactor and have green balls then score
    // if see interface wall and have red balls then score over wall
    // if see energy silo then collect ball

  }
示例#2
0
  @SuppressLint("InflateParams")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    ALog.v(TAG, "onCreate. Entry...");

    super.onCreate(savedInstanceState);

    ViewGroup viewGroup = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_select, null);
    setContentView(viewGroup);

    listOfApps = (ListView) viewGroup.findViewById(R.id.selectList);
    TextView headline = (TextView) viewGroup.findViewById(R.id.selectDescription);

    StateMachine.loadGPSAwareApplications(true);
    applications = StateMachine.getGPSAwareApplicationsList();

    if (applications.size() > 0) {
      listOfApps.setAdapter(new StableArrayAdapter(this));

      headline.setText(R.string.selectDescription);
    } else {
      headline.setText(R.string.selectDescriptionNo);
    }

    ALog.v(TAG, "onCreate. Exit.");
  }
示例#3
0
 public MinersWife(int ID, String name) {
   super(ID, name);
   location = Location.shack;
   pStateMachine = new StateMachine<MinersWife>(this);
   pStateMachine.setCurrentState(DoHouseWork.getSingleton());
   pStateMachine.setGlobalState(WifesGlobalState.getSingleton());
 }
示例#4
0
 /**
  * Monte-Carlo simulation for playout.
  *
  * @param node Node to start at
  * @param timeout Time limit
  * @return Scores for all players
  */
 private int[] playout(Node node, long timeout) {
   if (node instanceof TerminalNode) {
     return ((TerminalNode) node).goal;
   }
   MachineState state = ((NonTerminalNode) node).state;
   while (System.currentTimeMillis() < timeout) {
     if (theMachine.isTerminal(state)) {
       List<Integer> s;
       try {
         s = theMachine.getGoals(state);
       } catch (GoalDefinitionException e) {
         System.err.println("Could not compute goal values.");
         return null;
       }
       int[] scores = new int[s.size()];
       for (int i = 0; i < scores.length; i++) {
         scores[i] = s.get(i);
       }
       return scores;
     }
     try {
       state = theMachine.getNextState(state, theMachine.getRandomJointMove(state));
     } catch (TransitionDefinitionException e) {
       System.err.println("Could not perform state update.");
       return null;
     } catch (MoveDefinitionException e) {
       System.err.println("Could not compute legal moves.");
       return null;
     }
   }
   return null;
 }
示例#5
0
  /** Creates the instantiation and connects up all the ports/buses. */
  public void stateLogic(Module module, StateMachine mach) {
    ModuleInstance instance = new ModuleInstance(getVerilogName(design), "test");

    /*
     * Connect clock and reset if needed.
     */
    for (Design.ClockDomain domain : design.getAllocatedClockDomains()) {
      instance.add(
          new PortConnection(new Input(getVerilogName(domain.getClockPin()), 1), mach.getClock()));
      if (domain.getResetPin() != null) {
        instance.add(
            new PortConnection(
                new Input(getVerilogName(domain.getResetPin()), 1), mach.getReset()));
      }
    }

    for (TaskHandle th : taskHandles) {
      Task task = th.getTask();
      for (Port port : task.getCall().getPorts()) {
        InputPin pin = (InputPin) design.getPin(port);
        Wire portWire = th.getWireForConnection(port);
        if (portWire == null) {
          continue;
        }

        // Use the Port's bus to agree with InputPinPort and
        // VerilogNamer, but output pins use the actual pin.
        PortConnection pc =
            new PortConnection(new Input(getVerilogName(pin.getBus()), pin.getWidth()), portWire);
        instance.add(pc);
      }

      for (Bus bus : task.getCall().getExit(Exit.DONE).getBuses()) {
        Wire busWire = th.getWireForConnection(bus);
        if (busWire == null) {
          continue;
        }

        Pin pin = design.getPin(bus);
        PortConnection pc =
            new PortConnection(new Output(getVerilogName(pin), pin.getWidth()), busWire);
        instance.add(pc);
      }

      Pin goPin = design.getPin(task.getCall().getGoPort());
      if (goPin != null) {
        instance.add(
            new PortConnection(
                new Input(getVerilogName(((InputPin) goPin).getBus()), 1), th.getGoWire()));
      }

      Pin donePin = design.getPin(task.getCall().getExit(Exit.DONE).getDoneBus());
      if (donePin != null) {
        instance.add(new PortConnection(new Output(getVerilogName(donePin), 1), th.getDoneWire()));
      }
    }

    module.state(instance);
  }
示例#6
0
 public void frame__windowStateChanged(WindowEvent e) {
   if ((e.getNewState() & Frame.ICONIFIED) == Frame.ICONIFIED) {
     stateMachine.minimized = true;
     KeyHook.unblockWindowsKey();
   } else if ((e.getNewState() & Frame.NORMAL) == Frame.NORMAL) {
     stateMachine.minimized = false;
     KeyHook.blockWindowsKey();
   }
 }
  @Test
  public void load_and_set_active_state_as_a_inner_state() {
    StateMachine atm = new ATMStateMachine();
    atm.activeStateConfiguration(Arrays.asList(SERVING_CUSTOMER, AUTHENTICATION));

    atm.execute(new Authenticated());

    assertThat(atm.getActiveStateConfiguration())
        .containsSequence(SERVING_CUSTOMER, SELECTING_TRANSACTION);
  }
  @Test
  public void from_idle_to_authentication() {
    StateMachine atm = new ATMStateMachine();
    atm.activeStateConfiguration(asList(IDLE));

    atm.execute(new CardInserted());

    assertThat(atm.getActiveStateConfiguration())
        .containsSequence(SERVING_CUSTOMER, AUTHENTICATION);
  }
  @Test
  public void from_off_through_idle_back_to_off() {
    StateMachine atm = new ATMStateMachine();

    atm.execute(new TurnedOn());
    atm.execute(new TestedOk());
    atm.execute(new TurnedOff());

    assertThat(atm.getActiveStateName()).isEqualTo(OFF);
  }
示例#10
0
 public static ArrayList<StateMachine> findStateMachine(Thing thing, String name, boolean fuzzy) {
   ArrayList<StateMachine> result = new ArrayList<StateMachine>();
   for (StateMachine t : allStateMachines(thing)) {
     if (t.getName().startsWith(name)) {
       if (fuzzy) result.add(t);
       else if (t.getName().equals(name)) result.add(t);
     }
   }
   return result;
 }
  @Test
  public void simple_state_transfers() {
    // Given
    StateMachine atm = new ATMStateMachine();

    // When
    atm.execute(new TurnedOn());

    // Then
    assertThat(atm.getActiveStateName()).isEqualTo(SELF_TEST);
  }
示例#12
0
  @Test
  public void testBreakAndContinue() throws Exception {
    State s1 = new State("s1");
    s1.addTransition(new BreakAndContinueTransition("foo"));
    s1.addTransition(new SuccessTransition("foo"));

    StateContext context = new DefaultStateContext();
    StateMachine sm = new StateMachine(new State[] {s1}, "s1");
    sm.handle(new Event("foo", context));
    assertEquals(true, context.getAttribute("success"));
  }
示例#13
0
  @Override
  public void check(final Node node) {

    // Store snapshot from last check
    if (stateMachine.getLastNode() != null) {
      history.store(
          stateMachine.getLastNode(), currentGroupify, stateMachine.getLastTransition().snapshot);
    }

    // Transition
    final Transition transition = stateMachine.transition(node);

    // Switch groupifies
    final IHashGroupify temp = lastGroupify;
    lastGroupify = currentGroupify;
    currentGroupify = temp;
    currentGroupify.clear();

    // Apply transition
    switch (transition.type) {
      case UNOPTIMIZED:
        currentGroupify =
            transformer.apply(transition.projection, node.getTransformation(), currentGroupify);
        break;
      case ROLLUP:
        currentGroupify =
            transformer.applyRollup(
                transition.projection, node.getTransformation(), lastGroupify, currentGroupify);
        break;
      case SNAPSHOT:
        currentGroupify =
            transformer.applySnapshot(
                transition.projection,
                node.getTransformation(),
                currentGroupify,
                transition.snapshot);
        break;
    }

    // Mark as checked
    node.setChecked();

    // Propagate k-anonymity
    node.setKAnonymous(currentGroupify.isKAnonymous());

    // Propagate anonymity and information loss
    if (currentGroupify.isAnonymous()) {
      node.setAnonymous(true);
      metric.evaluate(node, currentGroupify);
    } else {
      node.setInformationLoss(null);
      node.setAnonymous(false);
    }
  }
  @Test
  public void to_dot() {
    StateMachine atm = new ATMStateMachine();

    System.out.println("DOT notation for ATM:");
    System.out.println(atm.toDot(false));

    // Force the composite state to active state for producing DOT notation of the composite state
    atm.activeStateConfiguration(Arrays.asList(SERVING_CUSTOMER, AUTHENTICATION));
    System.out.println("DOT notation for Composite state ServingCustomer:");
    System.out.println(((CompositeState) atm.getActiveState()).toDot(false));
  }
示例#15
0
  /**
   * Make sure InvariantViolationPlugin executed.
   *
   * @throws ConfigurationException when failure configuring Properties
   */
  @Test
  public void testInvariantFailurePlugin() throws ConfigurationException {
    hit = false;
    CrawljaxConfigurationBuilder builder =
        CrawljaxConfiguration.builderFor("http://localhost")
            .addPlugin(
                new OnInvariantViolationPlugin() {
                  @Override
                  public void onInvariantViolation(Invariant invariant, CrawlSession session) {
                    hit = true;
                  }
                });
    builder
        .crawlRules()
        .addInvariant(
            new Invariant(
                "Test123",
                new Condition() {

                  @Override
                  public NodeList getAffectedNodes() {
                    return null;
                  }

                  @Override
                  public boolean check(EmbeddedBrowser browser) {
                    return false;
                  }
                }));
    setStateMachineForConfig(builder.build());

    // state2.equals(state3)
    StateVertex state2 = new StateVertex("state2", "<table><div>state2</div></table>");
    StateVertex state3 = new StateVertex("state3", "<table><div>state2</div></table>");

    Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);

    assertTrue(sm.updateAndCheckIfClone(c, state2, dummyBrowser, new CrawlSession(dummyPool)));

    // New State so hit must be true;
    assertTrue("InvariantViolationPlugin are exeucted", hit);
    hit = false;
    assertFalse("Hit reseted", hit);

    Eventable c2 = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);

    assertFalse(sm.updateAndCheckIfClone(c2, state3, dummyBrowser, new CrawlSession(dummyPool)));

    // New State so plugin execution
    assertTrue("InvariantViolationPlugin are exeucted", hit);
  }
  @Test
  public void testUpdateWithConnectorSet() {
    try {
      stateMachine.updateWith(Command.AYT);
      stateMachine.updateWith(Command.SCO);
      stateMachine.updateWith(Command.RST);
      stateMachine.updateWith(Command.AYT);
      stateMachine.updateWith(Command.SCO);
      stateMachine.updateWith(Command.SCO);
      stateMachine.updateWith(Command.SCP);
    } catch (ProtocolStateException ignored) {
      Assert.fail();
    }

    try {
      stateMachine.updateWith(Command.AYT);
      Assert.fail();
    } catch (ProtocolStateException ignored) {
    }

    try {
      stateMachine.updateWith(Command.GCO);
      Assert.fail();
    } catch (ProtocolStateException ignored) {
    }

    try {
      stateMachine.updateWith(Command.CTF);
      Assert.fail();
    } catch (ProtocolStateException ignored) {
    }

    try {
      stateMachine.updateWith(Command.SWA);
      Assert.fail();
    } catch (ProtocolStateException ignored) {
    }

    try {
      stateMachine.updateWith(Command.GWA);
      Assert.fail();
    } catch (ProtocolStateException ignored) {
    }

    try {
      stateMachine.updateWith(Command.CTT);
    } catch (ProtocolStateException ignored) {
      Assert.fail();
    }
  }
示例#17
0
  @Test
  public void testBreakAndGotoNext() throws Exception {
    State s1 = new State("s1");
    State s2 = new State("s2");
    s1.addTransition(new BreakAndGotoNextTransition("foo", "s2"));
    s2.addTransition(new SuccessTransition("foo"));

    StateContext context = new DefaultStateContext();
    StateMachine sm = new StateMachine(new State[] {s1, s2}, "s1");
    sm.handle(new Event("foo", context));
    assertSame(s2, context.getCurrentState());
    sm.handle(new Event("foo", context));
    assertEquals(true, context.getAttribute("success"));
  }
示例#18
0
  /**
   *
   *
   * <pre>
   * always @(posedge clk)
   * begin
   *   if (hangTimer > 150) begin
   *    $fwrite(resultFile, "FAIL: Hang Timer Expired\n");
   *    $finish;
   * end
   *
   * if (foo_go || foo_done || bar_go || bar_done) hangTimer <= 0;
   * else hangTimer <= hangTimer + 1;
   * </pre>
   */
  private void stateTimer(Module module, SimFileHandle resFile, StateMachine mach) {
    Option op = EngineThread.getGenericJob().getOption(OptionRegistry.HANG_TIMER);
    int HANGTIMER = Integer.parseInt(op.getValue(CodeLabel.UNSCOPED).toString(), 10);

    SequentialBlock trueBlock = new SequentialBlock();

    // Hang timer expiry

    FStatement.FWrite write =
        new FStatement.FWrite(
            resFile.getHandle(), new StringStatement("FAIL: Hang Timer Expired\\n"));
    trueBlock.add(write);
    trueBlock.add(new FStatement.Finish());

    ConditionalStatement cs =
        new ConditionalStatement(
            new Compare.GT(getHangTimer(), new Constant(HANGTIMER, getHangTimer().getWidth())),
            trueBlock);

    SequentialBlock block = new SequentialBlock(cs);

    // Hang timer increment
    // List goDone = new ArrayList();
    // for (Iterator iter = this.taskHandles.iterator(); iter.hasNext();)
    // {
    // TaskHandle th = (TaskHandle)iter.next();
    // goDone.add(th.getGoWire());
    // goDone.add(th.getDoneWire());
    // }

    Assign htReset =
        new Assign.NonBlocking(getHangTimer(), new Constant(0, getHangTimer().getWidth()));
    Assign htInc =
        new Assign.NonBlocking(
            getHangTimer(),
            new org.xronos.openforge.verilog.model.Math.Add(
                getHangTimer(), new Constant(1, getHangTimer().getWidth())));
    // ConditionalStatement htCond = new ConditionalStatement(
    // new OrMany(goDone), htReset, htInc);
    ConditionalStatement htCond =
        new ConditionalStatement(
            new Logical.Or(mach.getAllGoWire(), mach.getAllDoneWire()), htReset, htInc);
    block.add(htCond);

    ProceduralTimingBlock ptb =
        new ProceduralTimingBlock(
            new EventControl(new EventExpression.PosEdge(mach.getClock())), block);

    module.state(new Always(ptb));
  }
示例#19
0
 /** Method sends a Close message to the server returns 1 on success */
 public CTPResponse Close() {
   // request
   Close close = new Close();
   CTPResponse response = sMachine.Process(sMachine.SENDING, close);
   close(); // now close the socket
   return response;
 }
示例#20
0
  @Override
  public void update(long dt) {
    sqtList.onUpdate(dt);
    repaint();

    if (!sqtList.tilesMoving()) {
      isActive = true;
      puzzleTicker.pause();
    }

    if (sqtList.puzzleCompleted()) {
      stateMachine.state = State.COMPLETED;
      stateMachine.executeState();
      isActive = false;
    }
  }
示例#21
0
  /**
   * This method verify if the transition from the current state to dest is valid. If so, the
   * current state is updated to dest. The up-to-date current state is returned.
   *
   * @param src The source state.
   * @param dest The destination state.
   * @return The curent state.
   */
  public synchronized String transitionState(String dest) {
    if (stateMachine.isTransitionValid(currentState, dest)) {
      currentState = dest;
    }

    return currentState;
  }
示例#22
0
  @Test
  public void testOnEntry() throws Exception {
    State s1 = new State("s1");
    State s2 = new State("s2");

    s1.addTransition(new SuccessTransition("foo", s2));
    s1.addOnExitSelfTransaction(new SampleSelfTransition());
    s2.addOnEntrySelfTransaction(new SampleSelfTransition());

    StateContext context = new DefaultStateContext();
    StateMachine sm = new StateMachine(new State[] {s1, s2}, "s1");
    sm.handle(new Event("foo", context));
    assertEquals(true, context.getAttribute("success"));
    assertEquals(true, context.getAttribute("SelfSuccess" + s1.getId()));
    assertEquals(true, context.getAttribute("SelfSuccess" + s2.getId()));
  }
示例#23
0
 public void keyPressed() {
   if (keyCode == ESC || key == ESC) {
     key = 0;
     keyCode = 0;
     stateMachine.Pop();
   }
 }
示例#24
0
 public QueryState getState() {
   readLock.lock();
   try {
     return stateMachine.getCurrentState();
   } finally {
     readLock.unlock();
   }
 }
示例#25
0
  /**
   *
   *
   * <ul>
   *   <li>Go to passive state if the ball is outside of movement range
   *   <li>Go to Defending state if the team doesnt have the ball and the agent doesnt have the ball
   *   <li>Go to Support state if the agent doesn't have the ball but the team does have the ball
   * </ul>
   *
   * @param stateMachine State Machine to update.
   * @param model Model containing the current game state.
   */
  @Override
  public void updateState(StateMachine stateMachine, EnvironmentModel model) {

    if (!model.ballInMovementRange() && !model.agentHasBall()) {
      stateMachine.changeState(StateMachine.PASSIVE_STATE, model);
      return;
    }

    if (!model.teamHasBall() && !model.agentHasBall()) {
      stateMachine.changeState(StateMachine.DEFENDING_STATE, model);
      return;
    }

    if (!model.agentHasBall() && model.teamHasBall() && !model.isPlayerGoalKeeper()) {
      stateMachine.changeState(StateMachine.SUPPORT_STATE, model);
    }
  }
示例#26
0
  /** Dequeues and delivers one message. */
  public boolean pump() {
    if (messages.isEmpty()) {
      return false;
    }

    Message message = (Message) messages.pop();
    int destAddress = message.destination;

    if (!stateMachines.containsKey(destAddress)) {
      throw new IllegalStateException(
          "Couldn't deliver message addressed to non-existent state machine" + destAddress);
    }

    StateMachine stateMachine = (StateMachine) stateMachines.get(destAddress);
    stateMachine.deliver(message);

    return true;
  }
示例#27
0
  /** Make sure Invariants are executed! */
  @Test
  public void testInvariants() {
    // state2.equals(state3)
    StateVertex state2 = new StateVertex("state2", "<table><div>state2</div></table>");
    StateVertex state3 = new StateVertex("state3", "<table><div>state2</div></table>");

    hit = false;
    ImmutableList<Invariant> iList =
        ImmutableList.of(
            new Invariant(
                "Test123",
                new Condition() {

                  @Override
                  public NodeList getAffectedNodes() {
                    return null;
                  }

                  @Override
                  public boolean check(EmbeddedBrowser browser) {
                    hit = true;
                    return false;
                  }
                }));
    StateMachine smLocal =
        new StateMachine(new StateFlowGraph(index), index, iList, Plugins.noPlugins());

    Eventable c = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);

    assertTrue(smLocal.updateAndCheckIfClone(c, state2, dummyBrowser, new CrawlSession(dummyPool)));

    // New State so hit must be true;
    assertTrue("Invariants are exeucted", hit);
    hit = false;
    assertFalse("Hit reseted", hit);

    Eventable c2 = new Eventable(new Identification(How.xpath, "/bla"), EventType.click);

    assertFalse(
        smLocal.updateAndCheckIfClone(c2, state3, dummyBrowser, new CrawlSession(dummyPool)));
    // CLONE State so hit must be true;
    assertTrue("Invariants are exeucted", hit);
  }
示例#28
0
 public void setup() {
   size((int) (displayWidth * SCALE), (int) (displayWidth * SCALE / ASPECT_RATIO), P2D);
   // size(1920,1080);
   frame.setTitle("Customer Simulator v0.0.1");
   KeyHook.blockWindowsKey();
   ui = new ControlP5(this);
   String dir = System.getProperty("user.dir");
   font = createFont(dir + "/src/Data/arialbd.ttf", 48);
   stateMachine = new StateMachine();
   stateMachine.Push(new States.State_1(this, ui, font));
 }
示例#29
0
 @Override
 public void stateMachineMetaGame(long timeout)
     throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
   started = false;
   // theMachine = getStateMachine();
   root = new NonTerminalNode(currentState);
   // System.out.println(getRole());
   role = theMachine.getRoleIndices().get(getRole());
   timeout -= 1000;
   mcts(timeout);
   started = true;
 }
示例#30
0
  @Test
  public void countDownTest() {
    EventSource<Void> src1 = new EventSource<Void>();
    EventSource<Void> src2 = new EventSource<Void>();
    EventSource<Void> reset = new EventSource<Void>();

    BiFunction<Integer, Void, Tuple2<Integer, Optional<String>>> countdown =
        (s, i) -> s == 1 ? t(3, Optional.of("COUNTDOWN REACHED")) : t(s - 1, Optional.empty());

    EventStream<String> countdowns =
        StateMachine.init(3)
            .on(src1)
            .transmit(countdown)
            .on(src2)
            .transmit(countdown)
            .on(reset)
            .transition((s, i) -> 3)
            .toEventStream();

    Counter counter = new Counter();
    Subscription sub = countdowns.hook(x -> counter.inc()).pin();

    src1.push(null);
    src2.push(null);
    assertEquals(0, counter.get());

    src1.push(null);
    assertEquals(1, counter.getAndReset());

    src2.push(null);
    src2.push(null);
    reset.push(null);
    assertEquals(0, counter.get());
    src2.push(null);
    assertEquals(0, counter.get());
    src1.push(null);
    assertEquals(0, counter.get());
    src2.push(null);
    assertEquals(1, counter.getAndReset());

    sub.unsubscribe();
    src1.push(null);
    src1.push(null);
    src1.push(null);
    src1.push(null);
    src1.push(null);
    src1.push(null);
    assertEquals(0, counter.get());
  }