Web Browser Control Panel#

This tutorial builds a control panel for a vessel that runs in a web browser, using the JavaScript client. The panel shows the vessel’s altitude, air speed, thrust to weight ratio and throttle. Its buttons activate the next stage, turn SAS and RCS on and off, and point the vessel with SAS.

The panel is a page and a script: control-panel.html and ControlPanel.js.

Building the Panel#

The script imports the client, so we bundle the two into one file for the page. The following installs the client and esbuild, then bundles them as control-panel.js, which the page loads, and serves the page:

npm install @krpc-org/krpc esbuild
npx esbuild ControlPanel.js --bundle --format=iife \
  --outfile=control-panel.js --servedir=.

Open http://127.0.0.1:8000/control-panel.html in the browser. The server accepts a page from a loopback address by default. Opened from another machine, by the address of this one, the page needs that origin added to the server’s Origins, as Web Pages describes.

In the game, the server window has a “Protobuf over WebSockets” server on port 50001 by default. Enter its address and port in the panel, and click “Connect”.

The Page#

The page holds an element for each value the panel shows, and the buttons. The script fills in the elements by their id:

<body>
  <section>
    <input id="address" value="127.0.0.1" size="12">
    <input id="port" value="50001" size="5">
    <button id="connect">Connect</button>
    <span id="vessel"></span>
  </section>

  <section class="readouts">
    <div>Altitude <output id="altitude">-</output></div>
    <div>Air speed <output id="airspeed">-</output></div>
    <div>TWR <output id="twr">-</output></div>
    <div>Throttle <output id="throttle">-</output></div>
    <input id="throttle-slider" type="range" min="0" max="100" value="0">
  </section>

  <section>
    <button id="stage">
      STAGE (next stage <span id="stage-number">-</span>)
    </button>
    <p>
      <button id="sas">SAS</button>
      <button id="rcs">RCS</button>
    </p>
    <div id="sas-modes"></div>
  </section>

  <section id="log"></section>

  <script src="control-panel.js"></script>
</body>

Connecting#

The script keeps the connection, the controls of the vessel shown, and the streams of that vessel:

/** @type {import("@krpc-org/krpc").Connection} */
let conn = null;
/** @type {SpaceCenter.Control} */
let control = null;
/** The streams of the vessel shown
 * @type {{ remove(): Promise<void> }[]} */
let streams = [];

Clicking “Connect” calls connectToServer. It connects to the server, then streams the active vessel:

async function connectToServer() {
  const address = /** @type {HTMLInputElement} */ (element("address"))
    .value;
  const port = Number(
    /** @type {HTMLInputElement} */ (element("port")).value,
  );
  try {
    conn = await connect({ name: "Control Panel", address, port });
  } catch (error) {
    log(`Connection failed: ${error}`);
    return;
  }
  log(`Connected to ${address}:${port}`);
  element("connect").textContent = "Disconnect";

  // Follow the active vessel, which changes when the player switches vessel
  const activeVessel = await conn.addStream(() =>
    conn.spaceCenter.getActiveVessel(),
  );
  await activeVessel.setRate(1);
  /** @type {SpaceCenter.Vessel} */
  let shown;
  activeVessel.addCallback(async (vessel) => {
    if (vessel === shown) return;
    shown = vessel;
    await showVessel(vessel);
  });

  // The stream ends when the connection closes
  activeVessel.addEndCallback((error) => {
    conn = null;
    control = null;
    streams = [];
    element("connect").textContent = "Connect";
    log(`Disconnected: ${error.message}`);
  });
}

The active vessel changes when the player switches vessel. The client returns one object for each vessel, so the callback compares the new vessel with the one shown using ===. The callback returns a Promise, so the client waits for showVessel to finish before it calls the callback again.

A stream ends when its connection closes. The end callback of the active vessel stream resets the panel, whether the player stopped the server or we clicked “Disconnect”.

Flight Data#

Each value on the panel comes from a stream. The watch function adds a callback to a stream that updates the page, and limits the stream to 10 updates a second:

/** Calls update with each new value of a stream, at most 10 times a second
 * @template T
 * @param {Promise<import("@krpc-org/krpc").Stream<T>>} added
 * @param {(value: T) => void} update */
async function watch(added, update) {
  const stream = await added;
  streams.push(stream);
  await stream.setRate(10);
  stream.addCallback(update);
}

