Docking with a Target

This script will dock any rocket with a targetted rocket. The script assumes the target is a ship and it is next to the target.

The complete program is available in a variety of languages:

Java, Python

First of all, we start with connecting to the server, initializing service instances and getting the active vessel.

15    public static void main(String[] args) throws IOException, RPCException, StreamException {
16        //This script assumes the vessel is next to the target and the target is a ship.
17        try(Connection conn = Connection.newInstance("Docking with a target")) {
18            SpaceCenter sc = SpaceCenter.newInstance(conn);
19            MechJeb mj = MechJeb.newInstance(conn);
20            Vessel active = sc.getActiveVessel();

Then, we set the first docking port as the controlling part, find a free docking port attached to the target vessel and set it as the target.

23            Parts parts = active.getParts();
24            parts.setControlling(parts.getDockingPorts().get(0).getPart());
25
26            System.out.println("Looking for a free docking port attached to the target vessel");
27            for(DockingPort dp : sc.getTargetVessel().getParts().getDockingPorts())
28                if(dp.getDockedPart() == null) {
29                    sc.setTargetDockingPort(dp);
30                    break;
31                }

Finally, we engage Docking Autopilot and close the connection when it finishes.

34            DockingAutopilot docking = mj.getDockingAutopilot();
35            docking.setEnabled(true);
36
37            Stream<Boolean> enabled = conn.addStream(docking, "getEnabled");
38            enabled.setRate(1); //we don't need a high throughput rate, 1 second is more than enough
39            synchronized(enabled.getCondition()) {
40                while(enabled.get())
41                    enabled.waitForUpdate();
42            }
43            enabled.remove();
44
45            System.out.println("Docking complete!");
46        }
47    }
48}

The vessels should now be docked.