Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Trigger.onChange #69

Merged
merged 1 commit into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions commands2/button/trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,27 @@ def _():

return self

def onChange(self, command: Command) -> Self:
"""
Starts the command when the condition changes.

:param command: the command t start
:returns: this trigger, so calls can be chained
"""

state = SimpleNamespace(pressed_last=self._condition())

@self._loop.bind
def _():
pressed = self._condition()

if state.pressed_last != pressed:
command.schedule()

state.pressed_last = pressed

return self

def whileTrue(self, command: Command) -> Self:
"""
Starts the given command when the condition changes to `True` and cancels it when the condition
Expand Down
17 changes: 17 additions & 0 deletions tests/test_trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ def test_onFalse(scheduler: commands2.CommandScheduler):
assert not command1.isScheduled()


def test_onChange(scheduler: commands2.CommandScheduler):
finished = OOBoolean(False)
command1 = commands2.WaitUntilCommand(finished)

button = InternalButton()
button.setPressed(True)
button.onChange(command1)
scheduler.run()
assert not command1.isScheduled()
button.setPressed(False)
scheduler.run()
assert command1.isScheduled()
finished.set(True)
scheduler.run()
assert not command1.isScheduled()


def test_whileTrueRepeatedly(scheduler: commands2.CommandScheduler):
inits = OOInteger(0)
counter = OOInteger(0)
Expand Down
Loading