/** Shows the data of a vessel, and points the controls at it
 * @param {SpaceCenter.Vessel} vessel */
async function showVessel(vessel) {
  // Remove the streams of the previous vessel
  await Promise.allSettled(streams.map((stream) => stream.remove()));
  streams = [];
  control = null;
  element("vessel").textContent = vessel
    ? await vessel.getName()
    : "No active vessel";
  if (!vessel) return;

  const flight = await vessel.flight();
  const newControl = await vessel.getControl();

  await Promise.all([
    watch(
      conn.addStream(() => flight.getMeanAltitude()),
      (altitude) => {
        element("altitude").textContent = distance(altitude);
      },
    ),
    watch(
      conn.addStream(() => flight.getTrueAirSpeed()),
      (speed) => {
        element("airspeed").textContent = `${speed.toFixed(1)} m/s`;
      },
    ),
    // The thrust to weight ratio, from the gravity at the vessel's distance
    // from the body
    watch(
      conn.addStream(
        ({ vessel }) =>
          vessel.thrust /
          ((vessel.mass * vessel.orbit.body.gravitationalParameter) /
            vessel.orbit.radius ** 2),
        { vessel },
      ),
      (twr) => {
        element("twr").textContent = twr.toFixed(2);
      },
    ),
    watch(
      conn.addStream(() => newControl.getThrottle()),
      (throttle) => {
        element("throttle").textContent =
          `${(throttle * 100).toFixed(0)} %`;
        // Leave the slider alone while the user drags it
        if (!throttleSlider.matches(":active")) {
          throttleSlider.value = String(throttle * 100);
        }
      },
    ),
    watch(
      conn.addStream(() => newControl.getCurrentStage()),
      (stage) => {
        element("stage-number").textContent = String(stage);
      },
    ),
    watch(
      conn.addStream(() => newControl.getSAS()),
      (sas) => {
        element("sas").classList.toggle("on", sas);
      },
    ),
    watch(
      conn.addStream(() => newControl.getRCS()),
      (rcs) => {
        element("rcs").classList.toggle("on", rcs);
      },
    ),
    watch(
      conn.addStream(() => newControl.getSASMode()),
      (mode) => {
        for (const [buttonMode, button] of modeButtons) {
          button.classList.toggle("on", buttonMode === mode);
        }
      },
    ),
  ]);
  control = newControl;
}

showVessel first removes the streams of the vessel shown before. It then adds a stream for each value on the panel, and for the state of the buttons. A stream of the SAS state lights up the SAS button, including when the player turns SAS on in the game.

The thrust to weight ratio is a stream of a server side function. The function divides the vessel’s thrust by its weight, using the gravity at the vessel’s distance from the center of the body. A ratio over 1 lifts the vessel off the ground.

Controls#

Each button runs an action on the vessel’s controls through act. A button clicked before the panel shows a vessel does nothing, and an action that fails logs its error to the page:

/** Runs an action on the vessel's controls, and logs an error it throws
 * @param {(control: SpaceCenter.Control) => Promise<unknown>} action */
async function act(action) {
  if (!control) return;
  try {
    await action(control);
  } catch (error) {
    log(String(error));
  }
}

The buttons are attached at the end of the script:

element("connect").addEventListener("click", () => {
  if (conn) conn.close();
  else connectToServer();
});

element("stage").addEventListener("click", () =>
  act((control) => control.activateNextStage()),
);

element("sas").addEventListener("click", () =>
  act(async (control) => control.setSAS(!(await control.getSAS()))),
);

element("rcs").addEventListener("click", () =>
  act(async (control) => control.setRCS(!(await control.getRCS()))),
);

throttleSlider.addEventListener("input", () =>
  act((control) => control.setThrottle(Number(throttleSlider.value) / 100)),
);

for (const [mode, label] of SAS_MODES) {
  const button = document.createElement("button");
  button.textContent = label;
  button.addEventListener("click", () =>
    act(async (control) => {
      // Turn SAS on, so the vessel holds the direction
      await control.setSAS(true);
      await control.setSASMode(mode);
    }),
  );
  element("sas-modes").append(button);
  modeButtons.set(mode, button);
}

The SAS mode buttons turn SAS on before they set the mode, so the vessel holds the direction. A mode the vessel cannot use, such as “Target” with no target selected, logs an error.