blob: 6d36086a50c67e0fc213e2261030504a72cd06e3 [file] [log] [blame]
Brian Silvermanf7f267a2017-02-04 16:16:08 -08001/*----------------------------------------------------------------------------*/
2/* Copyright (c) FIRST 2017. All Rights Reserved. */
3/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in the root directory of */
5/* the project. */
6/*----------------------------------------------------------------------------*/
7
8#include "Commands/ConditionalCommand.h"
9
10#include "Commands/Scheduler.h"
11
12using namespace frc;
13
14/**
15 * Creates a new ConditionalCommand with given onTrue and onFalse Commands.
16 *
17 * @param onTrue The Command to execute if {@link
18 * ConditionalCommand#Condition()} returns true
19 * @param onFalse The Command to execute if {@link
20 * ConditionalCommand#Condition()} returns false
21 */
22ConditionalCommand::ConditionalCommand(Command* onTrue, Command* onFalse) {
23 m_onTrue = onTrue;
24 m_onFalse = onFalse;
25
26 for (auto requirement : m_onTrue->GetRequirements()) Requires(requirement);
27 for (auto requirement : m_onFalse->GetRequirements()) Requires(requirement);
28}
29
30/**
31 * Creates a new ConditionalCommand with given onTrue and onFalse Commands.
32 *
33 * @param name the name for this command group
34 * @param onTrue The Command to execute if {@link
35 * ConditionalCommand#Condition()} returns true
36 * @param onFalse The Command to execute if {@link
37 * ConditionalCommand#Condition()} returns false
38 */
39ConditionalCommand::ConditionalCommand(const std::string& name, Command* onTrue,
40 Command* onFalse)
41 : Command(name) {
42 m_onTrue = onTrue;
43 m_onFalse = onFalse;
44
45 for (auto requirement : m_onTrue->GetRequirements()) Requires(requirement);
46 for (auto requirement : m_onFalse->GetRequirements()) Requires(requirement);
47}
48
49void ConditionalCommand::_Initialize() {
50 if (Condition()) {
51 m_chosenCommand = m_onTrue;
52 } else {
53 m_chosenCommand = m_onFalse;
54 }
55
56 /*
57 * This is a hack to make cancelling the chosen command inside a CommandGroup
58 * work properly
59 */
60 m_chosenCommand->ClearRequirements();
61
62 m_chosenCommand->Start();
63}
64
65void ConditionalCommand::_Cancel() {
66 if (m_chosenCommand != nullptr && m_chosenCommand->IsRunning()) {
67 m_chosenCommand->Cancel();
68 }
69
70 Command::_Cancel();
71}
72
73bool ConditionalCommand::IsFinished() {
74 return m_chosenCommand != nullptr && m_chosenCommand->IsRunning() &&
75 m_chosenCommand->IsFinished();
76}
77
78void ConditionalCommand::Interrupted() {
79 if (m_chosenCommand != nullptr && m_chosenCommand->IsRunning()) {
80 m_chosenCommand->Cancel();
81 }
82
83 Command::Interrupted();
84}