C++#
This guide describes how to install the C++ client, and the features it provides. The Client API Reference describes each function and class.
Installing the Library#
vcpkg#
The C++ client is available from vcpkg, which builds it along with its ASIO and protobuf dependencies. To install it:
vcpkg install krpc
vcpkg install krpc:x64-windows
A project in manifest mode lists the client in its vcpkg.json instead, and vcpkg installs it
when you configure the project:
{
"dependencies": ["krpc"]
}
CMake#
The C++ client requires ASIO and protobuf. By default, CMake looks for these as system-installed packages. On Ubuntu, install them with:
apt-get install libasio-dev libprotobuf-dev protobuf-compiler
CMake 3.15 or later is required. Download the source archive, extract it and run:
cmake -B build
cmake --build build
cmake --install build
Pass -DKRPC_FETCH_DEPS=ON when you configure, to download every dependency with FetchContent
in place of the system packages. The options -DKRPC_FETCH_PROTOBUF=ON,
-DKRPC_FETCH_ASIO=ON and -DKRPC_FETCH_ABSL=ON choose one dependency each. An option that
is OFF, the default, requires the system package.
To install the client in a directory of your choice, pass CMAKE_INSTALL_PREFIX when you
configure it:
cmake -B build -DCMAKE_INSTALL_PREFIX=/path/to/install
cmake --build build
cmake --install build
Compiling a Program#
CMake#
Find the installed library, and link your program against it, in your CMakeLists.txt:
set(CMAKE_CXX_STANDARD 17)
find_package(krpc CONFIG REQUIRED)
target_link_libraries(my_app PRIVATE krpc::krpc)
For a client installed with vcpkg, pass the vcpkg toolchain file when you configure your project:
cmake -B build \
-DCMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake
For a client installed in a directory of your choice, pass that directory as
CMAKE_PREFIX_PATH, so that find_package finds the client there:
cmake -B build -DCMAKE_PREFIX_PATH=/path/to/install
Compiler Command Line#
Link your program against libkrpc, libprotobuf-lite and libz. For a program saved as
main.cpp:
g++ main.cpp -std=c++17 -lkrpc -lprotobuf-lite -lz
clang++ main.cpp -std=c++17 -lkrpc -lprotobuf-lite -lz
Connecting to the Server#
The game must be running with the server started. The Server Plugin in the getting started guide shows how to install and start it.
The client connects over TCP/IP or over a local socket. Each server in the server window uses one protocol, and accepts connections over that protocol only. Pick the protocol when you add the server, and connect with the matching function.
Note
A server with “Auto-accept new clients” turned off answers only once the player approves the
connection in game. The connection fails after 5 seconds by default. Pass a handshake_timeout
of zero to wait indefinitely for the player.
Over TCP/IP#
Select “Protobuf over TCP/IP” as the server’s protocol. connect() connects to it, and
returns a Connection. You make every call through this object. The following
connects to a server with the default settings, address 127.0.0.1 and port 50000, and prints
its version:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/krpc.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::KRPC krpc(conn);
std::cout << krpc.get_status().version << std::endl;
}
connect() also takes a name for the connection, and the address and port of the
server. The address and port match the ones shown in the server window. The name appears in the
server window in the game:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/krpc.hpp>
int main() {
auto conn = krpc::connect("My Example Program", "192.168.1.10", 1000);
krpc::services::KRPC krpc(conn);
std::cout << krpc.get_status().version << std::endl;
}
TCP/IP works over a network, so your program can run on a different machine from the game.
Over a Local Socket#
Select “Protobuf over local socket” as the server’s protocol. connect_local()
connects to it, and returns a Connection as connect() does. The
following connects to a server with the default settings, at the default socket path for your
platform, and prints its version:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/krpc.hpp>
int main() {
auto conn = krpc::connect_local("My Example Program");
krpc::services::KRPC krpc(conn);
std::cout << krpc.get_status().version << std::endl;
}
connect_local() also takes a path, for a server with another socket path. The
path matches the one shown in the server window.
A local socket works only on the machine running the game. It has lower overhead than TCP/IP, so it is faster.
Closing the Connection#
A Connection can be copied, and every copy shares the connection. So does each
service, object, stream and event you make from it. Call close() to close
the connection:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/krpc.hpp>
int main() {
auto conn = krpc::connect("My Example Program");
krpc::services::KRPC krpc(conn);
std::cout << krpc.get_status().version << std::endl;
conn.close();
}
Calls through any of them then throw ConnectionError, and streams and events end.
Without the call, the connection closes when the last of them is destroyed. An object you return
from a function keeps the connection open.
Note
A callback that holds its own stream or event keeps the connection open until the stream ends. An
update callback that holds an object keeps it open until you call
close().
Note
Destroying the last copy of a stream or event stops new runs of its callbacks, but a run in
progress carries on. Call close() to wait for it.
Calling Remote Procedures#
The server provides procedures for your program to call, grouped into services.
The following gets the active vessel from active_vessel(), an
object of type Vessel. It sets the vessel’s name, then prints
its altitude:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
vessel.set_name("My Vessel");
auto flight_info = vessel.flight();
std::cout << flight_info.mean_altitude() << std::endl;
}
Each service is a class in the krpc::services namespace, declared in a header of its own, such
as krpc/services/space_center.hpp for the SpaceCenter service. Include
the header, and construct the service with a reference to the connection.
Handling Errors#
A procedure that fails on the server throws an exception in your program. The following catches the error from loading a save that does not exist:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <stdexcept>
int main() {
auto conn = krpc::connect();
krpc::services::KRPC krpc(conn);
krpc::services::SpaceCenter sc(conn);
try {
sc.load("missing");
} catch (const std::invalid_argument& error) {
std::cout << "Failed to load the save: " << error.what() << std::endl;
}
}
The exception you catch depends on the error:
A standard error, such as an invalid argument, throws the matching standard exception. The example catches
std::invalid_argument, as a missing save throwsArgumentException, an alias of it. The standard exceptions share bases, so acatchofInvalidOperationException, an alias ofstd::logic_error, also catches the argument and index exceptions.An error particular to a service throws a class of that service, such as
ObjectDestroyedException, derived fromServerError.An error the client has no class for throws
ServerError.A call made once the connection has failed throws
ConnectionError.
Every error of the client’s own derives RemoteError. A standard exception does
not.
Values#
Procedures take and return C++ values, such as int32_t, std::string, std::vector and
std::map, and an empty std::optional for a null. The services also define their own types:
A class is a remote object, described below.
A structure is a
struct.An enumeration is an
enum struct, with operators for a flags enumeration.
Flags Enumerations#
A flags enumeration, such as MapFilterType, holds any
combination of its values. Its enum struct has the operators |, &, ^ and ~, and
their assignment forms. You combine values with |, and test for one with &:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
using MapFilterType = krpc::services::SpaceCenter::MapFilterType;
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
// Show only probes and ships in map mode
sc.set_map_filter(MapFilterType::probes | MapFilterType::ships);
// Check whether map mode shows debris
auto filter = sc.map_filter();
std::cout << ((filter & MapFilterType::debris) == MapFilterType::debris)
<< std::endl;
// Show debris as well
sc.set_map_filter(filter | MapFilterType::debris);
}
~ gives the values the enumeration declares that its operand does not hold.
Remote Objects#
Many procedures return an object identifying something in the game, such as a vessel or a part. The object holds no copy of the game’s state. It is just a reference to it. Each call through it reads the game as it is now:
#include <chrono>
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <thread>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto flight_info = vessel.flight();
// Each read gets the current altitude from the game
std::cout << flight_info.mean_altitude() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << flight_info.mean_altitude() << std::endl;
// Two objects for the same vessel are equal
std::cout << (vessel == sc.active_vessel().value()) << std::endl;
}
Two objects for the same thing in the game compare equal. Objects are also ordered, so they can be
used as std::map keys, and hash hashes them for an unordered container.
Once the thing an object identifies is destroyed, such as a part that explodes, each call through
it throws ObjectDestroyedException.
An object for a vessel or a part keeps working when you load a save, quickload or revert, and then reads the loaded game. Other objects depend on what they identify. A maneuver node, for example, is destroyed by a load.
A vessel far from the active vessel is unloaded, and the game keeps no parts for it. The vessel
itself reads normally, but a call on one of its parts throws
ObjectNotLoadedException. The part works again once the vessel comes
back into range.
See also
Object Lifetime describes how each kind of object behaves in more detail.
Calling Methods#
You call a method on an object of its class. A static method needs no object, and you call it on
the class itself, passing the client as its first argument. Its _stream and _call forms
take the client first too:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <tuple>
using krpc::services::SpaceCenter;
int main() {
auto conn = krpc::connect();
SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto frame = vessel.orbit().body().reference_frame();
// Call a method on an object
auto position = vessel.position(frame);
std::cout << std::get<0>(position) << ", " << std::get<1>(position)
<< ", " << std::get<2>(position) << std::endl;
// Call a static method, passing the client first
auto direction =
SpaceCenter::Orbit::reference_plane_direction(conn, frame);
std::cout << std::get<0>(direction) << ", " << std::get<1>(direction)
<< ", " << std::get<2>(direction) << std::endl;
// Stream it
auto stream =
SpaceCenter::Orbit::reference_plane_direction_stream(conn, frame);
direction = stream();
std::cout << std::get<0>(direction) << ", " << std::get<1>(direction)
<< ", " << std::get<2>(direction) << std::endl;
}
bind binds a class’s static methods to a client, so each call leaves it out:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <tuple>
using krpc::services::SpaceCenter;
int main() {
auto conn = krpc::connect();
SpaceCenter sc(conn);
auto frame = sc.active_vessel().value().reference_frame();
// Bind the static methods to the client once
auto orbit = SpaceCenter::Orbit::bind(conn);
for (auto v : {orbit.reference_plane_normal(frame),
orbit.reference_plane_direction(frame)}) {
std::cout << std::get<0>(v) << ", " << std::get<1>(v) << ", "
<< std::get<2>(v) << std::endl;
}
}
Streaming Data#
A common use of kRPC is to read data from the game continuously. The following does so by calling a remote procedure in a loop, printing the position of the active vessel:
#include <iomanip>
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <tuple>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto ref_frame = vessel.orbit().body().reference_frame();
while (true) {
auto pos = vessel.position(ref_frame);
std::cout << std::fixed << std::setprecision(1);
std::cout << std::get<0>(pos) << ", " << std::get<1>(pos) << ", "
<< std::get<2>(pos) << std::endl;
}
}
Each call sends a request to the server and waits for its response. A stream is more efficient. The server runs the call repeatedly, and sends your program the result each time it changes.
The following does the same as above using a stream:
#include <iomanip>
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <tuple>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto ref_frame = vessel.orbit().body().reference_frame();
auto pos_stream = vessel.position_stream(ref_frame);
while (true) {
auto pos = pos_stream();
std::cout << std::fixed << std::setprecision(1);
std::cout << std::get<0>(pos) << ", " << std::get<1>(pos) << ", "
<< std::get<2>(pos) << std::endl;
}
}
Each procedure has a function with _stream added to its name, such as position_stream. It
creates the stream from the procedure’s arguments, and returns a Stream, whose
template argument is the procedure’s return type. Calling the stream returns its latest value.
A property is streamed the same way, with _stream added to the name of its getter:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto flight_info = sc.active_vessel().value().flight();
auto altitude = flight_info.mean_altitude_stream();
while (true) std::cout << altitude() << std::endl;
}
Each call to a _stream function creates another stream. A procedure with no return value
streams as a Stream<void>, which runs the call on each update for its effects. Calling it
returns nothing, and its callbacks take no arguments.
A stream runs until you remove it with remove(), or the connection closes.
A stream object can be copied, and every copy refers to the same stream. Destroying the last copy
also removes the stream, so a stream declared in a block is removed at the end of the block:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto flight_info = vessel.flight();
{
auto altitude = flight_info.mean_altitude_stream();
for (int i = 0; i < 10; i++) std::cout << altitude() << std::endl;
}
// The stream was removed at the end of the block
}
By default, the server sends a stream’s value each time it changes. Call
set_rate() to limit how many times a second the stream updates:
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto flight_info = sc.active_vessel().value().flight();
auto altitude = flight_info.mean_altitude_stream();
// Update the stream at most 10 times a second
altitude.set_rate(10);
}
Waiting for Changes#
Each stream has a condition variable, a Condition, which is used like a
std::condition_variable. wait() blocks until the stream’s value changes.
The following waits for the abort button to be pressed:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto control = sc.active_vessel().value().control();
auto abort = control.abort_stream();
abort.acquire();
while (!abort()) abort.wait();
abort.release();
}
Hold the condition when you call wait(), as acquire()
does here, and release() lets go of it. While you hold it, the value changes
only when you wait, so the loop misses no updates. An ending reaches you the same way: the wait
returns, and your next read or wait throws the exception that ended the stream.
wait() takes a timeout in seconds, and returns false when it elapses
before an update.
Callbacks#
A callback is a function the client calls with each new value of a stream. The following adds two callbacks to a stream of the abort button:
#include <chrono>
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <thread>
void check_abort1(bool x) {
std::cout << "Abort 1 called with a value of " << x << std::endl;
}
void check_abort2(bool x) {
std::cout << "Abort 2 called with a value of " << x << std::endl;
}
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto control = sc.active_vessel().value().control();
auto abort = control.abort_stream();
abort.add_callback(check_abort1);
abort.add_callback(check_abort2);
// Keep the program running, while the callbacks are called
while (true) std::this_thread::sleep_for(std::chrono::seconds(1));
}
A callback added to a stream that already has a value is called with that value straight away. It is then called with each new value, in order.
Note
Each connection has a callback thread, which runs the callbacks of its streams one at a time. A callback can make remote procedure calls. Other callbacks and waits are held up while it runs, so return promptly, and do not wait on a stream in a callback. For a long running task, start a worker thread from the callback.
Stream Endings#
A stream ends when its procedure throws an exception, when the server removes it, when you remove it, or when the connection closes. Calling the stream or waiting on it then throws the exception that ended it. The following streams the temperature of a part until the part is destroyed:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
int main() {
auto conn = krpc::connect();
krpc::services::KRPC krpc(conn);
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto temperature = vessel.parts().root().temperature_stream();
try {
temperature.acquire();
while (true) {
temperature.wait();
std::cout << "Temperature " << temperature() << std::endl;
}
} catch (const krpc::services::KRPC::ObjectDestroyedException&) {
std::cout << "The part was destroyed" << std::endl;
}
temperature.release();
}
The exception is the one the procedure threw, or one of the following:
StreamErrorwhen you or the server remove the stream, such as for an event that has finished.ConnectionErrorwhen the connection closes or fails.
An exception for an object that is not loaded, or for a procedure not available in the current game scene, does not end the stream. It pauses the stream’s updates, and the stream keeps its last value. The updates resume once the object or the scene is available.
See also
Object Lifetime describes when each kind of object is not loaded, and how streams behave around a load.
add_end_callback() adds a callback that is called once when the stream
ends, with the exception as a std::exception_ptr. The following prints the temperature of a
part with a callback, and prints the exception when the stream ends:
#include <chrono>
#include <exception>
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <thread>
void print_temperature(double value) {
std::cout << "Temperature " << value << std::endl;
}
void print_ending(const std::exception_ptr& error) {
try {
std::rethrow_exception(error);
} catch (const std::exception& exn) {
std::cout << "The stream ended: " << exn.what() << std::endl;
}
}
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto temperature = vessel.parts().root().temperature_stream();
temperature.add_callback(print_temperature);
temperature.add_end_callback(print_ending);
// Keep the program running, while the callbacks are called
while (true) std::this_thread::sleep_for(std::chrono::seconds(1));
}
Server Side Functions#
A server side function runs inside the game. You build it in your program with the expression API, and the client sends it to the server, which runs it there. The following reads the vessel’s altitude and speed together:
#include <iostream>
#include <krpc.hpp>
#include <krpc/function_stream.hpp>
#include <krpc/services/krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <tuple>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto flight = vessel.flight(vessel.orbit().body().reference_frame());
// Get the remote procedure calls as message objects,
// so they can be passed to the server
auto mean_altitude_call = flight.mean_altitude_call();
auto speed_call = flight.speed_call();
// Build a function that reads the altitude and the speed
auto e = krpc::services::KRPC::Expression::bind(conn);
auto expr =
e.create_tuple({e.call(mean_altitude_call), e.call(speed_call)});
// Run the function once, so both values come from the same physics tick
auto [altitude, speed] = krpc::run<std::tuple<double, double>>(expr);
std::cout << "Altitude: " << altitude << " m, speed: " << speed << " m/s"
<< std::endl;
}
Each procedure has a function with _call added to its name, such as mean_altitude_call. It
returns the call as a message, for call() to embed in the
function. A static function with _call_template added to the name, such as
Engine::has_fuel_call_template(), returns the call template. It names the procedure and
carries no arguments, for call_with_arguments() to
supply each one, as in Functions and Collections.
The Expression API in the server side functions guide describes how to build functions.
run(), compile(), add_stream() and add_event()
are declared in
krpc/function_stream.hpp.
Running a Function#
run() runs a function once, and returns its value. The template argument gives the
type of the value. The server runs the whole function within one physics tick, so every value it
reads comes from the same moment in the game. In the example, the altitude and the speed are
consistent with each other, which two separate calls cannot guarantee.
Streaming a Function#
Pass a function to add_stream() to stream its value. The template argument gives the
type of the value. The server evaluates the function on each update, within one physics tick. The
following streams the vessel’s altitude in kilometers:
#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));
}
}
A function stream ends on an exception its function throws, just like an
ordinary stream. Unlike an ordinary stream, it also ends on
ObjectNotLoadedException, thrown while the game loads or when a
vessel unloads. The server cannot pause a function partway through, and running it again would
repeat its effects. To keep a function running through a load, catch the exception in the
function:
auto e = Expr::bind(conn);
auto t = KType::bind(conn);
// altitude = mean_altitude / 1000, or 0 if the vessel is not loaded
auto altitude = e.variable("altitude", t.double_());
auto km = e.divide(e.call(flight.mean_altitude_call()),
e.constant_double(1000));
auto altitude_km = e.block_with_variables(
std::vector<Expr>({altitude}),
std::vector<Expr>(
{e.try_catch(e.assign(altitude, km), "KRPC",
"ObjectNotLoadedException", std::nullopt,
e.assign(altitude, e.constant_double(0))),
altitude}));
auto stream = krpc::add_stream<double>(altitude_km);
Events#
A common use of kRPC is to wait for something to happen in the game, such as the vessel reaching an altitude. An event does this efficiently. The server checks a condition, written as a server side function, and tells your program when it becomes true. The following waits until the vessel’s altitude exceeds 1000 meters:
#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();
}
add_event() creates the event, and wait() waits for it to fire.
The server checks the condition every physics tick, so the event catches a condition that holds
for only a moment, which a loop of calls can miss.
The event fires again each time the condition becomes true after being false. Call
remove() to stop it. Destroying the last copy of an event also removes it, so an
event declared in a block is removed at the end of the block:
#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();
auto mean_altitude = flight.mean_altitude_call();
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.get_condition_lock().lock();
event.wait();
std::cout << "Altitude reached 1000m" << std::endl;
}
// The end of the block released the lock and removed the event
}
As with a stream, hold the event’s condition when you call wait(). A wait
returns straight away if the event has fired since the last wait on the same event object, so a
firing between two waits is not missed.
Event Callbacks#
An event can also call a callback each time it fires. The callback takes no arguments:
#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();
auto e = krpc::services::KRPC::Expression::bind(conn);
auto expr = e.greater_than(e.call(flight.mean_altitude_call()),
e.constant_double(1000));
auto event = krpc::add_event(expr);
event.add_callback(
[] { std::cout << "Altitude reached 1000m" << std::endl; });
// Keep the program running, while the callback is called
while (true) std::this_thread::sleep_for(std::chrono::seconds(1));
}
Callbacks for events run on the connection’s callback thread, as the callbacks of a stream do.
Event Endings#
An event ends in the same ways as a stream. Waiting on an event that has ended throws the exception that ended it.
When the event fires just before the server ends it, your next wait returns for that firing first. Removing the event, or destroying its last copy, ends it at once.
add_end_callback() adds a callback that is called once when the event ends,
with the exception, just like an ordinary stream.
Threading#
A connection can be shared between threads. Each thread makes calls over it as it would alone, and each call returns its own result. The following prints the altitude and speed of the vessel from two threads:
#include <iostream>
#include <krpc.hpp>
#include <krpc/services/space_center.hpp>
#include <thread>
int main() {
auto conn = krpc::connect();
krpc::services::SpaceCenter sc(conn);
auto vessel = sc.active_vessel().value();
auto flight_info = vessel.flight(vessel.orbit().body().reference_frame());
// Both threads make calls over the same connection
std::thread altitude([&flight_info] {
for (int i = 0; i < 10; i++)
std::cout << "Altitude: " << flight_info.mean_altitude() << std::endl;
});
std::thread speed([&flight_info] {
for (int i = 0; i < 10; i++)
std::cout << "Speed: " << flight_info.speed() << std::endl;
});
altitude.join();
speed.join();
}
Streams and events can also be used from any thread:
Several threads can read a stream, or wait on a stream or an event. A change wakes every thread waiting for it. Each thread waits through its own copy of the stream or event object.
A thread holding a stream’s condition does not stop other threads from making calls.
Callbacks run on the connection’s callback thread, one at a time, and never on your program’s threads. A callback added to a stream that already has a value is different. Its first call, with that value, might run on your thread, before
add_callback()returns. Protect state that a callback shares with your program’s threads, such as with astd::mutex.
When the connection fails, the calls and waits of every thread end with
ConnectionError. A wait on a stream or an event that another thread removes ends
with the exception for a removed stream.
Deprecated Members#
A member of a service can be deprecated, when a newer member replaces it. A deprecated member still works, but may be removed in a future release, so move to its replacement.
The API reference and the member’s documentation comment mark it as deprecated, and name the
replacement. The member is also declared [[deprecated]] with that message, so the compiler
warns where your program uses it.
Service Stubs#
The client includes code for each service that ships with kRPC, generated from the services of
one kRPC release. These stubs are the headers in krpc/services, such as
krpc/services/space_center.hpp.
The stubs match the server from the same release, so install the client version that matches your server. With another version, a procedure that was removed or renamed throws an exception when you call it. A parameter or return type that changed is not checked, so a call can send or return a wrong value with no error.
A service with no stub, such as one added by another mod, needs stubs of its own. Generating Service Code for Static Clients shows how to generate them.
Client API Reference#
-
Connection connect(const std::string &name = "", const std::string &address = "127.0.0.1", unsigned int port = 50000, std::chrono::milliseconds timeout = std::chrono::milliseconds::zero(), std::chrono::milliseconds handshake_timeout = std::chrono::seconds(5), std::chrono::milliseconds stall_timeout = std::chrono::seconds(30))#
Connects to a kRPC server, and returns a
Connection.- Parameters:
name (std::string) – A name for the connection, shown in the server window in the game.
address (std::string) – The address of the server, as a host name or an IP address. Defaults to
"127.0.0.1".port (unsigned int) – The port of the server. Defaults to 50000.
timeout (std::chrono::milliseconds) – How long to wait for the connection to open. Defaults to zero, which waits indefinitely. Without a timeout, a network that drops the connection attempt leaves the client waiting.
handshake_timeout (std::chrono::milliseconds) – How long to wait for the server to accept the connection. Defaults to 5 seconds. Zero waits indefinitely, such as for a server that asks the player to approve each connection.
stall_timeout (std::chrono::milliseconds) – How long a message from the server can go without a new byte, once it has started to arrive, before the connection fails. Defaults to 30 seconds. Zero waits indefinitely.
Throws
ConnectionErrorif the connection fails or the server refuses it, andstd::invalid_argumentfor a negative handshake or stall timeout.
-
Connection connect_local(const std::string &name = "", const std::string &path = "", std::chrono::milliseconds handshake_timeout = std::chrono::seconds(5), std::chrono::milliseconds stall_timeout = std::chrono::seconds(30))#
Connects to a kRPC server on the same machine over a local socket, and returns a
Connection. The server must use the local socket protocol.Local sockets are available on Linux, macOS, and Windows 10 1803 and Windows Server 2019 or later.
- Parameters:
name (std::string) – A name for the connection, shown in the server window in the game.
path (std::string) – The path of the server’s socket, shown in the server window in the game. An empty path, the default, is the path the server uses unless it was configured with another.
handshake_timeout (std::chrono::milliseconds) – As for
connect().stall_timeout (std::chrono::milliseconds) – As for
connect().
Throws
ConnectionErrorandstd::invalid_argumentasconnect()does.
-
class Connection#
A connection to the server. Obtain one by calling
connect(). A service is constructed with a reference to it, such askrpc::services::SpaceCenter sc(conn).Connection objects are copy constructible and assignable, and every copy shares the connection. The connection closes on
close(), or when the last copy, and every service, object, stream and event made from one, is destroyed. A default-constructed connection is not connected. Its calls and its stream update members throwConnectionError.-
void close()#
Closes the connection. Calls in progress and later calls through any copy, service or object throw
ConnectionError, and streams and events end. Destroys the stream and update callbacks, and waits for a callback in progress unless called from a callback. Does nothing if the connection is already closed, or the client is not connected.
-
void wait_for_stream_update(double timeout = -1)#
Blocks until the next stream update message is processed, or the timeout elapses. A timeout of zero or more is in seconds, and a negative one waits indefinitely. Hold the stream update condition, with
acquire_stream_update(), when calling this method.Returns straight away once the connection has failed. It can also return before an update, so check for the change you are waiting for.
-
void acquire_stream_update()#
Locks the mutex of the stream update condition variable.
-
void release_stream_update()#
Unlocks the mutex of the stream update condition variable.
-
Condition &get_stream_update_condition() const#
A condition variable notified after each stream update message is processed.
-
std::unique_lock<RecursiveMutex> &get_stream_update_condition_lock() const#
A lock on the re-entrant mutex of the stream update condition variable. Every copy of the client shares the lock, so one thread at a time uses it.
-
int add_stream_update_callback(const std::function<void()> &callback)#
Adds a callback, with no arguments, called after each stream update message is processed. It runs on the connection’s callback thread, as the callbacks of a stream do. Returns a tag that identifies the callback.
-
void remove_stream_update_callback(int tag)#
Removes a stream update callback, given the tag
add_stream_update_callback()returned.
-
void close()#
-
template<typename T>
class RemoteObject# The base class of remote objects. Two objects compare equal with
==when they identify the same thing in the game.<and the other comparisons order objects by their identifiers, and<<writes an object’s class name and identifier to a stream. A default-constructed object identifies nothing. A call through it, or with it as an argument, throwsstd::invalid_argument.
-
template<typename T>
uint64_t get_object_id(const RemoteObject<T> &object)# The identifier of a remote object on the server, e.g. to pass to
constant_object(). Throwsstd::invalid_argumentfor a default-constructed object.
-
template<typename T>
class Stream# A stream, created by a procedure’s
_streamfunction. See Streaming Data. AStream<void>is a stream of a call or function with no value. It runs on each update for its effects, and the server sends one update, after the first run.Stream objects are copy constructible and assignable, and every copy refers to the same stream. Call
remove(), or destroy every copy, to remove the stream from the server. A default-constructed stream object refers to no stream. Its members throwStreamError, exceptremove(), which does nothing, and the comparisons.-
T operator()()#
Returns the most recent value of the stream, waiting for the first value if none has arrived yet. Throws the exception that ended the stream, if it has ended.
-
bool wait(double timeout = std::numeric_limits<double>::infinity())#
Blocks until the value of the stream changes, or the timeout elapses. Returns
trueif the value changed, andfalseon a timeout. Hold the condition, withacquire(), when calling this method.The timeout is in seconds, and the default waits indefinitely. Throws
std::invalid_argumentfor a negative or NaN timeout. Throws the exception that ended the stream, if it ends before or during the wait. A thread holding the condition sees an ending as an update: the wait returnstrue, and later reads and waits throw the exception.
-
void acquire()#
Locks the mutex of the stream’s condition variable. Every copy of the stream object shares the mutex, so a lock taken through one copy can be released through another.
-
void release()#
Unlocks the mutex of the stream’s condition variable.
-
Condition &get_condition() const#
A condition variable notified when the value of the stream changes. Every copy of the stream object shares it.
-
std::unique_lock<RecursiveMutex> &get_condition_lock() const#
A lock on the re-entrant mutex of the condition variable. Each stream object has its own lock, used by one thread, so a thread waiting on a stream uses its own copy of the stream object.
-
float rate()#
-
void set_rate(float rate)#
The update rate of the stream, in Hertz. Zero, the default, means no limit.
-
int add_callback(const std::function<void(T)> &callback)#
Adds a callback, called with each new value of the stream. If the stream already has a value, the callback is called with it straight away. The exception that ends a stream goes to its end callbacks. Returns a tag that identifies the callback.
-
void remove_callback(int tag)#
Removes a callback, given the tag
add_callback()returned.
-
int add_end_callback(const std::function<void(std::exception_ptr)> &callback)#
Adds a callback, called once when the stream ends, with the exception that ended it. It is called straight away if the stream has already ended. Returns a tag that identifies the callback.
-
void remove_end_callback(int tag)#
Removes an end callback, given the tag
add_end_callback()returned.
-
void remove()#
Removes the stream from the server, for every copy of the stream object. Other streams of the same call are not affected.
-
bool operator==(const Stream<T> &rhs) const#
-
bool operator!=(const Stream<T> &rhs) const#
Whether the two stream objects refer to the same stream. Two streams created for the same call are not equal.
-
explicit operator bool() const#
Whether the stream object refers to a stream.
-
T operator()()#
-
template<typename T = void, typename ...Args>
T run(const services::KRPC::Expression &function, const Args&... args)# Runs a server side function within a single physics tick, and returns its value. With the
voidtemplate type, the function is run for its effects. The arguments are passed to the function’s parameters, withstd::nulloptornullptrfor a null.A number converts to a
doubleparameter, and an integer or afloatto afloatparameter, as C++ converts it implicitly, which can round. An integer converts to a signed parameter that holds every value of its type, and an integer that is not negative to an unsigned parameter at least as wide. A number a collection or a tuple holds converts the same way.Throws
std::invalid_argumentif the template type does not describe the function’s value, the number of arguments differs from the number of parameters, or an argument does not match its parameter. ThrowsEncodingErrorfor a null value unless the template type is astd::optional.A class, enumeration or structure argument is checked by kind only. The server checks its class, and a null for a parameter that is not nullable, and throws
ArgumentExceptionfor a mismatch.
-
services::KRPC::Expression compile(const services::KRPC::Expression &function)#
Compiles a server side function on the server, so that its first run is as fast as later ones, and returns the function.
-
template<typename T>
Stream<T> add_stream(const services::KRPC::Expression &function)# Creates a stream from a server side function, evaluated on each update. Each call creates a new stream. A function that can produce a null needs a
std::optionaltemplate type, and reading a null without one throwsEncodingError. A callback is not called for a null value. A function with no value takesvoidas the template type, and runs on each update for its effects.Throws
std::invalid_argumentif the template type does not describe the function’s value,ConnectionErrorif the client is not connected to a server, andArgumentExceptionif the function has parameters.
-
Event add_event(const services::KRPC::Expression &function)#
Creates an event from a server side function that evaluates to a boolean value. Each call creates a new event. Throws
ConnectionErrorif the client is not connected to a server, andArgumentExceptionif the function does not evaluate to a boolean value or has parameters.
-
class Event#
An event, made from a
Stream<bool>that is true when the event fires. See Events.Event objects are copy constructible and assignable, and every copy refers to the same event. Destroying the last copy removes the event from the server. A default-constructed event object refers to no event. Its members throw
StreamError, exceptremove(),stream(), the comparisons andoperator bool.-
bool wait(double timeout = std::numeric_limits<double>::infinity())#
Blocks until the event fires, or the timeout elapses. Returns straight away if the event has fired since the previous wait on this event object, or for a first wait, since the event was created. Returns
trueif the event fired, andfalseon a timeout. Hold the condition, withacquire(), when calling this method.The timeout is in seconds, and the default waits indefinitely. Throws
std::invalid_argumentfor a negative or NaN timeout. Throws the exception that ended the event, if it ends before or during the wait.
-
void acquire()#
Locks the mutex of the event’s condition variable. Every copy of the event object, and its stream, shares the mutex.
-
void release()#
Unlocks the mutex of the event’s condition variable.
-
Condition &get_condition() const#
A condition variable notified when the event fires. Every copy of the event object shares it.
-
std::unique_lock<RecursiveMutex> &get_condition_lock() const#
A lock on the re-entrant mutex of the condition variable. Each event object has its own lock, used by one thread, so a thread waiting on an event uses its own copy of the event object.
-
int add_callback(const std::function<void()> &callback)#
Adds a callback, with no arguments, called each time the event fires. It is called straight away for a firing that no wait on this event object has returned for and no callback has been called for. Returns a tag that identifies the callback.
-
void remove_callback(int tag)#
Removes a callback, given the tag
add_callback()returned.
-
int add_end_callback(const std::function<void(std::exception_ptr)> &callback)#
Adds a callback, called once when the event ends, with the exception that ended it. It is called straight away if the event has already ended. Returns a tag that identifies the callback.
-
void remove_end_callback(int tag)#
Removes an end callback, given the tag
add_end_callback()returned.
-
void remove()#
Removes the event from the server.
-
bool operator==(const Event &rhs) const#
-
bool operator!=(const Event &rhs) const#
Whether the two event objects refer to the same event.
-
explicit operator bool() const#
Whether the event object refers to an event.
-
bool wait(double timeout = std::numeric_limits<double>::infinity())#
-
class RemoteError#
The base of every error the client throws of its own. A subclass of
std::runtime_error.
-
class ConnectionError#
Thrown when connecting fails, by each call once the connection has failed, and by each call on a client that is not connected. A subclass of
RemoteError.-
const std::string &status() const#
The status the server refused the connection with, such as
"DENIED", or empty.
-
const std::string &reason() const#
The reason the server gave for ending the connection, such as
"SERVER_STOPPED", or empty.
-
const std::string &status() const#
-
class ServerError#
Thrown for an error from the server with no standard exception, and the base class of each service exception with no standard equivalent. A subclass of
RemoteError.
-
class StreamError#
Thrown by a stream or event that you or the server removed, and when a stream cannot be created. A subclass of
RemoteError.
-
class EncodingError#
Thrown when a value cannot be encoded or decoded. A subclass of
RemoteError.
-
class RecursiveMutex#
The mutex of a stream’s, an event’s or the stream update’s condition variable. The thread holding it can lock it again, and each lock is matched by an unlock. It provides
lock,try_lock,try_lock_for,try_lock_untilandunlock, so it can be held withstd::unique_lockandstd::lock_guard.unlockthrowsstd::system_erroron a thread that does not hold it.-
bool held_by_this_thread() const#
Whether the calling thread holds the mutex.
-
bool held_by_this_thread() const#
-
class Condition#
The condition variable of a stream, an event or the stream update. Its
wait,wait_forandwait_untiltake astd::unique_lock<RecursiveMutex>, with or without a predicate, asstd::condition_variabledoes. A wait releases every lock the calling thread holds on the mutex, and takes them again before it returns. Throwsstd::system_errorif the calling thread does not hold the mutex. A wait can return without a notification, so call it in a loop that checks for the change.-
void wait()#
-
template<typename Rep, typename Period>
std::cv_status wait_for(const std::chrono::duration<Rep, Period> &duration)# -
template<typename Clock, typename Duration>
std::cv_status wait_until(const std::chrono::time_point<Clock, Duration> &deadline)# Waits as the overloads taking a lock do, for a thread that holds the mutex through
acquireor a lock of its own.
-
void wait()#
-
template<typename T>
std::size_t hash_value(const T &value)# Returns a hash of a value of any type the client carries: the arithmetic types, strings, enumerations, class objects,
std::optional, tuples, and the list, set and dictionary collection types, nested however deeply. A structure is also hashed by this function, and is given astd::hashof its own, so an unordered container can be keyed by one directly.
-
class hash#
A function object that calls
hash_value(), for a standard container that takes its hash as a template argument. The standard library hashes neitherstd::tuplenor the collection types, so a container keyed by one needs this:std::unordered_set<std::tuple<double, double, double>, krpc::hash> points;
Service API Reference#
Server