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.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 *
018 * <p>This class is provided by the NewCommands VendorDep
019 */
020public class FunctionalCommand extends CommandBase {
021  protected final Runnable m_onInit;
022  protected final Runnable m_onExecute;
023  protected final Consumer<Boolean> m_onEnd;
024  protected final BooleanSupplier m_isFinished;
025
026  /**
027   * Creates a new FunctionalCommand.
028   *
029   * @param onInit the function to run on command initialization
030   * @param onExecute the function to run on command execution
031   * @param onEnd the function to run on command end
032   * @param isFinished the function that determines whether the command has finished
033   * @param requirements the subsystems required by this command
034   */
035  public FunctionalCommand(
036      Runnable onInit,
037      Runnable onExecute,
038      Consumer<Boolean> onEnd,
039      BooleanSupplier isFinished,
040      Subsystem... requirements) {
041    m_onInit = requireNonNullParam(onInit, "onInit", "FunctionalCommand");
042    m_onExecute = requireNonNullParam(onExecute, "onExecute", "FunctionalCommand");
043    m_onEnd = requireNonNullParam(onEnd, "onEnd", "FunctionalCommand");
044    m_isFinished = requireNonNullParam(isFinished, "isFinished", "FunctionalCommand");
045
046    addRequirements(requirements);
047  }
048
049  @Override
050  public void initialize() {
051    m_onInit.run();
052  }
053
054  @Override
055  public void execute() {
056    m_onExecute.run();
057  }
058
059  @Override
060  public void end(boolean interrupted) {
061    m_onEnd.accept(interrupted);
062  }
063
064  @Override
065  public boolean isFinished() {
066    return m_isFinished.getAsBoolean();
067  }
068}