Uncategorized

Command-Based Programs with RobotBuilder

How to create a command-based robot program? There are two ways: start with the Command Robot template or use RobotBuilder.

RobotBuilder is a tool provided with WPILib for constructing robot programs conforming to the command-based application architecture. This is a tool you use when first start constructing your program. It also provides round trip engineering, which means you can switch back and forth between RobotBuilder and Visual Studio Code. RobotBuilder has a number of advantages over using the Command Robot template built into Visual Studio Code:

  • RobotBuilder forces a top-down approach design approach. You first map out the high-level structures before diving into specific code.
  • It generates a correct command-based structure. When building from the template, there is some risk of getting the concepts wrong.
  • RobotBuilder is fast, so you watch the construction of a full program over just an hour. This would allow every programmer to write their own program for experimentation. It becomes plausible to create multiple robot programs and throw away the ones that aren’t prefect.

RobotBuilder just creates the infrastructure, so there will still be plenty of work for the programmers. It gets you started. By the end of the season, most of your code will be non-RobotBuilder code.

The following discusses deploying in Java, but C++ robot programs can be constructed in the same way.

Starting a RobotBuilder Project

You can start RobotBuilder from within Visual Studio Code. Open the Command Palette menu by hitting control-shift-P (or command-shift-P on a Macintosh). Select “WPILib: Start Tool”. A new menu of all the WPILib tools will appear. Select “RobotBuilder”. If you have previously used RobotBuilder, it will open directly into your most recent project. If this is your first time, you will get a dialog asking your project name and team number.

When you first start a project, I recommend you do the following steps first:

  1. Click on the Export Directory. A file dialog will pop up to define which folder your project will be saved into. Specify that you want to “Use Absolute Path”. Select your Documents folder and hit the “Select Folder” button.
  2. Under the Export menu, select Java. This will cause a new project folder to be created in your Documents folder.
  3. Under the File menu, select Save. A file dialog will pop up. Navigate to your documents Directory and then into your new project folder. Save your RobotBuilder config file as “robot.yml”.
  4. Click on the Export Directory again. Change the dialog to “Use path relative”, and then select the Documents directory again.
  5. Click on Wiring File Location, which pops up another file dialog. Navigate to your Documents directory, select your project folder, and click the “Select Folder” button.
  6. Under the File menu, select Save again.

The above procedure will cause all file paths relative to the RobotBuilder save file. This will allow the project to work properly even if it is copied to another computer, or is cloned from git.

Naming Conventions

When you name things within RobotBuilder, you will be creating class names and variables in your code. You’ll want to pick names that work with your language’s naming conventions.

  • Subsystems will be classes, so they should start with a capital letter. It’s a good practice if the name ends in the word “Subsystem”. For example, ClimberSubsystem or ShooterSubsystem.
  • Commands will also be classes, so they should also start with a capital letter. A good practice is to end all command names with the word “Command” and begin command names with the primary subsystem. For example, ClimberUpCommand or ShooterShootCommand.
  • Other components within RobotBuilder will be variables, so they should start with a lower case letter. RobotBuilder will allow you to put spaces in names, but this is a bad practice; don’t do it. Make variables clear about what they represent. For example, leftClimberSolenoid or shooterMotor or forwardRangefinder.

Subsystems

Suppose that your new robot has a subsystem for shooting balls using a spinning wheel. This subsystem has a SparkMax motor controller attached to PWM channel 1. The subsystem also has a pneumatic piston for pushing balls into the wheel. The piston is operated by a double solenoid connected to channels 6 and 7 of a CTRE pneumatics control module. To create a subsystem class in code:

  1. Right-click on the Subsystems folder and select “Add Subsystem”. This will create a new folder under Subsytems.
  2. Click on the new folder to select it. Change its name to ShooterSubsystem.
  3. Right-click on the new ShooterSubsystem folder and select “Add Actuators” and then “Add Motor Controller”. This will create a new icon for the motor controller.
  4. Click on the new motor controller icon. Change its name to shooterWheelMotor. Change the motor controller type to PWMSparkMax and then set its output channel to 1.
  5. Right-click on the new ShooterSubsystem folder again and select “Add Pneumatics” and then “Add Double Solenoid”.
  6. Click on the new solenoid icon. Change its name to ballPusherSolenoid. Set forward channel to 6 and its reverse channel to 7. Make sure the module type is CTREPCM.
  7. Under the File menu select “Save”. Under Export menu select “Java”.

At this point you have a command-based robot program with one subsystem. You can go back to Visual Studio Code and open the new folder for your project. Take a look at the new ShooterSubsystem class. You’ll see private variables pointing to the motor controller and the solenoid.

At the bottom of the ShooterSubsystem class, add these three methods:

    public void setWheelSpeed(double speed) {
        shooterWheelMotor.set(speed);
    }

    public void pushBall() {
        ballPusherSolenoid.set(DoubleSolenoid.Value.kForward);
    }

    public void retractPiston() {
        ballPusherSolenoid.set(DoubleSolenoid.Value.kReverse);
    }

