Server Side Functions#
A server side function is code that runs inside the game, on the server. It has three main uses:
Custom events wait for a condition to become true. The server checks the condition every physics tick, and sends your program a message when it fires. Polling from your program adds a round trip to every check, and can miss a condition that holds for only a few ticks.
Function streams stream the result of a computation over several RPC values. The server reads every value in the same physics tick, so the values are consistent. It sends the result to your program when the result changes.
Run-once functions run a sequence of calls and computation in a single physics tick, from a single RPC. They can set properties and trigger actions. The same calls made from your program take a round trip each, and the game advances between them.
This guide is in two parts. Using Server Side Functions covers functions written in your own language and compiled by the client, and is all most users need. The Expression API covers the expression trees that compiled code translates into, which every client can build directly.
Every client supports Run. Support for the other features differs:
Client |
Compiled functions |
Events and function streams |
|---|---|---|
Python |
✓ |
✓ |
C# |
✓ |
✓ |
C++ |
✗ |
✓ |
C-nano |
✗ |
✗ |
Java |
✗ |
✓ |
Lua |
✗ |
✗ |
JavaScript |
✓ |
✓ |
Using Server Side Functions#
A client with a compiler turns a function or lambda into a server side function. It is the simplest way to write one. The constructs a compiler supports depend on the language. Without a compiler, the expression API defines a server side function directly.
A First Custom Event#
This event fires when the vessel’s altitude exceeds 1000 meters:
event = conn.add_event(lambda: flight.mean_altitude > 1000)
with event.condition:
event.wait()
print("Altitude reached 1000m")
var evnt = connection.AddEvent (() => flight.MeanAltitude > 1000);
lock (evnt.Condition) {
evnt.Wait ();
Console.WriteLine ("Altitude reached 1000m");
}
const event = await conn.addEvent(
({ flight }) => flight.meanAltitude > 1000,
{ flight },
);
await event.wait();
console.log("Altitude reached 1000m");
The client compiles the lambda into a server side function. The mean altitude call becomes an
embedded RPC, re-invoked on each check. 1000 becomes a constant.
The server checks the condition every physics tick until it is true. It then sends your program a single message, which ends the wait. Your program makes no polling calls while it waits, so it uses no round trips and no CPU time.
Remote Calls and Captured Values#
The compiler splits a function by what each part depends on:
Reading a property or calling a method of a remote object or service becomes part of the function. The server re-invokes it on every evaluation. So does any operation on its result.
A sub-expression that uses only client side values, such as captured variables and literals, is evaluated once, when the function is compiled. That includes arithmetic and library calls on those values. The result becomes a constant.
For example:
threshold = 50000
event = conn.add_event(
lambda: vessel.orbit.apoapsis_altitude > threshold * 2
)
var threshold = 50000;
var evnt = connection.AddEvent (
() => vessel.Orbit.ApoapsisAltitude > threshold * 2);
const threshold = 50000;
const event = await conn.addEvent(
({ vessel, threshold }) => vessel.orbit.apoapsisAltitude > threshold * 2,
{ vessel, threshold },
);
The client computes threshold * 2 when it creates the event, so the function compares the
apoapsis with the constant 100000. To use a new value of threshold, compile a new function
and remove the old event.
Computed Streams#
A stream created from a function carries the function’s result. The server runs the computation on each stream update:
# The vessel's altitude, in kilometers, computed on the server
stream = conn.add_stream(lambda: flight.mean_altitude / 1000)
print("Altitude:", stream(), "km")
// The vessel's altitude, in kilometers, computed on the server
var stream = connection.AddStream (
() => flight.MeanAltitude / 1000);
Console.WriteLine ("Altitude: " + stream.Get () + " km");
// The vessel's altitude, in kilometers, computed on the server
const stream = await conn.addStream(
({ flight }) => flight.meanAltitude / 1000,
{ flight },
);
console.log("Altitude:", await stream.get(), "km");
A function can produce a collection. This streams the thrust of every engine on the vessel, read in a single physics tick per update:
engines = vessel.parts.engines
stream = conn.add_stream(lambda: [engine.thrust for engine in engines])
for thrust in stream():
print(thrust)
var engines = vessel.Parts.Engines;
var stream = connection.AddStream (
() => engines.Select (engine => engine.Thrust).ToList ());
foreach (var thrust in stream.Get ())
Console.WriteLine (thrust);
const engines = await (await vessel.getParts()).getEngines();
const stream = await conn.addStream(
({ engines }) => engines.map((engine) => engine.thrust),
{ engines },
);
for (const thrust of await stream.get()) {
console.log(thrust);
}
Here engines is a captured variable, so the list of engines is fixed when the function is
compiled. The server re-reads only their thrusts. Read the engine list inside the function to
have the server fetch the list on each update. That follows staging, at the cost of extra work
per update.
Collections#
The language’s collection operations, such as mapping, filtering, counting, summing and sorting, compile to the server’s collection operations. This event fires when any engine on the vessel runs out of fuel. The server re-reads the engine list on each check, so the event covers engines that staging reveals:
event = conn.add_event(
lambda: any(not engine.has_fuel for engine in vessel.parts.engines)
)
with event.condition:
event.wait()
print("An engine has run out of fuel")
var evnt = connection.AddEvent (
() => vessel.Parts.Engines.Any (engine => !engine.HasFuel));
lock (evnt.Condition) {
evnt.Wait ();
Console.WriteLine ("An engine has run out of fuel");
}
const event = await conn.addEvent(
({ vessel }) => vessel.parts.engines.some((engine) => !engine.hasFuel),
{ vessel },
);
await event.wait();
console.log("An engine has run out of fuel");
Strings#
The language’s string operations, such as length, indexing, searching, splitting and case conversion, compile to the server’s string operations. This streams the vessel’s name in upper case:
stream = conn.add_stream(lambda: vessel.name.upper())
var stream = connection.AddStream (
() => vessel.Name.ToUpperInvariant ());
const stream = await conn.addStream(
({ vessel }) => vessel.name.toUpperCase(),
{ vessel },
);
Two rules apply to strings:
A character is a string of length one. The protocol carries no character type, so indexing a string produces a one character string, which works with every other string operation. In a language where indexing a string produces a character, that index is an unsupported construct. Take a substring instead.
Case conversion and comparison are the same in every locale. Case is converted, and strings are compared, by ordinal value. A function produces the same result whatever language the game runs in.
Statements, Loops and Local Variables#
A compiled function can be a sequence of statements, like any other function in your program. This one computes the fraction of liquid fuel left:
def fuel_fraction():
resources = vessel.resources
amount = resources.amount("LiquidFuel")
capacity = resources.max("LiquidFuel")
return amount / capacity
stream = conn.add_stream(fuel_fraction)
// A C# lambda holds a single expression
var stream = connection.AddStream (
() => vessel.Resources.Amount ("LiquidFuel") /
vessel.Resources.Max ("LiquidFuel"));
const stream = await conn.addStream(
({ vessel }) => {
const resources = vessel.resources;
const amount = resources.amount("LiquidFuel");
const capacity = resources.max("LiquidFuel");
return amount / capacity;
},
{ vessel },
);
In outline, a compiled function supports these statements:
If statements, with else branches.
While and for-each loops, with break and continue.
Early returns.
Local variables, which can be reassigned and changed in place. A loop can build up a collection in one.
The exact set depends on the language. Each client guide lists what its compiler supports: C#, JavaScript and Python.
A collection a call returns is a copy, as it is in your program. Changing the copy in a function leaves the game’s own collection unchanged.
This function collects a rating for each active engine:
def burn_ratings():
ratings: list[str] = []
for engine in vessel.parts.engines:
if not engine.active:
continue
if engine.thrust > 0.9 * engine.available_thrust:
ratings.append("full")
else:
ratings.append("partial")
return ratings
print(conn.run(burn_ratings))
// A C# lambda holds a single expression, so LINQ operators replace
// the loop
var ratings = connection.Run (
() => vessel.Parts.Engines
.Where (engine => engine.Active)
.Select (engine =>
engine.Thrust > 0.9 * engine.AvailableThrust
? "full" : "partial")
.ToList ());
Console.WriteLine (string.Join (", ", ratings));
const ratings = await conn.run(
({ vessel }) => {
const ratings = [];
for (const engine of vessel.parts.engines) {
if (!engine.active) {
continue;
}
if (engine.thrust > 0.9 * engine.availableThrust) {
ratings.push("full");
} else {
ratings.push("partial");
}
}
return ratings;
},
{ vessel },
);
console.log(ratings);
A variable keeps one type for the whole function. How it gets that type depends on the language:
A variable takes its type from its first assignment. A type annotation sets the type, and each value assigned then widens to it, as an integer does to a float:
def total_thrust():
total: float = 0
for engine in vessel.parts.engines:
total += engine.thrust
return total
print(conn.run(total_thrust))
An empty collection takes its element type the same way, as in ratings: list[str] = []
above.
A C# lambda holds a single expression, so it has no local variables. Each value has its C# type.
A number is always a double, so a running total needs no type:
const total = await conn.run(
({ vessel }) => {
let total = 0;
for (const engine of vessel.parts.engines) {
total += engine.thrust;
}
return total;
},
{ vessel },
);
console.log(total);
An empty array, Set or Map takes its type from a later use, such as a push. With no
such use, give one a type with cast, as the client guide describes.
Side Effects and Run-Once Functions#
A compiled function can also change the game. It can assign to the properties of remote objects and
services, and call methods for their effects. Pass such a function to Run, which evaluates it
once, with every step in the same physics tick:
def deploy():
for parachute in vessel.parts.parachutes:
if not parachute.deployed:
parachute.deploy()
conn.run(deploy)
// A single side-effecting call, run on the server
connection.Run (() => vessel.Control.ToggleActionGroup (1));
// Compute and return a value in one tick
var altitude = connection.Run (() => flight.MeanAltitude / 1000);
await conn.run(
({ vessel }) => {
for (const parachute of vessel.parts.parachutes) {
if (!parachute.deployed) {
parachute.deploy();
}
}
},
{ vessel },
);
Note
An event or stream runs its function on every stream update, effects included. See Control Loops on the Server.
Note
A procedure that runs over several ticks, such as SpaceCenter.WarpTo, is an error in a
function. See Errors, Edge Cases and Performance.
Function Arguments#
A compiled function can take parameters, and Run passes it a value for each. One function then
serves many inputs. This computes how long a burn takes, for several changes in velocity:
The function is a def with a type annotation on each parameter. Its arguments bind as
Python binds them, with defaults and keyword arguments:
@conn.compile
def burn_time(delta_v: float) -> float:
exhaust_velocity = vessel.specific_impulse * 9.82
final_mass = vessel.mass / math.exp(delta_v / exhaust_velocity)
return (
(vessel.mass - final_mass)
* exhaust_velocity
/ vessel.available_thrust
)
for delta_v in (100.0, 250.0, 400.0):
print(conn.run(burn_time, delta_v))
The function is a lambda with typed parameters:
var burnTime = connection.Compile ((double deltaV) =>
(vessel.Mass - vessel.Mass /
Math.Exp (deltaV / (vessel.SpecificImpulse * 9.82)))
* vessel.SpecificImpulse * 9.82 / vessel.AvailableThrust);
foreach (var deltaV in new [] { 100.0, 250.0, 400.0 })
Console.WriteLine (connection.Run<double> (burnTime, deltaV));
The parameters follow the captures, and compile takes their types:
const burnTime = await conn.compile(
({ vessel }, deltaV) => {
const exhaustVelocity = vessel.specificImpulse * 9.82;
const finalMass = vessel.mass / Math.exp(deltaV / exhaustVelocity);
return (
((vessel.mass - finalMass) * exhaustVelocity) / vessel.availableThrust
);
},
{ vessel },
[types.double],
);
for (const deltaV of [100, 250, 400]) {
console.log(await conn.run(burnTime, deltaV));
}
An event or a stream runs its function with no arguments.
State Between Updates#
A function can keep a value from one evaluation to the next, such as a running total. This stream counts the stream updates in which the engines are firing:
Declare a captured variable nonlocal:
def firing_counter():
updates = 0
@conn.compile
def count():
nonlocal updates
if vessel.thrust > 0:
updates += 1
return updates
return count
stream = conn.add_stream(firing_counter())
The variable takes its type from its value when the function is compiled. To give it
another type, such as a list that starts empty, start the function with a cast of it:
history = cast(List[float], history).
A C# lambda is an expression tree, which cannot assign to a variable. Build the function
with the expression API, and create the variable with
Expression.state_variable().
Assign a property of a captured object:
const state = { updates: 0 };
const stream = await conn.addStream(
({ vessel, state }) => {
if (vessel.thrust > 0) {
state.updates += 1;
}
return state.updates;
},
{ vessel, state },
);
The property takes its type from its value when the function is compiled. A property that
starts empty takes its type from the first use that adds to it, or from a cast such as
t.list(t.double).cast(state.history).
The state lives on the server. It starts with the variable’s value at compile time, and changes to it do not reach the variable in the client program.
A function passed straight to Run or a stream is compiled on each call, so each call gets its
own state. A function compiled once with compile keeps one state across every run, stream and
event that uses it. Two streams of it advance the state twice per update.
Control Loops on the Server#
A stream of a function with no value runs the function on every stream update, for its effects. Such a stream can run a control loop in the game, with no round trip to the client. This one throttles back as the vertical speed nears 100 m/s:
@conn.compile
def limit_throttle():
# Throttle back as the vertical speed nears 100 m/s
control.throttle = max(0, min(1, (100 - flight.vertical_speed) / 20))
with conn.add_stream(limit_throttle):
time.sleep(60)
A C# lambda is an expression tree, which cannot assign to a property. Build the function with the expression API.
const limitThrottle = await conn.compile(
({ control, flight }) => {
// Throttle back as the vertical speed nears 100 m/s
control.throttle = Math.max(
0,
Math.min(1, (100 - flight.verticalSpeed) / 20),
);
},
{ control, flight },
);
const stream = await conn.addStream(limitThrottle);
await new Promise((resolve) => setTimeout(resolve, 60000));
await stream.remove();
The stream’s value is the client’s null value. The server sends it once, after the first run, so a callback is called once. An error from the function ends the stream and stops the loop. Set the stream’s rate to run the function less often.
Exceptions#
A function can raise an exception. It reaches your program as an error when run, or as an error on the stream or event evaluating the function:
@conn.compile
def check_fuel():
if vessel.resources.amount("LiquidFuel") < 100:
raise RuntimeError("not enough fuel")
var e = Expression.Bind (connection);
// A C# lambda cannot throw, so the expression API builds the
// statement around a compiled condition
var checkFuel = e.IfThen (
connection.Compile (
() => vessel.Resources.Amount ("LiquidFuel") < 100),
e.Throw ("KRPC", "InvalidOperationException",
e.ConstantString ("not enough fuel")));
const checkFuel = await conn.compile(
({ vessel }) => {
if (vessel.resources.amount("LiquidFuel") < 100) {
throw new Error("not enough fuel");
}
},
{ vessel },
);
Your program catches the error as an exception, as it does for an error from any other call.
A function can also handle an exception, with the language’s try statement:
@conn.compile
def switch_modes() -> str:
try:
for engine in vessel.parts.engines:
engine.toggle_mode()
return "switched"
except Exception as error:
return "could not switch: " + error
var e = Expression.Bind (connection);
var t = Type.Bind (connection);
// A C# lambda cannot hold a loop or a handler, so the expression
// API builds them
var engine = e.Variable (
"engine", t.ClassType ("SpaceCenter", "Engine"));
var result = e.Variable ("result", t.String ());
var error = e.Variable ("error", t.String ());
var toggleMode = Connection.GetCallTemplate (
(Engine x) => x.ToggleMode ());
var toggleEngine = e.CallWithArguments (toggleMode,
new Dictionary<int, Expression> { { 0, engine } });
var switchModes = e.BlockWithVariables (
new List<Expression> { engine, result, error },
new List<Expression> {
e.TryCatchAll (
e.Block (new List<Expression> {
e.ForEach (engine,
connection.Compile (() => vessel.Parts.Engines),
toggleEngine),
e.Assign (result, e.ConstantString ("switched"))
}),
error,
e.Assign (result,
e.StringConcat (new List<Expression> {
e.ConstantString ("could not switch: "),
error
}))),
result
});
const switchModes = await conn.compile(
({ vessel }) => {
try {
for (const engine of vessel.parts.engines) {
engine.toggleMode();
}
return "switched";
} catch (error) {
return `could not switch: ${/** @type {Error} */ (error).message}`;
}
},
{ vessel },
);
These rules apply to handlers:
Only the message of an exception is exposed. The variable a handler binds is a string holding the message. In JavaScript, the handler reads it as
e.message.A handler also catches exceptions from the calls in the function. A handler for an exception catches it whether the function raises it, or a remote procedure the function calls does.
A procedure that pauses execution passes through every handler, including a catch-all. It is reported as an error.
Some errors are caught only by a catch-all handler, as they have no exception class to name. These are a call to a procedure that is unavailable in the current game scene, and a procedure that returns null when its return type does not allow it. Uncaught, each reaches your program as a plain error.
The Standard Library#
The StdLib service is a standard library for server side functions, with mathematics,
vector and quaternion operations, and printing. Calls to the language’s math library compile to the matching StdLib procedures when their arguments are computed on
the server. Call the service directly for the vector and quaternion operations. This streams the
angle between the vessel’s facing direction and its velocity relative to the surface:
stdlib = conn.std_lib
frame = vessel.orbit.body.reference_frame
stream = conn.add_stream(
lambda: stdlib.radians_to_degrees(
stdlib.vector_angle(vessel.direction(frame), vessel.velocity(frame))
)
)
var stdlib = connection.StdLib ();
var frame = vessel.Orbit.Body.ReferenceFrame;
var stream = connection.AddStream (
() => stdlib.RadiansToDegrees (stdlib.VectorAngle (
vessel.Direction (frame), vessel.Velocity (frame))));
const orbit = await vessel.getOrbit();
const frame = await (await orbit.getBody()).getReferenceFrame();
const stream = await conn.addStream(
({ stdLib, vessel, frame }) =>
stdLib.radiansToDegrees(
stdLib.vectorAngle(vessel.direction(frame), vessel.velocity(frame)),
),
{ stdLib: conn.stdLib, vessel, frame },
);
The service covers:
Scalar functions, such as square roots, trigonometry and clamping, and the constants pi and e.
Vector operations on the position and direction tuples of the
SpaceCenterservice, such as dot and cross products, magnitudes, angles and interpolation.Quaternion operations on its rotation tuples, such as composition, inverses, rotating vectors and interpolation.
Each midpoint rounding rule has its own procedure, so a function can round the way its language does:
StdLib.round()rounds a halfway value to the nearer even number, as Python and C# do.StdLib.round_half_away_from_zero()rounds it away from zero, as C and C++ do.StdLib.round_half_up()rounds it toward positive infinity, as Java and JavaScript do.
Each takes the number of decimal places, negative for tens and hundreds.
Printing#
The language’s print function compiles to StdLib.print(), which writes a line to the
game’s log, KSP.log. This logs the vessel’s mass from the server:
conn.run(lambda: print("Mass:", vessel.mass, "kg"))
connection.Run (
() => Console.WriteLine (
FormattableString.Invariant ($"Mass: {vessel.Mass} kg")));
await conn.run(({ vessel }) => console.log("Mass:", vessel.mass, "kg"), {
vessel,
});
A print in an event or stream function writes a line on every stream update.
Supported Constructs#
Each client guide lists the constructs its compiler supports, and where their meaning differs from the language’s: C#, JavaScript and Python. Any other construct is a compilation error that names it.
Reusing Functions#
Passing a new lambda to run in a loop builds a new function on each pass. Each pass reads the lambda’s captured variables again, while a compiled function keeps the values from when it was compiled.
In such cases, compile the function once, and run the compiled function as often as needed. To run it with different values, give it parameters, as in Function Arguments:
step = conn.compile(lambda: vessel.control.toggle_action_group(1))
while True:
conn.run(step)
var step = connection.Compile (
() => vessel.Control.ToggleActionGroup (1));
while (true)
connection.Run (step);
const step = await conn.compile(
({ vessel }) => vessel.control.toggleActionGroup(1),
{ vessel },
);
while (true) {
await conn.run(step);
}
A large lambda passed on every call can make the game stutter. The server compiles each one to native code on the game’s main thread. Compile a function before it is needed, such as before launch, and every run is fast.
Errors, Edge Cases and Performance#
Errors. An error raised while evaluating a stream or event function reaches your program when it reads the stream or event. An example is an embedded call reaching a destroyed part.
The server then removes the stream, as it does for any stream whose result is an error. Build a new event or stream once the cause clears.
Loads and unloaded vessels. A stream of a remote procedure pauses while its object is not
loaded, and resumes after. A function stream or event ends instead, with
KRPC.ObjectNotLoadedException. Examples are a part of an unloaded vessel, and a vessel part
way through a load. To keep one running, catch the exception in the function:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight = vessel.flight()
def above_1000m() -> bool:
try:
return flight.mean_altitude > 1000
except conn.krpc.ObjectNotLoadedException:
return False
event = conn.add_event(above_1000m)
with event.condition:
event.wait()
print("Altitude reached 1000m")
using System;
using System.Collections.Generic;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using KRPC.Client.Services.SpaceCenter;
using Type = KRPC.Client.Services.KRPC.Type;
class Program {
public static void Main() {
var connection = new Connection();
var e = Expression.Bind(connection);
var t = Type.Bind(connection);
var spaceCenter = connection.SpaceCenter();
var flight = spaceCenter.ActiveVessel.Flight();
// A C# lambda cannot hold a handler, so the expression API builds
// it around a compiled condition
var above = e.Variable("above", t.Bool());
var above1000m = e.BlockWithVariables(
new List<Expression> { above },
new List<Expression> {
e.TryCatch(
e.Assign(above, connection.Compile(
() => flight.MeanAltitude > 1000)),
"KRPC", "ObjectNotLoadedException", null,
e.Assign(above, e.ConstantBool(false))),
above
});
var evnt = connection.AddEvent(above1000m);
lock (evnt.Condition) {
evnt.Wait();
Console.WriteLine("Altitude reached 1000m");
}
}
}
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <optional>
#include <vector>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto flight = sc.active_vessel().value().flight();
typedef krpc::services::KRPC::Expression Expr;
typedef krpc::services::KRPC::Type KType;
auto e = Expr::bind(conn);
auto t = KType::bind(conn);
// above = mean_altitude > 1000, or false if the vessel is not loaded
auto above = e.variable("above", t.bool_());
auto altitude = e.call(flight.mean_altitude_call());
auto above_1000m = e.block_with_variables(
std::vector<Expr>({above}),
std::vector<Expr>(
{e.try_catch(
e.assign(above,
e.greater_than(altitude, e.constant_double(1000))),
"KRPC", "ObjectNotLoadedException", std::nullopt,
e.assign(above, e.constant_bool(false))),
above}));
auto event = krpc::add_event(above_1000m);
event.acquire();
event.wait();
std::cout << "Altitude reached 1000m" << std::endl;
event.release();
}
#include <krpc_cnano.h>
#include <krpc_cnano/functions.h>
#include <krpc_cnano/services/krpc.h>
#include <krpc_cnano/services/space_center.h>
#include <stdio.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Not loaded example") != KRPC_OK) return 1;
krpc_SpaceCenter_Vessel_t vessel;
krpc_SpaceCenter_ActiveVessel(conn, &vessel);
krpc_SpaceCenter_Flight_t flight;
krpc_SpaceCenter_Vessel_Flight(conn, &flight, vessel, KRPC_NULL);
// above = mean_altitude > 1000, or false if the vessel is not loaded
krpc_KRPC_Type_t bool_type;
krpc_KRPC_Type_Bool(conn, &bool_type);
krpc_KRPC_Expression_t above;
krpc_KRPC_Expression_Variable(conn, &above, "above", bool_type);
krpc_schema_ProcedureCall mean_altitude;
krpc_SpaceCenter_Flight_MeanAltitude_call(&mean_altitude, flight);
krpc_KRPC_Expression_t altitude, limit, comparison, assign_above;
krpc_KRPC_Expression_Call(conn, &altitude, &mean_altitude);
krpc_free_procedure_call(&mean_altitude);
krpc_KRPC_Expression_ConstantDouble(conn, &limit, 1000);
krpc_KRPC_Expression_GreaterThan(conn, &comparison, altitude, limit);
krpc_KRPC_Expression_Assign(conn, &assign_above, above, comparison);
krpc_KRPC_Expression_t no, assign_false, try_catch;
krpc_KRPC_Expression_ConstantBool(conn, &no, false);
krpc_KRPC_Expression_Assign(conn, &assign_false, above, no);
krpc_KRPC_Expression_TryCatchById(
conn, &try_catch, assign_above,
KRPC_EXCEPTION_KRPC_OBJECTNOTLOADEDEXCEPTION, KRPC_NULL,
assign_false);
krpc_KRPC_Expression_t variable_items[1] = {above};
krpc_KRPC_Expression_t statement_items[2] = {try_catch, above};
krpc_list_object_t variables = {1, variable_items};
krpc_list_object_t statements = {2, statement_items};
krpc_KRPC_Expression_t above_1000m;
krpc_KRPC_Expression_BlockWithVariables(conn, &above_1000m, &variables,
&statements);
// Run the function, as this client has no events
krpc_bytes_t data = KRPC_BYTES_NULL;
krpc_run_function(conn, &data, NULL, above_1000m, NULL);
bool reached;
pb_istream_t stream = pb_istream_from_buffer(data.data, data.size);
krpc_decode_bool(&stream, &reached);
KRPC_FREE_BYTES(data);
if (reached) printf("Altitude reached 1000m\n");
krpc_disconnect(conn);
}
import krpc.client.Connection;
import krpc.client.Event;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.KRPC.Type;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import java.util.Arrays;
public class NotLoadedEvent {
public static void main(String[] args) {
try (Connection connection = Connection.newInstance()) {
SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
Flight flight = spaceCenter.getActiveVessel().flight(null);
Expression.Bound e = Expression.bind(connection);
Type.Bound t = Type.bind(connection);
// above = meanAltitude > 1000, or false if the vessel is not loaded
Expression above = e.variable("above", t.bool());
Expression altitude =
e.call(connection.getCall(flight, "getMeanAltitude"));
Expression above1000m = e.blockWithVariables(
Arrays.asList(above),
Arrays.asList(
e.tryCatch(
e.assign(
above, e.greaterThan(altitude, e.constantDouble(1000))),
"KRPC", "ObjectNotLoadedException", null,
e.assign(above, e.constantBool(false))),
above));
Event event = connection.addEvent(above1000m);
synchronized (event.getCondition()) {
event.waitFor();
System.out.println("Altitude reached 1000m");
}
}
}
}
local krpc = require 'krpc'
local conn = krpc.connect()
local flight = conn.space_center.active_vessel:flight()
local Expression = conn.krpc.Expression
-- above = mean_altitude > 1000, or false if the vessel is not loaded
local above = Expression.variable('above', conn.krpc.Type.bool())
local mean_altitude = conn:get_call(flight.get_mean_altitude, flight)
local check = Expression.try_catch(
Expression.assign(above, Expression.greater_than(
Expression.call(mean_altitude), Expression.constant_double(1000))),
'KRPC', 'ObjectNotLoadedException', nil,
Expression.assign(above, Expression.constant_bool(false))
)
local above_1000m = Expression.block_with_variables({above}, {check, above})
-- Run the function, as this client has no events
if conn:run(above_1000m) then
print('Altitude reached 1000m')
end
import { connect } from "@krpc-org/krpc";
const conn = await connect();
const vessel = await conn.spaceCenter.getActiveVessel();
const flight = await vessel.flight();
const { Expression, Type } = conn.krpc;
// above = meanAltitude > 1000, or false if the vessel is not loaded
const above = await Expression.variable("above", await Type.bool());
const meanAltitude = conn.getCall(() => flight.getMeanAltitude());
const check = await Expression.tryCatch(
await Expression.assign(
above,
await Expression.greaterThan(
await Expression.call(meanAltitude),
await Expression.constantDouble(1000),
),
),
"KRPC",
"ObjectNotLoadedException",
null,
await Expression.assign(above, await Expression.constantBool(false)),
);
const above1000m = await Expression.blockWithVariables(
[above],
[check, above],
);
const event = await conn.addEvent(above1000m);
await event.wait();
console.log("Altitude reached 1000m");
The handler gives False, so the event does not fire while the vessel loads.
Procedures that pause. Some procedures pause execution and resume on a later tick, such as
SpaceCenter.WarpTo and SpaceCenter.LaunchVessel. Calling one is an error in any function.
The procedure keeps its effects up to the pause, so a WarpTo called this way leaves the game
warping.
Note
A future release is planned to support these procedures in server side functions.
Loops run to completion. A while loop runs to its end within a single tick, before the
game continues. A loop that never ends freezes the game for good. The only way out is to force
quit the game, which loses any progress since the last save. No compiler check can catch such a
loop, so bound every loop by a value that is certain to change.
Note
A future release is planned to stop a loop that runs for too long, with a time limit set in the server settings.
Null values. A null where the function needs a value raises a NullReferenceException
when the function runs. Examples are a null operand in arithmetic, and a null argument to a call.
Your program receives it as the closest built-in exception of its language.
Some procedures return null, such as Part.engine for a part that is not an engine. Compare
the result with null before using it.
A function can produce a null. A compiled null takes its type from where it is used, such as the other assignment to a variable or the other branch of a conditional:
def heaviest_engine():
best = None
for engine in vessel.parts.engines:
if best is None or engine.part.mass > best.part.mass:
best = engine
return best
var heaviest = connection.Run (
() => vessel.Parts.Engines.Count == 0 ? null
: vessel.Parts.Engines
.OrderBy (engine => engine.Part.Mass).Last ());
const heaviest = await conn.run(
({ vessel }) => {
let best = null;
for (const engine of vessel.parts.engines) {
if (best == null || engine.part.mass > best.part.mass) {
best = engine;
}
}
return best;
},
{ vessel },
);
Elsewhere, give a null its type with a type annotation or a cast.
Costs. A function is evaluated on the server as native code, and only its result crosses the network. Even a large function evaluates quickly. A function stream can run a full autopilot control loop every physics tick, as in Control Loops on the Server.
The Expression API#
The expression API builds a server side function node by node. The compilers use it under the hood.
Note
The C-nano and Lua clients have no events or streams, so their examples run each function
once, with krpc_run_function in C and conn:run in Lua.
Expression Trees#
A server side function is a tree of expression objects held on the server, built with the
static methods of the Expression class. The server compiles the tree to native code, so
evaluations are fast.
Each node is a constant, an embedded remote procedure call, an operator, a statement or a nested function. Statements are assignments, loops and if statements.
You use a tree in one of three ways:
An event, from a function that evaluates to a boolean. The server evaluates the function on each stream update, and triggers the event when it returns true.
A stream, from a function whose value can be sent to a client, such as a number, a string, a collection or an object. The value is recomputed on each stream update.
A run, which evaluates a function once, within a single physics tick, and returns its value. Useful for a function with side effects.
Two rules hold for every server side function:
Embedded remote procedure calls are re-invoked on every evaluation. Constants, and the values your program supplies when building the function, are fixed when the function is created.
The whole function is evaluated within a single physics tick. A function that reads the fuel level of every engine reads them all in the same tick.
Expression Objects#
The altitude event from the start of this guide has three nodes: an embedded call, a constant and a comparison:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight = vessel.flight()
# Convert a remote procedure call to a message,
# so it can be passed to the server
mean_altitude = conn.get_call(getattr, flight, "mean_altitude")
# Build the function on the server
expr = conn.krpc.Expression.greater_than(
conn.krpc.Expression.call(mean_altitude),
conn.krpc.Expression.constant_double(1000),
)
# Create an event from the function
event = conn.add_event(expr)
# Wait on the event
with event.condition:
event.wait()
print("Altitude reached 1000m")
using System;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using KRPC.Client.Services.SpaceCenter;
class Program {
public static void Main() {
var connection = new Connection();
var spaceCenter = connection.SpaceCenter();
var flight = spaceCenter.ActiveVessel.Flight();
// Get the remote procedure call as a message object,
// so it can be passed to the server
var meanAltitude = Connection.GetCall(() => flight.MeanAltitude);
// Build the function on the server
var e = Expression.Bind(connection);
var expr = e.GreaterThan(
e.Call(meanAltitude), e.ConstantDouble(1000));
var evnt = connection.AddEvent(expr);
lock (evnt.Condition) {
evnt.Wait();
Console.WriteLine("Altitude reached 1000m");
}
}
}
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto flight = sc.active_vessel().value().flight();
// Get the remote procedure call as a message object,
// so it can be passed to the server
auto mean_altitude = flight.mean_altitude_call();
// Build the function on the server
auto e = krpc::services::KRPC::Expression::bind(conn);
auto expr =
e.greater_than(e.call(mean_altitude), e.constant_double(1000));
auto event = krpc::add_event(expr);
event.acquire();
event.wait();
std::cout << "Altitude reached 1000m" << std::endl;
event.release();
}
#include <krpc_cnano.h>
#include <krpc_cnano/functions.h>
#include <krpc_cnano/services/krpc.h>
#include <krpc_cnano/services/space_center.h>
#include <stdio.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Altitude example") != KRPC_OK) return 1;
krpc_SpaceCenter_Vessel_t vessel;
krpc_SpaceCenter_ActiveVessel(conn, &vessel);
krpc_SpaceCenter_Flight_t flight;
krpc_SpaceCenter_Vessel_Flight(conn, &flight, vessel, KRPC_NULL);
// Fill in the remote procedure call as a message,
// so it can be passed to the server
krpc_schema_ProcedureCall mean_altitude;
krpc_SpaceCenter_Flight_MeanAltitude_call(&mean_altitude, flight);
// Build the function on the server
krpc_KRPC_Expression_t altitude, limit, expr;
krpc_KRPC_Expression_Call(conn, &altitude, &mean_altitude);
krpc_free_procedure_call(&mean_altitude);
krpc_KRPC_Expression_ConstantDouble(conn, &limit, 1000);
krpc_KRPC_Expression_GreaterThan(conn, &expr, altitude, limit);
// Run the function, as this client has no events
krpc_bytes_t data = KRPC_BYTES_NULL;
krpc_run_function(conn, &data, NULL, expr, NULL);
bool reached;
pb_istream_t stream = pb_istream_from_buffer(data.data, data.size);
krpc_decode_bool(&stream, &reached);
KRPC_FREE_BYTES(data);
if (reached) printf("Altitude reached 1000m\n");
krpc_disconnect(conn);
}
import krpc.client.Connection;
import krpc.client.Event;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
import krpc.schema.KRPC.ProcedureCall;
public class CustomEvent {
public static void main(String[] args) {
try (Connection connection = Connection.newInstance()) {
SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
Flight flight = spaceCenter.getActiveVessel().flight(null);
// Get the remote procedure call as a message object,
// so it can be passed to the server
ProcedureCall meanAltitude =
connection.getCall(flight, "getMeanAltitude");
// Build the function on the server
Expression.Bound e = Expression.bind(connection);
Expression expr = e.greaterThan(
e.call(meanAltitude), e.constantDouble(1000));
Event event = connection.addEvent(expr);
synchronized (event.getCondition()) {
event.waitFor();
System.out.println("Altitude reached 1000m");
}
}
}
}
local krpc = require 'krpc'
local conn = krpc.connect()
local flight = conn.space_center.active_vessel:flight()
-- Get the remote procedure call as a message,
-- so it can be passed to the server
local mean_altitude = conn:get_call(flight.get_mean_altitude, flight)
-- Build the function on the server
local Expression = conn.krpc.Expression
local expr = Expression.greater_than(
Expression.call(mean_altitude), Expression.constant_double(1000))
-- Run the function once
print('Above 1000m: ' .. tostring(conn:run(expr)))
import { connect } from "@krpc-org/krpc";
const conn = await connect();
const vessel = await conn.spaceCenter.getActiveVessel();
const flight = await vessel.flight();
// Get the remote procedure call as a message,
// so it can be passed to the server
const meanAltitude = conn.getCall(() => flight.getMeanAltitude());
// Build the function on the server
const Expression = conn.krpc.Expression;
const expr = await Expression.greaterThan(
await Expression.call(meanAltitude),
await Expression.constantDouble(1000),
);
const event = await conn.addEvent(expr);
await event.wait();
console.log("Altitude reached 1000m");
Two kinds of object appear here:
A procedure call message describes an RPC without invoking it. Each client builds one from a call written in its own language, as the examples show. Building a call message is a local operation.
An expression object is a node of the tree.
Expression.call()embeds a procedure call message, which the server invokes on each evaluation. A procedure with no return value embeds as a statement.
A call message carries its arguments, as the call for a stream does. A call template carries none,
for Expression.call_with_arguments() to give each one as an expression. See
Functions and Collections.
Each factory method is an RPC that creates one node on the server and returns a handle to it.
The factory methods are static methods of the Expression class, and each needs a
connection to send its RPC on:
Reach the class through the connection, as conn.krpc.Expression. Its methods use that
connection.
Expression.Bind(connection) returns the class bound to a connection. Its methods pass
the connection to each static method, so e.ConstantDouble(1000) needs no connection
argument.
krpc::services::KRPC::Expression::bind(conn) returns the class bound to a connection.
Its methods pass the connection to each static method, so e.constant_double(1000)
needs no connection argument.
Each factory method is a function that takes the connection first and the result second,
such as krpc_KRPC_Expression_ConstantDouble(conn, &limit, 1000).
Expression.bind(connection) returns an Expression.Bound for a connection. Its
methods pass the connection to each static method, so e.constantDouble(1000) needs no
connection argument.
Reach the class through the connection, as conn.krpc.Expression. Its functions use that
connection.
Reach the class through the connection, as conn.krpc.Expression. Each factory method
returns a Promise, so await each node before passing it to the next.
Operators and Types#
This truncates the altitude to a whole number of meters:
# Truncate the altitude to a whole number of meters
expr = expression.cast(expression.call(mean_altitude), types.int())
var e = Expression.Bind (connection);
var t = Type.Bind (connection);
// Truncate the altitude to a whole number of meters
var expr = e.Cast (e.Call (meanAltitude), t.Int ());
auto e = Expr::bind(conn);
auto t = KType::bind(conn);
// Truncate the altitude to a whole number of meters
auto expr = e.cast(e.call(mean_altitude), t.int_());
// Truncate the altitude to a whole number of meters
krpc_KRPC_Expression_t altitude, expr;
krpc_KRPC_Expression_Call(conn, &altitude, &mean_altitude);
krpc_free_procedure_call(&mean_altitude);
krpc_KRPC_Type_t int_type;
krpc_KRPC_Type_Int(conn, &int_type);
krpc_KRPC_Expression_Cast(conn, &expr, altitude, int_type);
Expression.Bound e = Expression.bind(connection);
Type.Bound t = Type.bind(connection);
// Truncate the altitude to a whole number of meters
Expression expr = e.cast(e.call(meanAltitude), t.int_());
-- Truncate the altitude to a whole number of meters
local expr = Expression.cast(
Expression.call(mean_altitude), conn.krpc.Type.int())
// Truncate the altitude to a whole number of meters
const expr = await Expression.cast(
await Expression.call(meanAltitude),
await Type.int(),
);
Expressions are statically typed, with the types of the server’s procedures. Numbers of different types convert to a common type, so an integer multiplies a double directly.
The same conversion applies to a procedure’s arguments, a collection’s elements, a structure’s
fields and an assigned variable, and each conversion must widen. Expression.cast()
converts a value explicitly, for example to narrow a double to an integer.
The Type class names types, including the classes, enumerations and structures a
service defines. Each type of constant has its own factory method, such as
Expression.constant_double().
A class, an enumeration, a structure or an exception is named by its service and its name, such
as "SpaceCenter", "Engine". Each procedure that takes the names has a variant that takes the
ids KRPC.get_services() reports, such as Type.class_type_by_id(). The C examples
use them.
Each operator has a factory method, such as Expression.add().
Function Streams#
A function whose value can be sent to a client can be streamed. A function with no value can be streamed too, and runs for its effects, as in Control Loops on the Server:
import time
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight = vessel.flight()
expression = conn.krpc.Expression
# Build a function that computes
# the vessel's altitude in kilometers
expr = expression.divide(
expression.call(conn.get_call(getattr, flight, "mean_altitude")),
expression.constant_double(1000),
)
# Stream the value of the function
stream = conn.add_stream(expr)
while True:
print("Altitude:", stream(), "km")
time.sleep(1)
using System;
using System.Threading;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using KRPC.Client.Services.SpaceCenter;
class Program {
public static void Main() {
var connection = new Connection();
var e = Expression.Bind(connection);
var spaceCenter = connection.SpaceCenter();
var flight = spaceCenter.ActiveVessel.Flight();
// Build a function that computes
// the vessel's altitude in kilometers
var expr = e.Divide(
e.Call(Connection.GetCall(() => flight.MeanAltitude)),
e.ConstantDouble(1000));
// Stream the value of the function
var stream = connection.AddStream<double>(expr);
while (true) {
Console.WriteLine("Altitude: " + stream.Get() + " km");
Thread.Sleep(1000);
}
}
}
#include <chrono>
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <thread>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto flight = sc.active_vessel().value().flight();
// Build a function that computes
// the vessel's altitude in kilometers
auto e = krpc::services::KRPC::Expression::bind(conn);
auto expr = e.divide(e.call(flight.mean_altitude_call()),
e.constant_double(1000));
// Stream the value of the function
auto stream = krpc::add_stream<double>(expr);
while (true) {
std::cout << "Altitude: " << stream() << " km" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
#include <krpc_cnano.h>
#include <krpc_cnano/functions.h>
#include <krpc_cnano/services/krpc.h>
#include <krpc_cnano/services/space_center.h>
#include <stdio.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Altitude in kilometers example") != KRPC_OK)
return 1;
krpc_SpaceCenter_Vessel_t vessel;
krpc_SpaceCenter_ActiveVessel(conn, &vessel);
krpc_SpaceCenter_Flight_t flight;
krpc_SpaceCenter_Vessel_Flight(conn, &flight, vessel, KRPC_NULL);
// Build a function that computes
// the vessel's altitude in kilometers
krpc_schema_ProcedureCall mean_altitude;
krpc_SpaceCenter_Flight_MeanAltitude_call(&mean_altitude, flight);
krpc_KRPC_Expression_t altitude, scale, expr;
krpc_KRPC_Expression_Call(conn, &altitude, &mean_altitude);
krpc_free_procedure_call(&mean_altitude);
krpc_KRPC_Expression_ConstantDouble(conn, &scale, 1000);
krpc_KRPC_Expression_Divide(conn, &expr, altitude, scale);
// Run the function in a loop, as this client has no streams
while (true) {
krpc_bytes_t data = KRPC_BYTES_NULL;
if (krpc_run_function(conn, &data, NULL, expr, NULL) != KRPC_OK) break;
double value;
pb_istream_t stream = pb_istream_from_buffer(data.data, data.size);
krpc_decode_double(&stream, &value);
KRPC_FREE_BYTES(data);
printf("Altitude: %.3f km\n", value);
}
krpc_disconnect(conn);
}
import krpc.client.Connection;
import krpc.client.Stream;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.SpaceCenter;
import krpc.client.services.SpaceCenter.Flight;
public class FunctionStream {
public static void main(String[] args) throws InterruptedException {
try (Connection connection = Connection.newInstance()) {
SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
Flight flight = spaceCenter.getActiveVessel().flight(null);
// Build a function that computes
// the vessel's altitude in kilometers
Expression.Bound e = Expression.bind(connection);
Expression expr = e.divide(
e.call(connection.getCall(flight, "getMeanAltitude")),
e.constantDouble(1000));
// Stream the value of the function
Stream<Double> stream = connection.addStream(expr);
while (true) {
System.out.println("Altitude: " + stream.get() + " km");
Thread.sleep(1000);
}
}
}
}
local krpc = require 'krpc'
local conn = krpc.connect()
local flight = conn.space_center.active_vessel:flight()
-- Build a function that computes
-- the vessel's altitude in kilometers
local Expression = conn.krpc.Expression
local mean_altitude = conn:get_call(flight.get_mean_altitude, flight)
local expr = Expression.divide(
Expression.call(mean_altitude), Expression.constant_double(1000))
-- Run the function in a loop, as this client has no streams
while true do
print(string.format('Altitude: %.3f km', conn:run(expr)))
end
import { connect } from "@krpc-org/krpc";
const conn = await connect();
const vessel = await conn.spaceCenter.getActiveVessel();
const flight = await vessel.flight();
// Build a function that computes
// the vessel's altitude in kilometers
const Expression = conn.krpc.Expression;
const meanAltitude = conn.getCall(() => flight.getMeanAltitude());
const expr = await Expression.divide(
await Expression.call(meanAltitude),
await Expression.constantDouble(1000),
);
// Stream the value of the function
/** @type {import("@krpc-org/krpc").Stream<number>} */
const stream = await conn.addStream(expr);
stream.addCallback((x) => console.log(`Altitude: ${x.toFixed(3)} km`));
Some clients take the type of the stream’s values as a type argument, and others read the function’s return type from the server. A function stream behaves like any other stream, and its rate can be limited in the usual way.
Functions and Collections#
This builds the “any engine out of fuel” event from earlier. The call names the procedure through
the Engine class, with no engine:
import krpc
conn = krpc.connect()
expression = conn.krpc.Expression
types = conn.krpc.Type
vessel = conn.space_center.active_vessel
# A function taking an engine, returning true if it is out of fuel
engine = expression.parameter(
"engine", types.class_type("SpaceCenter", "Engine")
)
has_fuel = conn.space_center.Engine.has_fuel
out_of_fuel = expression.lambda_(
[engine],
expression.not_(expression.call_with_arguments(has_fuel, {0: engine})),
)
# Whether any engine satisfies it
engines = conn.get_call(getattr, vessel.parts, "engines")
expr = expression.any(expression.call(engines), out_of_fuel)
event = conn.add_event(expr)
with event.condition:
event.wait()
print("An engine has run out of fuel")
using System;
using System.Collections.Generic;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using Type = KRPC.Client.Services.KRPC.Type;
using KRPC.Client.Services.SpaceCenter;
class Program {
public static void Main() {
var connection = new Connection();
var e = Expression.Bind(connection);
var t = Type.Bind(connection);
var vessel = connection.SpaceCenter().ActiveVessel;
// A function taking an engine, returning true if it is out of fuel
var engine = e.Parameter(
"engine", t.ClassType("SpaceCenter", "Engine"));
var hasFuel = Connection.GetCallTemplate((Engine x) => x.HasFuel);
var outOfFuel = e.Lambda(new List<Expression> { engine },
e.Not(e.CallWithArguments(hasFuel,
new Dictionary<int, Expression> { { 0, engine } })));
// Whether any engine satisfies it
var engines = Connection.GetCall(() => vessel.Parts.Engines);
var expr = e.Any(e.Call(engines), outOfFuel);
var evnt = connection.AddEvent(expr);
lock (evnt.Condition) {
evnt.Wait();
Console.WriteLine("An engine has run out of fuel");
}
}
}
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <map>
#include <vector>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
typedef krpc::services::KRPC::Expression Expr;
typedef krpc::services::KRPC::Type KType;
auto e = Expr::bind(conn);
auto t = KType::bind(conn);
// A function taking an engine, returning true if it is out of fuel
auto engine =
e.parameter("engine", t.class_type("SpaceCenter", "Engine"));
auto has_fuel =
krpc::services::SpaceCenter::Engine::has_fuel_call_template();
auto out_of_fuel =
e.lambda(std::vector<Expr>({engine}),
e.not_(e.call_with_arguments(
has_fuel, std::map<int32_t, Expr>({{0, engine}}))));
// Whether any engine satisfies it
auto engines = vessel.parts().engines_call();
auto expr = e.any(e.call(engines), out_of_fuel);
auto event = krpc::add_event(expr);
event.acquire();
event.wait();
std::cout << "An engine has run out of fuel" << std::endl;
event.release();
}
#include <krpc_cnano.h>
#include <krpc_cnano/functions.h>
#include <krpc_cnano/services/krpc.h>
#include <krpc_cnano/services/space_center.h>
#include <stdio.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Out of fuel example") != KRPC_OK) return 1;
krpc_SpaceCenter_Vessel_t vessel;
krpc_SpaceCenter_ActiveVessel(conn, &vessel);
krpc_SpaceCenter_Parts_t parts;
krpc_SpaceCenter_Vessel_Parts(conn, &parts, vessel);
// A function taking an engine, returning true if it is out of fuel
krpc_KRPC_Type_t engine_type;
krpc_KRPC_Type_ClassTypeById(conn, &engine_type,
KRPC_CLASS_SPACECENTER_ENGINE);
krpc_KRPC_Expression_t engine;
krpc_KRPC_Expression_Parameter(conn, &engine, "engine", engine_type);
krpc_schema_ProcedureCall has_fuel;
krpc_SpaceCenter_Engine_HasFuel_call_template(&has_fuel);
krpc_dictionary_entry_int32_object_t entries[1] = {{0, engine}};
krpc_dictionary_int32_object_t arguments = {1, entries};
krpc_KRPC_Expression_t engine_has_fuel, no_fuel, out_of_fuel;
krpc_KRPC_Expression_CallWithArguments(conn, &engine_has_fuel, &has_fuel,
&arguments);
krpc_free_procedure_call(&has_fuel);
krpc_KRPC_Expression_Not(conn, &no_fuel, engine_has_fuel);
krpc_list_object_t parameters = {1, &engine};
krpc_KRPC_Expression_Lambda(conn, &out_of_fuel, ¶meters, no_fuel);
// Whether any engine satisfies it
krpc_schema_ProcedureCall engines_call;
krpc_SpaceCenter_Parts_Engines_call(&engines_call, parts);
krpc_KRPC_Expression_t engines, expr;
krpc_KRPC_Expression_Call(conn, &engines, &engines_call);
krpc_free_procedure_call(&engines_call);
krpc_KRPC_Expression_Any(conn, &expr, engines, out_of_fuel);
// Run the function, as this client has no events
krpc_bytes_t data = KRPC_BYTES_NULL;
krpc_run_function(conn, &data, NULL, expr, NULL);
bool any_out_of_fuel;
pb_istream_t stream = pb_istream_from_buffer(data.data, data.size);
krpc_decode_bool(&stream, &any_out_of_fuel);
KRPC_FREE_BYTES(data);
if (any_out_of_fuel) printf("An engine has run out of fuel\n");
krpc_disconnect(conn);
}
import krpc.client.Connection;
import krpc.client.Event;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.KRPC.Type;
import krpc.client.services.SpaceCenter;
import krpc.schema.KRPC.ProcedureCall;
import java.util.Arrays;
import java.util.Collections;
public class CollectionEvent {
public static void main(String[] args) {
try (Connection connection = Connection.newInstance()) {
SpaceCenter spaceCenter = SpaceCenter.newInstance(connection);
SpaceCenter.Vessel vessel = spaceCenter.getActiveVessel();
Expression.Bound e = Expression.bind(connection);
Type.Bound t = Type.bind(connection);
// A function taking an engine, returning true if it is out of fuel
Expression engine =
e.parameter("engine", t.classType("SpaceCenter", "Engine"));
ProcedureCall hasFuel = connection.getCallTemplate(
SpaceCenter.Engine.class, "getHasFuel");
Expression outOfFuel = e.lambda(Arrays.asList(engine),
e.not(e.callWithArguments(
hasFuel, Collections.singletonMap(0, engine))));
// Whether any engine satisfies it
ProcedureCall engines =
connection.getCall(vessel.getParts(), "getEngines");
Expression expr = e.any(e.call(engines), outOfFuel);
Event event = connection.addEvent(expr);
synchronized (event.getCondition()) {
event.waitFor();
System.out.println("An engine has run out of fuel");
}
}
}
}
local krpc = require 'krpc'
local Map = require 'pl.Map'
local conn = krpc.connect()
local Expression = conn.krpc.Expression
local parts = conn.space_center.active_vessel.parts
-- A function taking an engine, returning true if it is out of fuel
local engine = Expression.parameter(
'engine', conn.krpc.Type.class_type('SpaceCenter', 'Engine'))
local has_fuel = conn.space_center.Engine.get_has_fuel
-- A Lua keyword is not a field name, so not is reached by its string
local out_of_fuel = Expression.lambda(
{engine},
Expression['not'](
Expression.call_with_arguments(has_fuel, Map{[0] = engine}))
)
-- Whether any engine satisfies it
local engines = conn:get_call(parts.get_engines, parts)
local expr = Expression.any(Expression.call(engines), out_of_fuel)
print('An engine is out of fuel: ' .. tostring(conn:run(expr)))
import { connect } from "@krpc-org/krpc";
const conn = await connect();
const { Expression, Type } = conn.krpc;
const vessel = await conn.spaceCenter.getActiveVessel();
const parts = await vessel.getParts();
// A function taking an engine, returning true if it is out of fuel
const engine = await Expression.parameter(
"engine",
await Type.classType("SpaceCenter", "Engine"),
);
const hasFuel = conn.spaceCenter.Engine.prototype.getHasFuel;
const outOfFuel = await Expression.lambda(
[engine],
await Expression.not(
await Expression.callWithArguments(hasFuel, new Map([[0, engine]])),
),
);
// Whether any engine satisfies it
const engines = conn.getCall(() => parts.getEngines());
const expr = await Expression.any(
await Expression.call(engines),
outOfFuel,
);
const event = await conn.addEvent(expr);
await event.wait();
console.log("An engine has run out of fuel");
A function passed to a collection operation is built from two pieces:
Expression.parameter()creates a named, typed parameter. The type can be a class, so a parameter can be anEngine.Expression.lambda_()combines a list of parameters and a body into a function. In the body, the parameter expressions stand for the arguments.
To call an RPC on each element, take the call’s instance from the function’s parameter.
Expression.call_with_arguments() embeds a call with its arguments given as expressions.
Each expression is keyed by the position of its parameter, and position 0 is the instance.
The call is a call template, which names the procedure through its class and carries no
arguments. In Python, Lua and JavaScript, the member itself stands for its call template, as
has_fuel does in the Python example. A position without an expression takes the parameter’s
default. A call that carries arguments, such as one built from an engine, raises an error.
Expression.invoke() calls a function directly, binding values to its parameters by name.
A function from Expression.lambda_() can also be run on its own. Run passes its arguments
to the function’s parameters in order, and Expression.parameter_types gives their types.
Expression.select() applies a function to every element, and Expression.where()
filters by a predicate. Both produce lazy sequences, which a client cannot decode. Convert one
with Expression.to_list() or Expression.to_set() before streaming it. The
aggregations, such as Expression.sum() and Expression.any(), take lazy sequences
directly.
The Expression class has the other usual collection operations, such as ordering,
grouping and set operations, and a constructor for each kind of collection. A function can change
a collection in place, with operations such as Expression.append() and
Expression.remove().
A dictionary is iterated through its keys or its values. Expression.dictionary_keys()
and Expression.dictionary_values() each produce a list. Passing a dictionary to a
collection operation is an error that points at them. Expression.contains_key() tests for
a key. Expression.get() of a missing key raises a KeyNotFoundException, and of a list
index out of range an IndexOutOfRangeException.
The index into a tuple must be a constant. The elements of a tuple differ in type, and
Expression.get() takes its result type from the index. A list or a dictionary takes any
index expression.
Structures#
A structure a service defines is a value like any other. A function can return, stream, pass
and build one. Expression.get_field() reads a field by name:
# The Name field of a structure a call returns
expr = expression.get_field(expression.call(site_info), "Name")
var e = Expression.Bind (connection);
// The Name field of a structure a call returns
var expr = e.GetField (e.Call (siteInfo), "Name");
auto e = Expr::bind(conn);
// The Name field of a structure a call returns
auto expr = e.get_field(e.call(site_info), "Name");
// The Name field of a structure a call returns
krpc_KRPC_Expression_t value, expr;
krpc_KRPC_Expression_Call(conn, &value, &site_info);
krpc_free_procedure_call(&site_info);
krpc_KRPC_Expression_GetFieldByIndex(
conn, &expr, value, KRPC_FIELD_SPACECENTER_COMMNODE_NAME);
Expression.Bound e = Expression.bind(connection);
// The Name field of a structure a call returns
Expression expr = e.getField(e.call(siteInfo), "Name");
-- The Name field of a structure a call returns
local expr = Expression.get_field(Expression.call(site_info), 'Name')
// The Name field of a structure a call returns
const expr = await Expression.getField(
await Expression.call(siteInfo),
"Name",
);
Expression.create_struct() builds a structure from its type and its field values, in the
order the structure declares them. A field’s name is the one the service declares, as shown in
the API documentation. Expression.get_field_by_index() reads a field by its position in
that order, counting from 0.
The compilers produce both nodes from ordinary syntax. Reading a field of a structure compiles
to Expression.get_field(), and constructing one compiles to
Expression.create_struct().
Statements, Variables and Loops#
This builds and runs total = 0; for x in [1, 2, 3]: total += x, which returns 6:
import krpc
conn = krpc.connect()
expression = conn.krpc.Expression
types = conn.krpc.Type
# total = 0; for x in [1, 2, 3]: total += x
total = expression.variable("total", types.int())
x = expression.variable("x", types.int())
values = expression.create_list(
[expression.constant_int(i) for i in [1, 2, 3]]
)
program = expression.block_with_variables(
[total, x],
[
expression.assign(total, expression.constant_int(0)),
expression.for_each(
x, values, expression.assign(total, expression.add(total, x))
),
total,
],
)
print(conn.run(program))
using System;
using System.Collections.Generic;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using Type = KRPC.Client.Services.KRPC.Type;
class Program {
public static void Main() {
var connection = new Connection();
var e = Expression.Bind(connection);
var t = Type.Bind(connection);
// total = 0; foreach (var x in [1, 2, 3]) total += x;
var total = e.Variable("total", t.Int());
var x = e.Variable("x", t.Int());
var values = e.CreateList(new List<Expression> {
e.ConstantInt(1), e.ConstantInt(2), e.ConstantInt(3)
});
var program = e.BlockWithVariables(
new List<Expression> { total, x },
new List<Expression> {
e.Assign(total, e.ConstantInt(0)),
e.ForEach(x, values, e.Assign(total, e.Add(total, x))),
total
});
Console.WriteLine(connection.Run<int>(program));
}
}
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <vector>
int main() {
auto conn = krpc::connect();
typedef krpc::services::KRPC::Expression Expr;
typedef krpc::services::KRPC::Type KType;
auto e = Expr::bind(conn);
auto t = KType::bind(conn);
// total = 0; for (auto x : {1, 2, 3}) total += x;
auto total = e.variable("total", t.int_());
auto x = e.variable("x", t.int_());
auto values = e.create_list(std::vector<Expr>(
{e.constant_int(1), e.constant_int(2), e.constant_int(3)}));
auto program = e.block_with_variables(
std::vector<Expr>({total, x}),
std::vector<Expr>(
{e.assign(total, e.constant_int(0)),
e.for_each(x, values, e.assign(total, e.add(total, x))),
total}));
std::cout << krpc::run<int32_t>(program) << std::endl;
}
#include <krpc_cnano.h>
#include <krpc_cnano/functions.h>
#include <krpc_cnano/services/krpc.h>
#include <stdio.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Function statements example") != KRPC_OK)
return 1;
// total = 0; for x in {1, 2, 3}: total += x;
krpc_KRPC_Type_t int_type;
krpc_KRPC_Type_Int(conn, &int_type);
krpc_KRPC_Expression_t total, x;
krpc_KRPC_Expression_Variable(conn, &total, "total", int_type);
krpc_KRPC_Expression_Variable(conn, &x, "x", int_type);
krpc_KRPC_Expression_t items[3];
for (int i = 0; i < 3; i++)
krpc_KRPC_Expression_ConstantInt(conn, &items[i], i + 1);
krpc_list_object_t elements = {3, items};
krpc_KRPC_Expression_t values;
krpc_KRPC_Expression_CreateList(conn, &values, &elements);
krpc_KRPC_Expression_t zero, start, sum, add, loop;
krpc_KRPC_Expression_ConstantInt(conn, &zero, 0);
krpc_KRPC_Expression_Assign(conn, &start, total, zero);
krpc_KRPC_Expression_Add(conn, &sum, total, x);
krpc_KRPC_Expression_Assign(conn, &add, total, sum);
krpc_KRPC_Expression_ForEach(conn, &loop, x, values, add);
krpc_KRPC_Expression_t variable_items[2] = {total, x};
krpc_KRPC_Expression_t statement_items[3] = {start, loop, total};
krpc_list_object_t variables = {2, variable_items};
krpc_list_object_t statements = {3, statement_items};
krpc_KRPC_Expression_t program;
krpc_KRPC_Expression_BlockWithVariables(conn, &program, &variables,
&statements);
krpc_bytes_t data = KRPC_BYTES_NULL;
krpc_run_function(conn, &data, NULL, program, NULL);
int32_t result;
pb_istream_t stream = pb_istream_from_buffer(data.data, data.size);
krpc_decode_int32(&stream, &result);
KRPC_FREE_BYTES(data);
printf("%d\n", (int)result);
krpc_disconnect(conn);
}
import krpc.client.Connection;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.KRPC.Type;
import java.util.Arrays;
public class FunctionStatements {
public static void main(String[] args) {
try (Connection connection = Connection.newInstance()) {
Expression.Bound e = Expression.bind(connection);
Type.Bound t = Type.bind(connection);
// total = 0; for (int x : new int[] {1, 2, 3}) total += x;
Expression total = e.variable("total", t.int_());
Expression x = e.variable("x", t.int_());
Expression values = e.createList(Arrays.asList(
e.constantInt(1), e.constantInt(2), e.constantInt(3)));
Expression program = e.blockWithVariables(
Arrays.asList(total, x),
Arrays.asList(
e.assign(total, e.constantInt(0)),
e.forEach(x, values, e.assign(total, e.add(total, x))),
total));
int result = connection.run(program);
System.out.println(result);
}
}
}
local krpc = require 'krpc'
local conn = krpc.connect()
local Expression = conn.krpc.Expression
local Type = conn.krpc.Type
-- total = 0; for x in {1, 2, 3} do total = total + x end
local total = Expression.variable('total', Type.int())
local x = Expression.variable('x', Type.int())
local values = Expression.create_list({
Expression.constant_int(1),
Expression.constant_int(2),
Expression.constant_int(3)
})
local program = Expression.block_with_variables(
{total, x},
{
Expression.assign(total, Expression.constant_int(0)),
Expression.for_each(
x, values, Expression.assign(total, Expression.add(total, x))),
total
}
)
print(conn:run(program))
import { connect } from "@krpc-org/krpc";
const conn = await connect();
const { Expression, Type } = conn.krpc;
// let total = 0; for (const x of [1, 2, 3]) total = total + x;
const total = await Expression.variable("total", await Type.int());
const x = await Expression.variable("x", await Type.int());
const values = await Expression.createList([
await Expression.constantInt(1),
await Expression.constantInt(2),
await Expression.constantInt(3),
]);
const program = await Expression.blockWithVariables(
[total, x],
[
await Expression.assign(total, await Expression.constantInt(0)),
await Expression.forEach(
x,
values,
await Expression.assign(total, await Expression.add(total, x)),
),
total,
],
);
console.log(await conn.run(program));
Statements are ordinary expression nodes. Expression.block_with_variables() sequences
statements and declares local variables, and its value is the value of its last statement.
The other statements, such as assignments, if statements, loops and early returns, each have a factory method. A call to a procedure without a return value is a statement, run for its effects.
Match and Switch Statements#
This loop adds 10 to a total for the values 1 and 2, and 1 for any other value. It returns 21:
import krpc
conn = krpc.connect()
expression = conn.krpc.Expression
types = conn.krpc.Type
# total = 0
# for x in [1, 2, 3]:
# match x:
# case 1 | 2: total += 10
# case _: total += 1
total = expression.variable("total", types.int())
x = expression.variable("x", types.int())
values = expression.create_list(
[expression.constant_int(i) for i in [1, 2, 3]]
)
body = expression.match(
x,
[[expression.constant_int(1), expression.constant_int(2)], []],
[
expression.assign(
total, expression.add(total, expression.constant_int(10))
),
expression.assign(
total, expression.add(total, expression.constant_int(1))
),
],
)
program = expression.block_with_variables(
[total, x],
[
expression.assign(total, expression.constant_int(0)),
expression.for_each(x, values, body),
total,
],
)
print(conn.run(program))
using System;
using System.Collections.Generic;
using KRPC.Client;
using KRPC.Client.Services.KRPC;
using Type = KRPC.Client.Services.KRPC.Type;
class Program {
public static void Main() {
var connection = new Connection();
var e = Expression.Bind(connection);
var t = Type.Bind(connection);
// total = 0;
// foreach (var x in [1, 2, 3])
// switch (x) {
// case 1: case 2: total += 10; break;
// default: total += 1; break;
// }
var total = e.Variable("total", t.Int());
var x = e.Variable("x", t.Int());
var values = e.CreateList(new List<Expression> {
e.ConstantInt(1), e.ConstantInt(2), e.ConstantInt(3)
});
var body = e.Match(
x,
new List<IList<Expression>> {
new List<Expression> { e.ConstantInt(1), e.ConstantInt(2) },
new List<Expression>()
},
new List<Expression> {
e.Assign(total, e.Add(total, e.ConstantInt(10))),
e.Assign(total, e.Add(total, e.ConstantInt(1)))
});
var program = e.BlockWithVariables(
new List<Expression> { total, x },
new List<Expression> {
e.Assign(total, e.ConstantInt(0)),
e.ForEach(x, values, body),
total
});
Console.WriteLine(connection.Run<int>(program));
}
}
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <vector>
int main() {
auto conn = krpc::connect();
typedef krpc::services::KRPC::Expression Expr;
typedef krpc::services::KRPC::Type KType;
auto e = Expr::bind(conn);
auto t = KType::bind(conn);
// total = 0;
// for (auto x : {1, 2, 3})
// switch (x) {
// case 1: case 2: total += 10; break;
// default: total += 1; break;
// }
auto total = e.variable("total", t.int_());
auto x = e.variable("x", t.int_());
auto values = e.create_list(std::vector<Expr>(
{e.constant_int(1), e.constant_int(2), e.constant_int(3)}));
auto body =
e.match(x,
std::vector<std::vector<Expr>>(
{{e.constant_int(1), e.constant_int(2)}, {}}),
std::vector<Expr>(
{e.assign(total, e.add(total, e.constant_int(10))),
e.assign(total, e.add(total, e.constant_int(1)))}));
auto program = e.block_with_variables(
std::vector<Expr>({total, x}),
std::vector<Expr>({e.assign(total, e.constant_int(0)),
e.for_each(x, values, body), total}));
std::cout << krpc::run<int32_t>(program) << std::endl;
}
#include <krpc_cnano.h>
#include <krpc_cnano/functions.h>
#include <krpc_cnano/services/krpc.h>
#include <stdio.h>
int main() {
krpc_connection_t conn;
if (krpc_open_serial(&conn, "COM0") != KRPC_OK) return 1;
if (krpc_connect(conn, "Switch statement example") != KRPC_OK) return 1;
// total = 0;
// for x in {1, 2, 3}:
// switch (x) {
// case 1: case 2: total += 10; break;
// default: total += 1; break;
// }
krpc_KRPC_Type_t int_type;
krpc_KRPC_Type_Int(conn, &int_type);
krpc_KRPC_Expression_t total, x;
krpc_KRPC_Expression_Variable(conn, &total, "total", int_type);
krpc_KRPC_Expression_Variable(conn, &x, "x", int_type);
krpc_KRPC_Expression_t items[3];
for (int i = 0; i < 3; i++)
krpc_KRPC_Expression_ConstantInt(conn, &items[i], i + 1);
krpc_list_object_t elements = {3, items};
krpc_KRPC_Expression_t values;
krpc_KRPC_Expression_CreateList(conn, &values, &elements);
// The first case tests 1 and 2, and the second, with no test values, is
// the default
krpc_list_object_t case_items[2] = {{2, items}, {0, NULL}};
krpc_list_list_object_t cases = {2, case_items};
krpc_KRPC_Expression_t ten, one, plus_ten, plus_one, bodies_items[2];
krpc_KRPC_Expression_ConstantInt(conn, &ten, 10);
krpc_KRPC_Expression_ConstantInt(conn, &one, 1);
krpc_KRPC_Expression_Add(conn, &plus_ten, total, ten);
krpc_KRPC_Expression_Add(conn, &plus_one, total, one);
krpc_KRPC_Expression_Assign(conn, &bodies_items[0], total, plus_ten);
krpc_KRPC_Expression_Assign(conn, &bodies_items[1], total, plus_one);
krpc_list_object_t bodies = {2, bodies_items};
krpc_KRPC_Expression_t body;
krpc_KRPC_Expression_Match(conn, &body, x, &cases, &bodies);
krpc_KRPC_Expression_t zero, start, loop;
krpc_KRPC_Expression_ConstantInt(conn, &zero, 0);
krpc_KRPC_Expression_Assign(conn, &start, total, zero);
krpc_KRPC_Expression_ForEach(conn, &loop, x, values, body);
krpc_KRPC_Expression_t variable_items[2] = {total, x};
krpc_KRPC_Expression_t statement_items[3] = {start, loop, total};
krpc_list_object_t variables = {2, variable_items};
krpc_list_object_t statements = {3, statement_items};
krpc_KRPC_Expression_t program;
krpc_KRPC_Expression_BlockWithVariables(conn, &program, &variables,
&statements);
krpc_bytes_t data = KRPC_BYTES_NULL;
krpc_run_function(conn, &data, NULL, program, NULL);
int32_t result;
pb_istream_t stream = pb_istream_from_buffer(data.data, data.size);
krpc_decode_int32(&stream, &result);
KRPC_FREE_BYTES(data);
printf("%d\n", (int)result);
krpc_disconnect(conn);
}
import krpc.client.Connection;
import krpc.client.services.KRPC.Expression;
import krpc.client.services.KRPC.Type;
import java.util.Arrays;
import java.util.Collections;
public class SwitchStatement {
public static void main(String[] args) {
try (Connection connection = Connection.newInstance()) {
Expression.Bound e = Expression.bind(connection);
Type.Bound t = Type.bind(connection);
// total = 0;
// for (int x : new int[] {1, 2, 3})
// switch (x) {
// case 1: case 2: total += 10; break;
// default: total += 1; break;
// }
Expression total = e.variable("total", t.int_());
Expression x = e.variable("x", t.int_());
Expression values = e.createList(Arrays.asList(
e.constantInt(1), e.constantInt(2), e.constantInt(3)));
Expression body = e.match(
x,
Arrays.asList(
Arrays.asList(e.constantInt(1), e.constantInt(2)),
Collections.<Expression>emptyList()),
Arrays.asList(
e.assign(total, e.add(total, e.constantInt(10))),
e.assign(total, e.add(total, e.constantInt(1)))));
Expression program = e.blockWithVariables(
Arrays.asList(total, x),
Arrays.asList(
e.assign(total, e.constantInt(0)),
e.forEach(x, values, body),
total));
int result = connection.run(program);
System.out.println(result);
}
}
}
local krpc = require 'krpc'
local conn = krpc.connect()
local Expression = conn.krpc.Expression
local Type = conn.krpc.Type
-- total = 0
-- for x in {1, 2, 3} do
-- if x == 1 or x == 2 then total = total + 10 else total = total + 1 end
-- end
local total = Expression.variable('total', Type.int())
local x = Expression.variable('x', Type.int())
local values = Expression.create_list({
Expression.constant_int(1),
Expression.constant_int(2),
Expression.constant_int(3)
})
local body = Expression.match(
x,
{{Expression.constant_int(1), Expression.constant_int(2)}, {}},
{
Expression.assign(
total, Expression.add(total, Expression.constant_int(10))),
Expression.assign(
total, Expression.add(total, Expression.constant_int(1)))
}
)
local program = Expression.block_with_variables(
{total, x},
{
Expression.assign(total, Expression.constant_int(0)),
Expression.for_each(x, values, body),
total
}
)
print(conn:run(program))
import { connect } from "@krpc-org/krpc";
const conn = await connect();
const { Expression, Type } = conn.krpc;
// let total = 0;
// for (const x of [1, 2, 3])
// switch (x) {
// case 1: case 2: total = total + 10; break;
// default: total = total + 1; break;
// }
const total = await Expression.variable("total", await Type.int());
const x = await Expression.variable("x", await Type.int());
const values = await Expression.createList([
await Expression.constantInt(1),
await Expression.constantInt(2),
await Expression.constantInt(3),
]);
const body = await Expression.match(
x,
[[await Expression.constantInt(1), await Expression.constantInt(2)], []],
[
await Expression.assign(
total,
await Expression.add(total, await Expression.constantInt(10)),
),
await Expression.assign(
total,
await Expression.add(total, await Expression.constantInt(1)),
),
],
);
const program = await Expression.blockWithVariables(
[total, x],
[
await Expression.assign(total, await Expression.constantInt(0)),
await Expression.forEach(x, values, body),
total,
],
);
console.log(await conn.run(program));
Expression.match() takes the value, the test values of each case and the body of each
case. It runs the body of the first case with a test value equal to the value, as
Expression.equal() compares them. The test values are evaluated in order, up to the first
match. A case with no test values is the default. A Expression.break_() in a body ends the
enclosing loop, as in Python’s match. The Python client compiles the cases of a match
statement that have no guard to it.
Expression.switch() takes the same arguments, and behaves as switch in C, C++, Java and
JavaScript. It runs the bodies from the matching case on, and a Expression.break_() in a
body ends the switch.
A switch in C, C++, C# or Java becomes a Expression.switch() with its breaks kept. When
each case ends in a break, as in the example, it can also become a Expression.match() with
the breaks dropped.
Object Constants#
Expression.constant_object() embeds a reference to an object, such as a vessel, a reference
frame or an engine. A function can compare it for equality, or pass it to a call built with
Expression.call_with_arguments(). This event fires when the vessel’s target changes to a
particular vessel:
target = conn.get_call(getattr, conn.space_center, "target_vessel")
expr = expression.equal(
expression.call(target),
expression.constant_object(krpc.get_object_id(some_vessel)),
)
event = conn.add_event(expr)
var e = Expression.Bind (connection);
var target = Connection.GetCall (() => spaceCenter.TargetVessel);
var expr = e.Equal (
e.Call (target),
e.ConstantObject (RemoteObject.GetObjectId (someVessel)));
var evnt = connection.AddEvent (expr);
auto e = Expr::bind(conn);
auto target = sc.target_vessel_call();
auto expr = e.equal(e.call(target),
e.constant_object(krpc::get_object_id(some_vessel)));
auto event = krpc::add_event(expr);
krpc_schema_ProcedureCall target;
krpc_SpaceCenter_TargetVessel_call(&target);
krpc_KRPC_Expression_t current, wanted, expr;
krpc_KRPC_Expression_Call(conn, ¤t, &target);
krpc_free_procedure_call(&target);
krpc_KRPC_Expression_ConstantObject(conn, &wanted, some_vessel);
krpc_KRPC_Expression_Equal(conn, &expr, current, wanted);
// Run the function, as this client has no events
krpc_bytes_t data = KRPC_BYTES_NULL;
krpc_run_function(conn, &data, NULL, expr, NULL);
bool is_target;
pb_istream_t stream = pb_istream_from_buffer(data.data, data.size);
krpc_decode_bool(&stream, &is_target);
KRPC_FREE_BYTES(data);
Expression.Bound e = Expression.bind(connection);
ProcedureCall target =
connection.getCall(SpaceCenter.class, "getTargetVessel");
Expression expr = e.equal(
e.call(target),
e.constantObject(RemoteObject.getObjectId(someVessel)));
Event event = connection.addEvent(expr);
local target = conn:get_call(
conn.space_center.get_target_vessel, conn.space_center)
local expr = Expression.equal(
Expression.call(target),
Expression.constant_object(krpc.get_object_id(some_vessel))
)
local is_target = conn:run(expr)
const target = conn.getCall(() => conn.spaceCenter.getTargetVessel());
const expr = await Expression.equal(
await Expression.call(target),
await Expression.constantObject(getObjectId(someVessel)),
);
const event = await conn.addEvent(expr);
Expression.constant_object() takes the object’s identifier in the communication protocol.
Each client has a function that returns it: krpc.get_object_id in Python and Lua,
RemoteObject.GetObjectId in C#, krpc::get_object_id in C++, RemoteObject.getObjectId
in Java and getObjectId in JavaScript. In C, an object’s handle is its identifier. The
compilers embed a captured remote object this way.
Exceptions in the Expression API#
Expression.throw() raises an exception, named by its service and class. This builds the
fuel check from Exceptions:
amount = conn.get_call(vessel.resources.amount, "LiquidFuel")
expr = expression.if_then(
expression.less_than(
expression.call(amount), expression.constant_double(100)
),
expression.throw(
"KRPC",
"InvalidOperationException",
expression.constant_string("not enough fuel"),
),
)
conn.run(expr)
var e = Expression.Bind (connection);
var amount = Connection.GetCall (
() => vessel.Resources.Amount ("LiquidFuel"));
var expr = e.IfThen (
e.LessThan (e.Call (amount), e.ConstantDouble (100)),
e.Throw ("KRPC", "InvalidOperationException",
e.ConstantString ("not enough fuel")));
connection.Run (expr);
auto e = Expr::bind(conn);
auto amount = vessel.resources().amount_call("LiquidFuel");
auto expr = e.if_then(e.less_than(e.call(amount), e.constant_double(100)),
e.throw_("KRPC", "InvalidOperationException",
e.constant_string("not enough fuel")));
krpc::run(expr);
krpc_schema_ProcedureCall amount;
krpc_SpaceCenter_Resources_Amount_call(&amount, resources, "LiquidFuel");
krpc_KRPC_Expression_t fuel, limit, low, message, thrown, expr;
krpc_KRPC_Expression_Call(conn, &fuel, &amount);
krpc_free_procedure_call(&amount);
krpc_KRPC_Expression_ConstantDouble(conn, &limit, 100);
krpc_KRPC_Expression_LessThan(conn, &low, fuel, limit);
krpc_KRPC_Expression_ConstantString(conn, &message, "not enough fuel");
krpc_KRPC_Expression_ThrowById(
conn, &thrown, KRPC_EXCEPTION_KRPC_INVALIDOPERATIONEXCEPTION,
message);
krpc_KRPC_Expression_IfThen(conn, &expr, low, thrown);
krpc_run_function(conn, NULL, NULL, expr, NULL);
Expression.Bound e = Expression.bind(connection);
ProcedureCall amount = connection.getCall(
vessel.getResources(), "amount", "LiquidFuel");
Expression expr = e.ifThen(
e.lessThan(e.call(amount), e.constantDouble(100)),
e.throw_("KRPC", "InvalidOperationException",
e.constantString("not enough fuel")));
connection.run(expr);
local amount = conn:get_call(resources.amount, resources, 'LiquidFuel')
local expr = Expression.if_then(
Expression.less_than(
Expression.call(amount), Expression.constant_double(100)),
Expression.throw('KRPC', 'InvalidOperationException',
Expression.constant_string('not enough fuel'))
)
conn:run(expr)
const amount = conn.getCall(() => resources.amount("LiquidFuel"));
const expr = await Expression.ifThen(
await Expression.lessThan(
await Expression.call(amount),
await Expression.constantDouble(100),
),
await Expression.throw(
"KRPC",
"InvalidOperationException",
await Expression.constantString("not enough fuel"),
),
);
await conn.run(expr);
Expression.try_catch(), Expression.try_catch_all() and Expression.try_finally()
handle exceptions.
Extensibility#
A server side function can call any remote procedure, including those of services that other
mods add. The one exception is the KRPC service, which builds and runs the functions.
To give functions a new capability, write a service. Its procedures are available to server side functions on every client.