Class FiniteStateMachine<StateT extends Enum<StateT> & FsmState<StateT,ContextT>, ContextT>

java.lang.Object
xbot.common.logic.FiniteStateMachine<StateT,ContextT>
Type Parameters:
StateT - The enum type representing the states of this machine.
ContextT - The type of the payload passed to execute(Object) on every cycle.

public class FiniteStateMachine<StateT extends Enum<StateT> & FsmState<StateT,ContextT>, ContextT> extends Object
A small, reusable, polled finite state machine, intended to be ticked once per robot loop from a Subsystem.periodic() or Command.execute(). There is no event queue; "events" are simply changes visible in ContextT between calls to execute(Object).

States are represented as constants of an enum implementing FsmState, with each constant supplying its own execute() (and, optionally, enter()/exit()) via a constant-specific class body. States must be stateless - enum constants are singletons shared by every FiniteStateMachine instance using that enum type, so any mutable data a state needs belongs on ContextT, never on the enum itself.

The initial state's enter() is not invoked at construction time (no payload is available yet); it runs lazily on the first call to execute(Object) or forceState(...), using the payload from that call.

Any exception or error thrown by a hook (before-hook, state execution, after-hook, enter, exit) is caught and logged, aborting only the current cycle - the machine remains in whatever state it had reached and is ready to be executed again next cycle. This is deliberately caught as Throwable, not just RuntimeException (mirroring XScheduler's handling of command exceptions): a bug that causes runaway recursive transitions (e.g. two states each redirecting to the other from enter()) surfaces as a StackOverflowError, which is an Error, not an Exception - without this, such a bug would defeat the whole point of isolating this state machine from the rest of the robot loop.

Example - a simple intake sequence:

   stateDiagram-v2
       [*] --> Idle
       Idle --> Intaking : intakeRequested
       Intaking --> Holding : hasGamePiece
       Holding --> Idle : timeInState > 2s AND !intakeRequested
public enum IntakeFsmState implements FsmState<IntakeFsmState, IntakeSubsystem> {
    Idle {
        public void execute(FsmContext<IntakeSubsystem> context, FsmTransition<IntakeFsmState> transition) {
            context.payload().setRollerPower(0);
            if (context.payload().isIntakeRequested()) {
                transition.transitionTo(Intaking);
            }
        }
    },
    Intaking {
        public void execute(FsmContext<IntakeSubsystem> context, FsmTransition<IntakeFsmState> transition) {
            context.payload().setRollerPower(IntakeSubsystem.INTAKE_POWER);
            if (context.payload().hasGamePiece()) {
                transition.transitionTo(Holding);
            }
        }
    },
    Holding {
        public void execute(FsmContext<IntakeSubsystem> context, FsmTransition<IntakeFsmState> transition) {
            context.payload().setRollerPower(IntakeSubsystem.HOLD_POWER);
            if (context.timeInState() > 2.0 && !context.payload().isIntakeRequested()) {
                transition.transitionTo(Idle);
            }
        }
    }
}

private final FiniteStateMachine<IntakeFsmState, IntakeSubsystem> fsm = new FiniteStateMachine<>("IntakeFsm", IntakeFsmState.Idle);

public void periodic() {
    fsm.execute(this);
    aKitLog.record("IntakeState", fsm.getCurrentState());
}
  • Constructor Details

    • FiniteStateMachine

      public FiniteStateMachine(String name, StateT initialState)
      Creates a new state machine with no before/after hooks.
      Parameters:
      name - A short, human-readable name for this machine, used in log output.
      initialState - The state the machine starts in. Its enter() runs lazily on the first execute/forceState call.
    • FiniteStateMachine

      public FiniteStateMachine(String name, StateT initialState, FsmHook<StateT,ContextT> beforeHook, FsmHook<StateT,ContextT> finallyHook)
      Creates a new state machine.
      Parameters:
      name - A short, human-readable name for this machine, used in log output.
      initialState - The state the machine starts in. Its enter() runs lazily on the first execute/forceState call.
      beforeHook - Runs on every execute(Object) call, before the current state's execute(). Useful for machine-wide preemptive transitions (e.g. faults) that can fire regardless of which state is currently active. If this hook transitions to a new state, that new state's execute() still runs in the same cycle.
      finallyHook - Runs on every execute(Object) call, after the current state's execute() (and is skipped if the current state's execute() threw). Useful for publishing shared telemetry/outputs regardless of state.
  • Method Details

    • execute

      public void execute(ContextT payload)
      Runs one cycle of the state machine: the before-hook, the current state's execute(), then the after-hook. Intended to be called once per robot loop.
      Parameters:
      payload - The payload for this cycle, typically the subsystem or command that owns this machine.
    • forceState

      public void forceState(StateT newState, ContextT payload)
      Forces a transition to the given state outside of the normal execution cycle (e.g. from tests, or from code external to this machine that needs to reset it). Runs the current state's exit() and the new state's enter(), same as a transition requested from within a hook - unless this is the very first call made against a freshly-constructed machine and newState is already its initial state, in which case only that state's enter() runs once (there is nothing yet to exit).
      Parameters:
      newState - The state to transition to.
      payload - The payload to use for the exit/enter calls this transition triggers.
    • getCurrentState

      public StateT getCurrentState()
      Returns:
      The state the machine is currently in.
    • getPreviousState

      public StateT getPreviousState()
      Returns:
      The state the machine was in immediately prior to its current state. If multiple transitions have cascaded within a single execution cycle (e.g. an entry guard immediately redirecting), this is the most recently exited state in that cascade, not necessarily the state active last cycle.
    • isInState

      public boolean isInState(StateT candidate)
      Parameters:
      candidate - The state to check against.
      Returns:
      True if the machine is currently in the given state.
    • getExecutionsInState

      public long getExecutionsInState()
      Returns:
      The number of times execute(Object) has run against the current state, including the one currently in progress if called from within a hook.
    • getTimeInState

      public double getTimeInState()
      Returns:
      The number of seconds since the current state was entered, per XTimer.