Log in

View Full Version : Command Based JAVA - Basic Tutorial


DaveFrederick
27-11-2012, 21:41
I have put together a basic tutorial on how to use the Command Based JAVA approach.

All Feedback is welcome!

Dave Frederick
Mentor, Team 1895
Manassas, VA

F22Rapture
27-11-2012, 21:51
Yes! I've been waiting for this :D

Even the last version you posted was one of the best compilations I'd seen.

joelg236
27-11-2012, 21:58
Very well presented and detailed. I will be saving that for future use, if you don't mind. :)

Ether
27-11-2012, 23:03
For those of us who are curious but don't have the time right now to wade through this, can someone please post an "executive summary" of how this command-based architecture works "under the hood"?

Is it spawning threads in response to events?

otherguy
28-11-2012, 01:20
Here's my understanding of the Command Based robot project. Please feel free to correct me where I'm wrong.

First an overview of the concept:
There are two major classes which are provided that can be extended to contain the majority of the robot specific code, the Subsystem class and the Command class.
Subsystems characterize mechanisms on your robot. So each subsystem (drivetrain, shooter, lift, etc) should extend the Subsystem class and implement any methods for the functionality that subsystem can perform. It abstracts hardware specific funcitons from the rest of the program. So the shooter may have a method setSpeed which takes a parameter in RPMs, but this alone wouldn't be enough to shoot a ball. You will likely need to interact with multiple subsystems to do that.

This is where the Command class comes in. The purpose of the command class is to build more complex sets of functions, a procedure to follow to complete a task. For many commands this requires using methods across a number of subsystems. Groups of commands can be created to complete a number of steps in series or parallel (or a mix of both).

Commands are then linked into operator interfaces (e.g. joystick buttons) or even executed from autonomous modes.

You need to conform somewhat rigidly to the framework for everything to work, but this can have the advantage of helping you organize your thoughts.


How it works:
New instances of Commands are created from events (e.g. button press from operator). These instances are passed to a scheduler which maintains a list of all the active commands. Commands have a number of methods which allow the scheduler to step through their execution (initialize(), execute(), isFinished(), end()).

Part of a command definition provides information as to which Subsystems are required for the particular command. This allows the scheduler to identify conflicting commands, and handle which ones get to execute. Basically whichever command was issued last will execute (if there was a subsystem dependency conflict).

The command based robot project builds on top or the iterative robot project. Methods for each game mode (teleopPeriodic(), autonomousPeriodic()) are called repeatedly (every 20ms - with each driver station update). Calls to the scheduler's run() method are required within the teleop and auto periodic mode methods to allow the scheduler to process outstanding commands.

I found this presentation (http://simplerobotics.org/cRIO/2012NewFeatures.pdf) to be particularly helpful. Start at slide 18.

Once you understand the model it makes building up a fairly complex system quite painless. Throwing together auto mode actions become quite easy, as it simply becomes a new command which calls other existing commands that in many cases have already been tested and proven to work in teleop.

Ether
28-11-2012, 09:12
Basically whichever command was issued last will execute

This sounds problematic, unless I'm misunderstanding what was intended.

BigJ
28-11-2012, 09:35
Commands run "in parallel" unless they have a subsystem dependency conflict. Methods are provided by the Command class in order to allow a command to do something if it is "interrupted" by another command that requires the same subsystems.

See http://www.wbrobotics.com/javadoc/edu/wpi/first/wpilibj/command/Command.html#interrupted()

The Command class also lets you set a command as non-interruptible, but I'm not sure if the scheduler actually honors that or if it is for you to fetch with isInterruptible when making some decisions somewhere.... I've never actually tried it.

Ether
28-11-2012, 09:40
Commands run "in parallel" unless they have a subsystem dependency conflict.

What's the time slice? Does everything run at the same priority?

BigJ
28-11-2012, 09:43
I haven't actually dived into the scheduler to look at it. I'm not sure if it threads or if it is basically splitting the IterativeRobot style command loops between the commands. We've never done anything particularly timing-intensive (yet :) ) so we never had to look. (that's why I added the quotation marks, hehe)

