Skip to content

Commit 3eac469

Browse files
authored
Add Trigger.onChange (#69)
1 parent 4ca8a52 commit 3eac469

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Diff for: commands2/button/trigger.py

+21
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,27 @@ def _():
122122

123123
return self
124124

125+
def onChange(self, command: Command) -> Self:
126+
"""
127+
Starts the command when the condition changes.
128+
129+
:param command: the command t start
130+
:returns: this trigger, so calls can be chained
131+
"""
132+
133+
state = SimpleNamespace(pressed_last=self._condition())
134+
135+
@self._loop.bind
136+
def _():
137+
pressed = self._condition()
138+
139+
if state.pressed_last != pressed:
140+
command.schedule()
141+
142+
state.pressed_last = pressed
143+
144+
return self
145+
125146
def whileTrue(self, command: Command) -> Self:
126147
"""
127148
Starts the given command when the condition changes to `True` and cancels it when the condition

Diff for: tests/test_trigger.py

+17
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,23 @@ def test_onFalse(scheduler: commands2.CommandScheduler):
4242
assert not command1.isScheduled()
4343

4444

45+
def test_onChange(scheduler: commands2.CommandScheduler):
46+
finished = OOBoolean(False)
47+
command1 = commands2.WaitUntilCommand(finished)
48+
49+
button = InternalButton()
50+
button.setPressed(True)
51+
button.onChange(command1)
52+
scheduler.run()
53+
assert not command1.isScheduled()
54+
button.setPressed(False)
55+
scheduler.run()
56+
assert command1.isScheduled()
57+
finished.set(True)
58+
scheduler.run()
59+
assert not command1.isScheduled()
60+
61+
4562
def test_whileTrueRepeatedly(scheduler: commands2.CommandScheduler):
4663
inits = OOInteger(0)
4764
counter = OOInteger(0)

0 commit comments

Comments
 (0)