[commands] Add Trigger.onChange() (#6390)

This commit is contained in:
Jacob Hotz
2024-04-22 00:37:15 -05:00
committed by GitHub
parent b620b6a4dd
commit dc4c63568a
3 changed files with 71 additions and 0 deletions

View File

@@ -13,6 +13,34 @@ using namespace frc2;
Trigger::Trigger(const Trigger& other) = default;
Trigger Trigger::OnChange(Command* command) {
m_loop->Bind(
[condition = m_condition, previous = m_condition(), command]() mutable {
bool current = condition();
if (previous != current) {
command->Schedule();
}
previous = current;
});
return *this;
}
Trigger Trigger::OnChange(CommandPtr&& command) {
m_loop->Bind([condition = m_condition, previous = m_condition(),
command = std::move(command)]() mutable {
bool current = condition();
if (previous != current) {
command.Schedule();
}
previous = current;
});
return *this;
}
Trigger Trigger::OnTrue(Command* command) {
m_loop->Bind(
[condition = m_condition, previous = m_condition(), command]() mutable {

View File

@@ -57,6 +57,23 @@ class Trigger {
Trigger(const Trigger& other);
/**
* Starts the command when the condition changes.
*
* @param command the command to start
* @return this trigger, so calls can be chained
*/
Trigger OnChange(Command* command);
/**
* Starts the command when the condition changes. Moves command ownership to
* the button scheduler.
*
* @param command the command to start
* @return this trigger, so calls can be chained
*/
Trigger OnChange(CommandPtr&& command);
/**
* Starts the given command whenever the condition changes from `false` to
* `true`.