EDIT: The cookbook says commands are accessed around every 20ms. It doesn't mention anything about priority, though.

JesseK
28-11-2012, 10:00
The command architecture is an interesting concept for robotics, but only because our processors are powerful enough to jump through the extra layers of abstraction without effecting the mechanical performance. I've experimented with sending high-level (marshalled) commands from a prompt to my quadrotor with some success. The architecture is essentially a queue for predicates and closures. The key to success on a larger system is managing compounding and/or non-deterministic behavior that causes the command queue to get gummed up.

As a reviewer's note, the command queue itself should have overriding interrupts -- ways to interrupt the current command with a higher priority command for the same subsystem. End-users under high pressure in an intense match are REALLY good at hitting the wrong button (e.g. to tell an arm to go down when they really wanted it to go up) and then changing their minds in under a few milliseconds.

BigJ
28-11-2012, 10:11
As long as your commands require the same subsystem a new command will interrupt the first and go. This lets you run a "default" joystick driving command at all times and interrupt it to do a separate controlled command with the drive subsystem for something like an autoscoring mechanism in a game like '11.

otherguy
28-11-2012, 11:29
What's the time slice? Does everything run at the same priority?

I was looking at the Scheduler code last night. I didn't see any threads being used for command execution. It's iteratively stepping through a structure which contains all active commands. Sequentially executing them if they aren't complete and removing them if they are.

This process is kicked off by the call to the scheduler's run() method. One pass through the list of active commands per call. That's why it's necessary to place within the respective auto and teleop periodic methods.

The downside to this approach is obviously that if any command takes a significant amount of time to execute, it will block program execution. But this has to be considered for any code written using the Iterative Robot model. Code within each command shouldn't do much more than some logical checks and updating the state of related outputs.

Ether
28-11-2012, 11:55
The downside to this approach is obviously that if any command takes a significant amount of time to execute, it will block program execution. ... Code within each command shouldn't do much more than some logical checks and updating the state of related outputs.

That goes to the heart of what I was asking. What you've described sounds like you have to write a state machine if you want time delays and/or wait for events like limit switches etc

Ether
28-11-2012, 11:57
As long as your commands require the same subsystem a new command will interrupt the first and go.

I think you meant abort the first and go? Otherwise, you could get some pretty funky behavior when returning from the interrupt.

apalrd
28-11-2012, 12:10
A few questions on the command architecture (without reading the paper at the beginning of the document):

-Do subsystems get poked by run() also? Or does run() just poke all of the active commands?

-Is the architecture designed for the subsystems to store the subsystem state, or for the commands to store subsystem state? I would assume the subsystems store their state, but if they don't get poked then the have to wait for a command in progress to do anything (or you have to manually poke them, or start a new thread).

Joe Ross
28-11-2012, 12:17
That goes to the heart of what I was asking. What you've described sounds like you have to write a state machine if you want time delays and/or wait for events like limit switches etc


The scheduler handles some of that for you. You can register a command to run at an event for a button or switch (eg when pressed, when released, while held), and the scheduler will poll it for you and trigger the command. You can also run several commands consecutively, or in parallel by defining a Command Group. However, if you want to do something complex, you would have to implement your own state machine.

I've been playing with the command based system, and our 2012 robot which was implemented in a huge, overly complicated, state machine in LabVIEW was able to be reduced to about 20 fairly simple commands without the need for additional state machines.

I think you meant abort the first and go? Otherwise, you could get some pretty funky behavior when returning from the interrupt.

You are correct that it would be more proper to call it an abort. However, interrupted is the term that the command based library uses. There is an optional method for a command to define that allows it to clean up before it is interrupted.

Ether
28-11-2012, 12:57
I've been playing with the command based system, and our 2012 robot which was implemented in a huge, overly complicated, state machine in LabVIEW was able to be reduced to about 20 fairly simple commands without the need for additional state machines.

Joe, are you saying that you rewrote your 2012 LabVIEW code in Java using the command-based approach and successfully ran it on the robot?