These three methods will allow outside access to the private components inside ShooterSubsystem.

Commands

Go back to RobotBuilder. Create a method for setting the spinning wheel speed.

  1. Right-click on the Commands folder and select “Add Command”.
  2. Click on the new command icon. Change the command’s name to “ShooterSpinCommand”.
  3. Specify that this new command requires the ShooterSubsystem.
  4. Add a new parameter named “speed” of type “double”.
  5. Save everything and then export java code again.

Go back into Visual Studio Code and open the new ShooterSpinCommand class. Change the isFinished method so it always returns true. Then change the initialize method so it looks like this:

    @Override
    public void initialize() {
        m_shooterSubsystem.setWheelSpeed(m_speed);
    }

Next in RobotBuilder, create a command to extend the ball pusher piston:

  1. Right-click on the Commands folder and select “Add Command”.
  2. Click on the new command icon. Change the command’s name to “ShooterPushCommand”.
  3. Specify that this new command requires the ShooterSubsystem.

Now, repeat these three steps for a ShooterRetractCommand. Save and Export.

Switch to Visual Studio Code and open the two new commands. For both of them, the isFinished method should return true. For each of them, modify the initialize method to call the appropriate method within the ShooterSubsystem.

Operator Interfaces

Now we can create buttons to start the commands:

  1. Right-click on the Operator Interface folder and select “Add Xbox Controller”. Click on the new icon and rename it to just “xbox”.
  2. Right-click on the new “xbox” folder and choose “Add Xbox Button”. Click on the new button icon and rename it to “shooterPushButton”. Specify button “Y” and then specify the ShooterPushCommand.
  3. Add another XBox Button. Click on the new button icon and rename it to “shooterRetractButton”. Specify button “A” and then specify the ShooterRetractCommand.
  4. Add another XBox Button. Click on the new button icon and rename it to “shooterSpinButton”. Specify button “B” and then specify the ShooterSpinCommand. Click on the parameter area and specify that the speed should be 1.0.
  5. Add another XBox Button. Click on the new button icon and rename it to “shooterStopButton”. Specify button “X” and then specify the ShooterSpinCommand. You don’t have to specify a speed parameter for this button, since the default value is zero.
  6. Save and Export code.

You can return to Visual Studio Code and examine all the button setup within the RobotContainer class.

Cleanup of RobotBuilder code

There are a couple of frustrations you will encounter using RobotBuilder.

  • The code is often not indented correctly. You should use the auto formatter in Visual Studio Code to correct this.
  • The code is filled with messy comments which help implement the round trip engineering.
  • The round trip engineering will usually break down as programmers add their own classes, or delete classes or rename things.

Although RobotBuilder will get you started, you probably won’t use it for the full season. So, a good practice is to clean up the code after a week or two of development. Auto format each class. Delete all the messy comments. Clean out the unused import statements. Make it beautiful, because code should be easy to read.

RobotBuilder Extensions

One problem you might have already noticed is that RobotBuilder might not contain all the components you want to use on your robot. In particular, you might notice that motor controls from REV Robotics or CTRE are missing. Fortunately RobotBuilder allows extensions to be added for missing parts. These extension files should be put into a folder called RobotBuilder/extensions under your wpilib directory.

One source of extensions is at https://github.com/firstmncsa/Robotbuilder-Extensions.git. Clone this repository and the drag the files into your extensions folder.

You may also need to add 3rd party extension files into the vendordeps folder of your project. You can do this from with Visual Studio Code by opening the Command Palette and selecting Manage Vendor Libraries / Install New Libraries Offline. The vendor library URLs change every year, but for 2023 they are:

Further Reading:

Uncategorized

Command-Based Robot Architecture

It is possible to write simple robot programs in a single Robot class, using the simple TimedRobot template. However, as your program grows, the complexity can snowball. You’re better off if your overall program is designed to be scalable. Scalability is an engineering concept where we observe how problems and solutions change as they grow. You want your program to scale gracefully as it adds functions. You may also want to be able to scale up the number of programmers, so multiple people can work comfortably on separate parts of the code.

A recommended pattern for organizing robot programs for FIRST is the command-based framework.

Command Based Framework

When creating a command-based robot program, we define three types of software:

  • Subsystem classes represent major physical parts of your robot, such as a drive train, shooter, game-piece collector, or climber.
  • Command classes represent major actions that subsystems can do, such as driving, shooting, acquiring, or climbing.
  • Operator interface objects start commands executing on the subsystems. Think of joystick buttons, or custom trigger objects.

For a command-based program these bits of software will work within a standardized software project. Within this framework there is another object called the CommandScheduler, which will handle the lifecycle of commands. The CommandScheduler monitors buttons and triggers. It starts and manages the commands.

At the top level of your project will be three important class files:

  • Main, which starts the whole program. Don’t make any changes to this file.
  • RobotContainer, which is in charge of creating the objects from the subsystem and command classes, and connecting them with operator interfaces.
  • Robot, which handles the lifecycle timing. It will initiate robot initialization calls into the RobotContainer class. It also handles transitions in and out of teleop and autonomous modes, and causes the CommandScheduler to execute.

