blob: 3d7d2acd916651049eac6dfba850943e3caab304 [file] [log] [blame]
Brian Silvermanf7f267a2017-02-04 16:16:08 -08001/*----------------------------------------------------------------------------*/
2/* Copyright (c) FIRST 2011-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/Command.h"
9
10#include <typeinfo>
11
12#include "Commands/CommandGroup.h"
13#include "Commands/Scheduler.h"
14#include "RobotState.h"
15#include "Timer.h"
16#include "WPIErrors.h"
17
18using namespace frc;
19
20static const std::string kName = "name";
21static const std::string kRunning = "running";
22static const std::string kIsParented = "isParented";
23
24int Command::m_commandCounter = 0;
25
26/**
27 * Creates a new command.
28 * The name of this command will be default.
29 */
30Command::Command() : Command("", -1.0) {}
31
32/**
33 * Creates a new command with the given name and no timeout.
34 *
35 * @param name the name for this command
36 */
37Command::Command(const std::string& name) : Command(name, -1.0) {}
38
39/**
40 * Creates a new command with the given timeout and a default name.
41 *
42 * @param timeout the time (in seconds) before this command "times out"
43 * @see Command#isTimedOut() isTimedOut()
44 */
45Command::Command(double timeout) : Command("", timeout) {}
46
47/**
48 * Creates a new command with the given name and timeout.
49 *
50 * @param name the name of the command
51 * @param timeout the time (in seconds) before this command "times out"
52 * @see Command#isTimedOut() isTimedOut()
53 */
54Command::Command(const std::string& name, double timeout) {
55 // We use -1.0 to indicate no timeout.
56 if (timeout < 0.0 && timeout != -1.0)
57 wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
58
59 m_timeout = timeout;
60
61 // If name contains an empty string
62 if (name.length() == 0) {
63 m_name = std::string("Command_") + std::string(typeid(*this).name());
64 } else {
65 m_name = name;
66 }
67}
68
69Command::~Command() {
70 if (m_table != nullptr) m_table->RemoveTableListener(this);
71}
72
73/**
74 * Get the ID (sequence number) for this command.
75 *
76 * The ID is a unique sequence number that is incremented for each command.
77 *
78 * @return the ID of this command
79 */
80int Command::GetID() const { return m_commandID; }
81
82/**
83 * Sets the timeout of this command.
84 *
85 * @param timeout the timeout (in seconds)
86 * @see Command#isTimedOut() isTimedOut()
87 */
88void Command::SetTimeout(double timeout) {
89 if (timeout < 0.0)
90 wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0");
91 else
92 m_timeout = timeout;
93}
94
95/**
96 * Returns the time since this command was initialized (in seconds).
97 *
98 * This function will work even if there is no specified timeout.
99 *
100 * @return the time since this command was initialized (in seconds).
101 */
102double Command::TimeSinceInitialized() const {
103 if (m_startTime < 0.0)
104 return 0.0;
105 else
106 return Timer::GetFPGATimestamp() - m_startTime;
107}
108
109/**
110 * This method specifies that the given {@link Subsystem} is used by this
111 * command.
112 *
113 * This method is crucial to the functioning of the Command System in general.
114 *
115 * <p>Note that the recommended way to call this method is in the
116 * constructor.</p>
117 *
118 * @param subsystem the {@link Subsystem} required
119 * @see Subsystem
120 */
121void Command::Requires(Subsystem* subsystem) {
122 if (!AssertUnlocked("Can not add new requirement to command")) return;
123
124 if (subsystem != nullptr)
125 m_requirements.insert(subsystem);
126 else
127 wpi_setWPIErrorWithContext(NullParameter, "subsystem");
128}
129
130/**
131 * Called when the command has been removed.
132 *
133 * This will call {@link Command#interrupted() interrupted()} or
134 * {@link Command#end() end()}.
135 */
136void Command::Removed() {
137 if (m_initialized) {
138 if (IsCanceled()) {
139 Interrupted();
140 _Interrupted();
141 } else {
142 End();
143 _End();
144 }
145 }
146 m_initialized = false;
147 m_canceled = false;
148 m_running = false;
149 if (m_table != nullptr) m_table->PutBoolean(kRunning, false);
150}
151
152/**
153 * Starts up the command. Gets the command ready to start.
154 *
155 * <p>Note that the command will eventually start, however it will not
156 * necessarily do so immediately, and may in fact be canceled before initialize
157 * is even called.</p>
158 */
159void Command::Start() {
160 LockChanges();
161 if (m_parent != nullptr)
162 wpi_setWPIErrorWithContext(
163 CommandIllegalUse,
164 "Can not start a command that is part of a command group");
165
166 Scheduler::GetInstance()->AddCommand(this);
167}
168
169/**
170 * The run method is used internally to actually run the commands.
171 *
172 * @return whether or not the command should stay within the {@link Scheduler}.
173 */
174bool Command::Run() {
175 if (!m_runWhenDisabled && m_parent == nullptr && RobotState::IsDisabled())
176 Cancel();
177
178 if (IsCanceled()) return false;
179
180 if (!m_initialized) {
181 m_initialized = true;
182 StartTiming();
183 _Initialize();
184 Initialize();
185 }
186 _Execute();
187 Execute();
188 return !IsFinished();
189}
190
191/**
192 * The initialize method is called the first time this Command is run after
193 * being started.
194 */
195void Command::Initialize() {}
196
197/**
198 * The execute method is called repeatedly until this Command either finishes
199 * or is canceled.
200 */
201void Command::Execute() {}
202
203/**
204 * Called when the command ended peacefully. This is where you may want
205 * to wrap up loose ends, like shutting off a motor that was being used
206 * in the command.
207 */
208void Command::End() {}
209
210/**
211 * Called when the command ends because somebody called
212 * {@link Command#cancel() cancel()} or another command shared the same
213 * requirements as this one, and booted it out.
214 *
215 * <p>This is where you may want to wrap up loose ends, like shutting off a
216 * motor that was being used in the command.</p>
217 *
218 * <p>Generally, it is useful to simply call the {@link Command#end() end()}
219 * method within this method, as done here.</p>
220 */
221void Command::Interrupted() { End(); }
222
223void Command::_Initialize() {}
224
225void Command::_Interrupted() {}
226
227void Command::_Execute() {}
228
229void Command::_End() {}
230
231/**
232 * Called to indicate that the timer should start.
233 *
234 * This is called right before {@link Command#initialize() initialize()} is,
235 * inside the {@link Command#run() run()} method.
236 */
237void Command::StartTiming() { m_startTime = Timer::GetFPGATimestamp(); }
238
239/**
240 * Returns whether or not the
241 * {@link Command#timeSinceInitialized() timeSinceInitialized()} method returns
242 * a number which is greater than or equal to the timeout for the command.
243 *
244 * If there is no timeout, this will always return false.
245 *
246 * @return whether the time has expired
247 */
248bool Command::IsTimedOut() const {
249 return m_timeout != -1 && TimeSinceInitialized() >= m_timeout;
250}
251
252/**
253 * Returns the requirements (as an std::set of {@link Subsystem Subsystems}
254 * pointers) of this command.
255 *
256 * @return the requirements (as an std::set of {@link Subsystem Subsystems}
257 * pointers) of this command
258 */
259Command::SubsystemSet Command::GetRequirements() const {
260 return m_requirements;
261}
262
263/**
264 * Prevents further changes from being made.
265 */
266void Command::LockChanges() { m_locked = true; }
267
268/**
269 * If changes are locked, then this will generate a CommandIllegalUse error.
270 *
271 * @param message the message to report on error (it is appended by a default
272 * message)
273 * @return true if assert passed, false if assert failed
274 */
275bool Command::AssertUnlocked(const std::string& message) {
276 if (m_locked) {
277 std::string buf =
278 message + " after being started or being added to a command group";
279 wpi_setWPIErrorWithContext(CommandIllegalUse, buf);
280 return false;
281 }
282 return true;
283}
284
285/**
286 * Sets the parent of this command. No actual change is made to the group.
287 *
288 * @param parent the parent
289 */
290void Command::SetParent(CommandGroup* parent) {
291 if (parent == nullptr) {
292 wpi_setWPIErrorWithContext(NullParameter, "parent");
293 } else if (m_parent != nullptr) {
294 wpi_setWPIErrorWithContext(CommandIllegalUse,
295 "Can not give command to a command group after "
296 "already being put in a command group");
297 } else {
298 LockChanges();
299 m_parent = parent;
300 if (m_table != nullptr) {
301 m_table->PutBoolean(kIsParented, true);
302 }
303 }
304}
305
306/**
307 * Clears list of subsystem requirements. This is only used by
308 * {@link ConditionalCommand} so cancelling the chosen command works properly in
309 * {@link CommandGroup}.
310 */
311void Command::ClearRequirements() { m_requirements.clear(); }
312
313/**
314 * This is used internally to mark that the command has been started.
315 *
316 * The lifecycle of a command is:
317 *
318 * startRunning() is called.
319 * run() is called (multiple times potentially)
320 * removed() is called
321 *
322 * It is very important that startRunning and removed be called in order or some
323 * assumptions of the code will be broken.
324 */
325void Command::StartRunning() {
326 m_running = true;
327 m_startTime = -1;
328 if (m_table != nullptr) m_table->PutBoolean(kRunning, true);
329}
330
331/**
332 * Returns whether or not the command is running.
333 *
334 * This may return true even if the command has just been canceled, as it may
335 * not have yet called {@link Command#interrupted()}.
336 *
337 * @return whether or not the command is running
338 */
339bool Command::IsRunning() const { return m_running; }
340
341/**
342 * This will cancel the current command.
343 *
344 * <p>This will cancel the current command eventually. It can be called
345 * multiple times. And it can be called when the command is not running. If
346 * the command is running though, then the command will be marked as canceled
347 * and eventually removed.</p>
348 *
349 * <p>A command can not be canceled if it is a part of a command group, you
350 * must cancel the command group instead.</p>
351 */
352void Command::Cancel() {
353 if (m_parent != nullptr)
354 wpi_setWPIErrorWithContext(
355 CommandIllegalUse,
356 "Can not cancel a command that is part of a command group");
357
358 _Cancel();
359}
360
361/**
362 * This works like cancel(), except that it doesn't throw an exception if it is
363 * a part of a command group.
364 *
365 * Should only be called by the parent command group.
366 */
367void Command::_Cancel() {
368 if (IsRunning()) m_canceled = true;
369}
370
371/**
372 * Returns whether or not this has been canceled.
373 *
374 * @return whether or not this has been canceled
375 */
376bool Command::IsCanceled() const { return m_canceled; }
377
378/**
379 * Returns whether or not this command can be interrupted.
380 *
381 * @return whether or not this command can be interrupted
382 */
383bool Command::IsInterruptible() const { return m_interruptible; }
384
385/**
386 * Sets whether or not this command can be interrupted.
387 *
388 * @param interruptible whether or not this command can be interrupted
389 */
390void Command::SetInterruptible(bool interruptible) {
391 m_interruptible = interruptible;
392}
393
394/**
395 * Checks if the command requires the given {@link Subsystem}.
396 *
397 * @param system the system
398 * @return whether or not the subsystem is required (false if given nullptr)
399 */
400bool Command::DoesRequire(Subsystem* system) const {
401 return m_requirements.count(system) > 0;
402}
403
404/**
405 * Returns the {@link CommandGroup} that this command is a part of.
406 *
407 * Will return null if this {@link Command} is not in a group.
408 *
409 * @return the {@link CommandGroup} that this command is a part of (or null if
410 * not in group)
411 */
412CommandGroup* Command::GetGroup() const { return m_parent; }
413
414/**
415 * Sets whether or not this {@link Command} should run when the robot is
416 * disabled.
417 *
418 * <p>By default a command will not run when the robot is disabled, and will in
419 * fact be canceled.</p>
420 *
421 * @param run whether or not this command should run when the robot is disabled
422 */
423void Command::SetRunWhenDisabled(bool run) { m_runWhenDisabled = run; }
424
425/**
426 * Returns whether or not this {@link Command} will run when the robot is
427 * disabled, or if it will cancel itself.
428 *
429 * @return whether or not this {@link Command} will run when the robot is
430 * disabled, or if it will cancel itself
431 */
432bool Command::WillRunWhenDisabled() const { return m_runWhenDisabled; }
433
434std::string Command::GetName() const { return m_name; }
435
436std::string Command::GetSmartDashboardType() const { return "Command"; }
437
438void Command::InitTable(std::shared_ptr<ITable> subtable) {
439 if (m_table != nullptr) m_table->RemoveTableListener(this);
440 m_table = subtable;
441 if (m_table != nullptr) {
442 m_table->PutString(kName, GetName());
443 m_table->PutBoolean(kRunning, IsRunning());
444 m_table->PutBoolean(kIsParented, m_parent != nullptr);
445 m_table->AddTableListener(kRunning, this, false);
446 }
447}
448
449std::shared_ptr<ITable> Command::GetTable() const { return m_table; }
450
451void Command::ValueChanged(ITable* source, llvm::StringRef key,
452 std::shared_ptr<nt::Value> value, bool isNew) {
453 if (!value->IsBoolean()) return;
454 if (value->GetBoolean()) {
455 if (!IsRunning()) Start();
456 } else {
457 if (IsRunning()) Cancel();
458 }
459}