Could the "huge, overly complicated, state machine in LabVIEW" have been partitioned and cleaned up to give results similar to the Java command-based system, or does LabVIEW not readily lend itself to that?

otherguy
28-11-2012, 13:56
Do subsystems get poked by run() also? Or does run() just poke all of the active commands?
The scheduler only interfaces with the commands. Commands then interface with the methods of a subsystem.

Is the architecture designed for the subsystems to store the subsystem state, or for the commands to store subsystem state?
The state of a subsystem is kept track of by the subsystem.
The state of a command sequence is kept track of by the commands and scheduler.

A subsystem only knows how to interact with itself. It can turn a motor on/off, it can read the status of a sensor. Alone, it doesn't do you much good. The subsystem alone is not intended to be completing complex tasks.
The command keeps track of state through it's methods (previously mentioned). The command has something it needs to do, in the execute() method. Then a check is performed to see if a terminating condition is met, in the isFinished() method. So the command itself has a notion of what needs to be done and when it should consider the task complete.

Multiple commands can be linked together (series or parallel execution) in a Command Group. This allows more complex tasks to be built up from a simple set of commands, simply by calling the commands in the right order.

For example if you wanted to aquire a ball from a made up robot with a drop down intake, a lift system which moved balls vertically,you may have the following subsystems and methods within them:
Dropdown_Intake()
raise()
isRaised()
lower()
isLowered()
collect()
discard()

Elevator_Lift()
driveUp()
driveDown()
isBallPresent()

The above subsystems and methods strictly set output values and read input values.

You may then create the following commands:
RaiseIntake()
LowerIntake()
CollectIntake()

And then the following Command Group to aquire one ball:
RaiseLiftUntilBallPresent()
it could execute the following commands in sequence
LowerIntake()
ElevatorUp()
CollectIntake()
and the group of commands could terminate when ElevatorLift.isBallPresent() returns true.


Other command groups could then be created as necessary re-using some of the above commands for other teleop or autonomous functions.

Joe Ross
28-11-2012, 16:06
Joe, are you saying that you rewrote your 2012 LabVIEW code in Java using the command-based approach and successfully ran it on the robot?

Yes.

Could the "huge, overly complicated, state machine in LabVIEW" have been partitioned and cleaned up to give results similar to the Java command-based system, or does LabVIEW not readily lend itself to that?

It certainly could be cleaned up to much better then it is now, but it wouldn't be as clean as the Command based code. There's a lot of stuff going on in the background that makes the Command based code easier to use. I'm sure something similar could be implemented in LabVIEW, but it would take someone fairly skilled in LabVIEW to make it easy enough for a novice LabVIEW programmer to use.

The scheduler only interfaces with the commands. Commands then interface with the methods of a subsystem.


The state of a subsystem is kept track of by the subsystem.
The state of a command sequence is kept track of by the commands and scheduler.

A subsystem only knows how to interact with itself. It can turn a motor on/off, it can read the status of a sensor. Alone, it doesn't do you much

I do agree that in most cases the subsystem can update it's state in response to command.

There are sometimes that the state of a subsystem needs to be periodically updated, and isn't (necessarily) the result of a command. For example, consider a chassis subsystem that is keeping track of of the X-Y Location of the robot on the field using encoders and a gyro. The location may change when the robot isn't supposed to be moving, because the robot may be bumped. In order to get accurate results, you need to operate on small enough timesteps of data. If you don't have a command that is calling the updateLocation method, you will lose data.

otherguy
28-11-2012, 16:36
There are sometimes that the state of a subsystem needs to be periodically updated, and isn't (necessarily) the result of a command. For example, consider a chassis subsystem that is keeping track of of the X-Y Location of the robot on the field using encoders and a gyro. The location may change when the robot isn't supposed to be moving, because the robot may be bumped. In order to get accurate results, you need to operate on small enough timesteps of data. If you don't have a command that is calling the updateLocation method, you will lose data.

I would think your default command for the chassis would take care of calling the updateLocation() method for you if/when it's required?

BigJ
28-11-2012, 16:36
If you don't have a command that is calling the updateLocation method, you will lose data.

