Skip to content

Commit

Permalink
Add Trigger.onChange (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
spacey-sooty authored Jun 27, 2024
1 parent 4ca8a52 commit 3eac469
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
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

0 comments on commit 3eac469

Please sign in to comment.