001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.wpilibj2.command;
006
007import static edu.wpi.first.wpilibj.util.ErrorMessages.requireNonNullParam;
008
009import java.util.function.BooleanSupplier;
010import java.util.function.Consumer;
011
012/**
013 * A command that allows the user to pass in functions for each of the basic command methods through
014 * the constructor. Useful for inline definitions of complex commands - note, however, that if a
015 * command is beyond a certain complexity it is usually better practice to write a proper class for
016 * it than to inline it.
017 */
018public class FunctionalCommand extends CommandBase {
019  protected final Runnable m_onInit;
020  protected final Runnable m_onExecute;
021  protected final Consumer<Boolean> m_onEnd;
022  protected final BooleanSupplier m_isFinished;
023
024  /**
025   * Creates a new FunctionalCommand.
026   *
027   * @param onInit the function to run on command initialization
028   * @param onExecute the function to run on command execution
029   * @param onEnd the function to run on command end
030   * @param isFinished the function that determines whether the command has finished
031   * @param requirements the subsystems required by this command
032   */
033  public FunctionalCommand(
034      Runnable onInit,
035      Runnable onExecute,
036      Consumer<Boolean> onEnd,
037      BooleanSupplier isFinished,
038      Subsystem... requirements) {
039    m_onInit = requireNonNullParam(onInit, "onInit", "FunctionalCommand");
040    m_onExecute = requireNonNullParam(onExecute, "onExecute", "FunctionalCommand");
041    m_onEnd = requireNonNullParam(onEnd, "onEnd", "FunctionalCommand");
042    m_isFinished = requireNonNullParam(isFinished, "isFinished", "FunctionalCommand");
043
044    addRequirements(requirements);
045  }
046
047  @Override
048  public void initialize() {
049    m_onInit.run();
050  }
051
052  @Override
053  public void execute() {
054    m_onExecute.run();
055  }
056
057  @Override
058  public void end(boolean interrupted) {
059    m_onEnd.accept(interrupted);
060  }
061
062  @Override
063  public boolean isFinished() {
064    return m_isFinished.getAsBoolean();
065  }
066}