Build Command in autonomousInit()

We would like to dynamically adjust the command delay of whatever auto we have selected from our chooser. We are appling some of the tricks we learned over the past few iterations.

autonomousCommand = new CommandGroup() {
{
    addSequential(  new Auto_Util_TimeDelay((Integer) Robot.delayChooser.getSelected()));
    addSequential(	(Command) autonomousChooser.getSelected());
        		}
        	};

This worked with one big but, the first run the autonomous works just as expected. If we test the auto again without restarting the code [power cycle, program download] the code crashes. I don’t have the log file but it was something along the lines of

can not add a command to a command group … it’s already in

That’s because you’re adding the same command object to a new CommandGroup each time the robot enters autonomousInit().

One way to get around it is to use a Supplier in the chooser instead of the command objects; this way, you’ll be able to get a new command object each time.

Change your existing code:


SendableChooser<Command> autonomousChooser = new SendableChooser<>();
autonomousChooser.addObject("Example", new ExampleCommand());
...
addSequential(autonomousChooser.getSelected());

to something like this:


SendableChooser<Supplier<Command>> autonomousChooser = new SendableChooser<>();
autonomousChooser.addObject("Example", () -> new ExampleCommand());
...
addSequential(autonomousChooser.getSelected().get());

Note the “new” in the supplier – returning a predefined command will have the same problem you’re experiencing now

Thanks that seemed to do the trick.

Can we give the new command a name other than the random encrypted names the bellow creates?

autonomousChooser.addObject("Example", () -> new ExampleCommand());

The name this creates is …Robot$1

Use the setName() method: autonomousChooser.setName(“autoMode”) will set the name to autoMode. Go up to SendableBasefor more options on this method.