Switching two cameras with open stream in command based


#1

So I’m trying to follow what screenstep has for multiple cameras especially the one with open stream. However, it’s really hard to follow since I believe it’s in iterative or timed based. I was wondering if someone has example codes in time based that has the same setup that screenstep has but in command based in github?


#2

To emulate the same functionality in command-based is pretty straightforward.

In Robot.java

public class Robot extends TimedRobot 
{
    public static OI oi;

    public static UsbCamera camera1, camera2;
    public static VideoSink server;

    @Override
    public void robotInit() 
    {
        oi = new OI();

        camera1 = CameraServer.getInstance().startAutomaticCapture(0);
        camera2 = CameraServer.getInstance().startAutomaticCapture(1);
        server = CameraServer.getInstance().getServer();
    }

// the rest of Robot.java...
}

In OI.java

public class OI
{
	private static Joystick joystick = new Joystick(0);
	private static JoystickButton camera1Button = new JoystickButton(joystick, 0);
	private static JoystickButton camera2Button = new JoystickButton(joystick, 1);

	public OI() {
		camera1Button.whenPressed(new SwitchToCamera1());
		camera2Button.whenPressed(new SwitchToCamera2());
	}
}

in commands/SwitchToCamera1.java

public class SwitchToCamera1 extends InstantCommand {
	public SwitchToCamera1() { }

	@Override
	protected void execute() {
		Robot.server.setSource(Robot.camera1);
	}
}

in commands/SwitchToCamera2.java

public class SwitchToCamera2 extends InstantCommand {
	public SwitchToCamera2() { }

	@Override
	protected void execute() {
		Robot.server.setSource(Robot.camera2);
	}
}

The InstantCommand class is perfect for something simple like this, as none of the other methods are needed.


#3

The only thing I would add is I definitely recommend following the guidance in the “keeping streams open” section of screensteps, as otherwise camera switching will be slow. Just add these lines to the end of the above robotInit() function.

camera1.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen);
camera2.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen);