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 Command {
021  private final Runnable m_onInit;
022  private final Runnable m_onExecute;
023  private final Consumer<Boolean> m_onEnd;
024  private 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  @SuppressWarnings("this-escape")
036  public FunctionalCommand(
037      Runnable onInit,
038      Runnable onExecute,
039      Consumer<Boolean> onEnd,
040      BooleanSupplier isFinished,
041      Subsystem... requirements) {
042    m_onInit = requireNonNullParam(onInit, "onInit", "FunctionalCommand");
043    m_onExecute = requireNonNullParam(onExecute, "onExecute", "FunctionalCommand");
044    m_onEnd = requireNonNullParam(onEnd, "onEnd", "FunctionalCommand");
045    m_isFinished = requireNonNullParam(isFinished, "isFinished", "FunctionalCommand");
046
047    addRequirements(requirements);
048  }
049
050  @Override
051  public void initialize() {
052    m_onInit.run();
053  }
054
055  @Override
056  public void execute() {
057    m_onExecute.run();
058  }
059
060  @Override
061  public void end(boolean interrupted) {
062    m_onEnd.accept(interrupted);
063  }
064
065  @Override
066  public boolean isFinished() {
067    return m_isFinished.getAsBoolean();
068  }
069}