|
| 1 | +# Custom Commands |
| 2 | + |
| 3 | +While NextFTC includes many useful commands, |
| 4 | +you often will need to create your own. |
| 5 | + |
| 6 | +The recommended way to create a command is by using the `LambdaCommand` class, |
| 7 | +which allows you to define the command's behavior using lambda functions. |
| 8 | +This approach is concise and flexible, making it easy to create custom commands |
| 9 | +without needing to create a new class for each command. |
| 10 | + |
| 11 | +Here is how the builtin `RunToPosition` command could |
| 12 | +be implemented using `LambdaCommand`: |
| 13 | + |
| 14 | +::: tabs key:code |
| 15 | + |
| 16 | +== Java |
| 17 | +```java |
| 18 | +public static Command runToPosition(ControlSystem system, double position, KineticState tolerance) { |
| 19 | + return new LambdaCommand("RunToPosition(" + position + ")") |
| 20 | + .setStart(() -> system.setGoal(new KineticState(position))) |
| 21 | + .setIsDone(() -> system.isWithinTolerance(tolerance)) |
| 22 | + .requires(system); |
| 23 | +{ |
| 24 | +``` |
| 25 | + |
| 26 | +Because Java doesn't have default parameters, |
| 27 | +we must make another method to use a default tolerance. |
| 28 | +This example uses a tolerance of 10.0: |
| 29 | +
|
| 30 | +```java |
| 31 | +public static Command runToPosition(ControlSystem system, double position) { |
| 32 | + return runToPosition(system, position, new KineticState(10.0)); |
| 33 | +} |
| 34 | +``` |
| 35 | +
|
| 36 | +== Kotlin |
| 37 | +```kotlin |
| 38 | +fun runToPosition( |
| 39 | + system: ControlSystem, |
| 40 | + position: Double, |
| 41 | + tolerance: KineticState = KineticState(10.0) |
| 42 | +) = LambdaCommand("RunToPosition($position)") |
| 43 | + .setStart { system.goal = KineticState(position) } |
| 44 | + .setIsDone { system.isWithinTolerance(tolerance) } |
| 45 | + .requires(system) |
| 46 | +``` |
| 47 | +
|
| 48 | +::: |
| 49 | +
|
| 50 | +The `setStart`, `setUpdate`, `setIsDone`, and `setStop` |
| 51 | +methods directly map to the methods of the `Command` class. |
0 commit comments