On this note, to those not yet familiar with the system, you can have "default commands" that run when nothing else is using a subsystem. For example, you might have a JoystickDrive command that runs at all times during teleoperated mode, unless you use another command to temporarily take control of the drive. This way, you would just have to make sure you are updating your location in all drive commands.

Joe Ross
28-11-2012, 16:55
I would think your default command for the chassis would take care of calling the updateLocation() method for you if/when it's required?

You'd also have to add it to every other command that requires that subsystem, which gets messy.

BigJ
28-11-2012, 17:14
You'd also have to add it to every other command that requires that subsystem, which gets messy.

I haven't given a lot of thought to the ramifications, but you could make the location sensors its own Subsystem, which no commands "require". You should still be able to reference the "location system" in other commands to ask it for data, should be safe if you don't modify anything.

Meanwhile, your location system always just runs a default command that maintains the location udpates.

Brian Selle
28-11-2012, 22:47
There are sometimes that the state of a subsystem needs to be periodically updated, and isn't (necessarily) the result of a command. For example, consider a chassis subsystem that is keeping track of of the X-Y Location of the robot on the field using encoders and a gyro. The location may change when the robot isn't supposed to be moving, because the robot may be bumped. In order to get accurate results, you need to operate on small enough timesteps of data. If you don't have a command that is calling the updateLocation method, you will lose data.

You could put in a call to update the position in the periodic loop before the scheduler runs in teleopPeriodic() or put it in teleopContinuous().

Ginto8
29-11-2012, 00:33
The biggest problem I see with calling an update function in a periodic function or having a Command update it is that it breaks the idea of what a Subsystem is supposed to be. Subsystems should be standalone classes with internal state corresponding to some aspect of the robot (eg. sensors, motors) with simple, non-blocking methods that modify that state. Having a periodic update function muddies that picture of a Subsystem.

So if updating from periodic or a Command violates the Subsystem's Subsystem-ness, what can be done instead? The answer was mentioned: make a background thread contained within the class. If you look at WPILibJ's PIDSubsystem, its interface is extremely simple: you have a couple ways to set the setpoint, and a way to read the current "position" (sensor value). Internally, however, there is a TimerTask acting as a PID feedback loop, working periodically. This thread is entirely encapsulated within the Subsystem, and allows the interface to be as simple as it is.

So define a Subsystem to work how you want to think about it: if you want to think about an arm as having a height above the ground, then make that the interface, leaving the rest of the details encapsulated within. If you want to think of a shooter wheel's speed in rpms instead of in [-1,1], you can do that, and implement some sort of feedback controller (like PID or bang-bang) internally. Subsystems are supposed to provide a useful interface to the robot's hardware so that commands can be simpler; sometimes, this means sacrificing a simple implementation (eg. motor power going to an arm) to make a more powerful interface (eg. setting the arm's height, allowing presets that can simplify both teleop and autonomous in a game like Logomotion).

As a rule of thumb for this design, if your Subsystem interface does stuff, you should rethink your setup. A Subsystem can do stuff internally, but its interface should be solely concerned with setting things. Doing things is the Commands' job.

kdehaan42
29-11-2012, 08:51
Thank You, so much this is great:)

Dr. Osemwengie
30-11-2012, 11:57
I have put together a basic tutorial on how to use the Command Based JAVA approach.

All Feedback is welcome!

Dave Frederick
Mentor, Team 1895
Manassas, VA

Open Robotics University (http://www.openroboticsuniversity.net/) applied to participate in tracks C and D of the DARPA Robotics Challenge. Since we are an open-source university, individuals not enrolled in the university worldwide can join our team Open Robotics University to design software and robot for the competition. Here is the link for the DARPA Robotics Challenge: http://www.theroboticschallenge.org/about.php . The prize money for the winner is two million dollars ($2000000.00). I viewed your Command Based Java approach PowerPoint, we looking for individuals with your experience that would like to participate in our projects. We are also interested in individuals that are experts in Autodesk Inventor and mechanical engineering. For more details you can email me at osem@openroboticsuniversity.net