forked from robotpy/robotpy-commands-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconditionalcommand.py
61 lines (43 loc) · 1.89 KB
/
conditionalcommand.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from __future__ import annotations
from typing import Callable
from .command import Command
from .commandgroup import *
from .commandscheduler import CommandScheduler
class ConditionalCommand(Command):
"""
A command composition that runs one of two commands, depending on the value of the given
condition when this command is initialized.
The rules for command compositions apply: command instances that are passed to it cannot be
added to any other composition or scheduled individually, and the composition requires all
subsystems its components require.
This class is provided by the NewCommands VendorDep"""
selectedCommand: Command
def __init__(
self, onTrue: Command, onFalse: Command, condition: Callable[[], bool]
):
"""
Creates a new ConditionalCommand.
:param onTrue: the command to run if the condition is true
:param onFalse: the command to run if the condition is false
:param condition: the condition to determine which command to run"""
super().__init__()
CommandScheduler.getInstance().registerComposedCommands([onTrue, onFalse])
self.onTrue = onTrue
self.onFalse = onFalse
self.condition = condition
self.addRequirements(*onTrue.getRequirements())
self.addRequirements(*onFalse.getRequirements())
def initialize(self):
if self.condition():
self.selectedCommand = self.onTrue
else:
self.selectedCommand = self.onFalse
self.selectedCommand.initialize()
def execute(self):
self.selectedCommand.execute()
def isFinished(self) -> bool:
return self.selectedCommand.isFinished()
def end(self, interrupted: bool):
self.selectedCommand.end(interrupted)
def runsWhenDisabled(self) -> bool:
return self.onTrue.runsWhenDisabled() and self.onFalse.runsWhenDisabled()