Separating robot functions out into these three classes is an example of Separation of Concerns, a software engineering principle in which we divide different functions into different areas.

Subsystems

Subsystems represent physical parts of your robot. Think about the physical components that you may manipulate from your program. A subsystem might contain:

  • Motors, and their associated motor controllers and sometimes encoders
  • Pneumatic pistons, and their associated solenoids
  • Servos
  • Relays or Spikes
  • Gyros or Inertial Management Units
  • Cameras
  • Sensors, including ultrasonic sensors, limit switches or potentiometers

Each subsystem class will contain software objects connecting to those physical objects. For instance, if a drive train subsystem has two physical motors, then the DriveTrainSubsystem class will contain two motor controller objects. Typically we make those objects private, meaning that they may not be accessed directly from the outside.

To allow access to the internal components, we next define functions in the subsystem that allow component access. For instance, we might add a function that sets the speed of a shooter motor or another function that causes pneumatic solenoids to push a ball into the shooter. One important quality of these functions is that each one must be quick, only taking a tiny amount of time.

The practice of making internals private but then exposing high-level actions through functions is another software engineering principal called Ecapsulation. Encapsulation hides internal complexity, allowing the overall program to be less complex.

Commands

Commands execute actions on subsystems. Most commands operate only on a single subsystem, but it is possible to run a command on multiple subsystems. When a command operates on a subsystem, we say that the command requires that subsystem. There are three important rules for commands:

  1. A subsystem can only run one command at a time.
  2. If a subsystem is running one command but then another command starts on that subsystem, the first command will be interrupted. We call this action interrupting, but the first command will be completely stopped.
    For instance, suppose the robot is turning clockwise, but then you initiate a command to turn counter-clockwise. It is impossible to do both at the same time, and the second command is what you really want. The clockwise command will be stopped and the counter-clockwise command will start up.
  3. A subsystem may have a default command that runs whenever no other commands are scheduled.
    For instance, a drivetrain subsystem typically has a default driving command that allows joysticks to drive the robot. If we initiate a command to rotate the robot ninety degrees clockwise, then the driving command will be interrupted until the rotate command finishes. The default command will start up again as soon as the turn command is finished.

Some commands will be “instant commands”, meaning that they initiate some simple action and then end immediately. For instance, a command to set the speed on a shooter wheel will do just that, and then end.

Other commands have a lifecycle that can span a much longer period of time. These command have an initialization function when they start, and then an execution function that is run repeatedly until the command is finished, and then a finalization function to run when the command is finished. Each of these functions must be quick and time a tiny amount of time, but the overall life of the command may take many seconds.

Note that you can also combine commands into command groups. One command group can cause multiple commands to run in sequence or in parallel.

Operator Interfaces

The most common way of initiating a command is to attach it to a joystick button. Pressing that button schedules the command and it will start running. You can also cause a command to start when the button is released, or to execute only while the button is held down. You can allow a button to toggle on or off. You can also define combinations of buttons, so commands start when you press multiple buttons. There is a lot of flexibility available.

You can also define custom trigger objects that initiate commands. You could define triggers that start commands whenever certain conditions become true, such as when an ultrasonic sensor detects a wall or when voltage drops on an analog input or when a certain time is reached.

Note that autonomous routines are typically created as group commands. The autonomous command will be scheduled whenever the robot initiates autonomous mode.

Designing Subsystems and Commands

When it is time to divide your robot into subsystems, the choices might seem obvious, but there are a couple of principles to think about. Remember that a subsystem can only run one command at a time. If it seems that you will need to run multiple commands on one area, consider splitting those parts into multiple subsystems. For instance, if you have a subsystem that acquires balls, stores them, and then shoots them, you might want to break that part into two or three separate subsystems. On the other hand, if it seems like two subsystems are always doing the same thing at the same time, then maybe they should be combined. For instance, it might not be optimal to create separate subsystems for the left and right sides of your drive train.

The number of subsystems is usually fixed, but you can have a great many commands. You can keep adding commands as you think of new functions. Don’t worry if you create a lot of commands that aren’t ultimately used in the final robot program. Commands are an area for innovation.

After you’ve learned how basic commands work, read the documentation on all specialized command types, such as the InstantCommand, ConditionalCommand, CommandGroup, etc. After you’ve mastered these heavy-weight commands, you learn light-weight lambda based commands.

Naming Conventions

Most programming languages develop standards on how things should be named. In Java, the long established practice is:

  • Class names start with a capital letter, but then separate words with capital letters. This is called camel case.
  • Variables start with a lower case letter, and then proceed with camel case.
  • Constants, which are variables that are never changed, are all capital letters with words separated by underscores.

When choosing names, don’t be afraid to make long multi-word names that make meaning more clear. For robot programs, you might adopt the following conventions:

  • Subsystem classes should end in the word “Subsystem”. For instance ShooterSubsystem or ClimberSubsystem.
  • Commands classes should end in the word “Command” and begin with the name of the command’s main subystem. For instance, ClimberUpCommand or ClimberDownCommand.

Further Reading: