Rust client
microrti-client is the Rust library for writing HLA 4 federates, the federate side of MicroRTI. Its
RtiAmbassador has every federate-initiated service of IEEE 1516.1-2025 (clauses 4 to 10) as a
blocking method, and its FederateAmbassador trait receives the callbacks. It speaks the standard HLA
Federate Protocol (12.13), so it is not tied to the MicroRTI server. This page is a reference; for a
first program, follow
Your first federate in Rust.
Add the crate
[dependencies]
microrti-client = "0.5"The crate needs Rust 1.88 or later. Its build compiles the protobuf files of the Federate Protocol with a
Rust build script, so no protoc has to be installed. The API documentation is on
docs.rs/microrti-client.
Cargo features
| Feature | Default | What it adds |
|---|---|---|
fedpro | yes | The Federate Protocol client (module fedpro) and the connectors for the address schemes tcp, tls, ws, wss and for bare host[:port] addresses. Pulls in Tokio and rustls. |
embedded | no | An RTI inside the federate’s process (module embedded); adds a dependency on microrti-engine, and on an HTTP client (ureq, rustls) that reads FOM modules named by http: and https: URLs. |
test-util | no | Module testing: the scripted in-memory link that the crate’s own tests use. |
A program that only ever uses the RTI in its own process can drop the network part:
[dependencies]
microrti-client = { version = "0.5", default-features = false, features = ["embedded"] }Connect to an RTI
RTI addresses
The RTI address of the RtiConfiguration given to Connect selects the transport:
| Address | Transport | Default port |
|---|---|---|
tcp://host[:port], or host[:port] without a scheme | TCP | 15164 |
tls://host[:port] | TLS 1.3 | 15165 |
ws://host[:port][/path] | WebSocket | 80 |
wss://host[:port][/path] | secure WebSocket | 443 |
An empty address means tcp://localhost:15164 (the constant microrti_client::fedpro::DEFAULT_RTI_ADDRESS).
An IPv6 address goes in brackets when a port follows. The WebSocket path is sent in the handshake; the
MicroRTI server accepts any path. An address with a scheme nobody registered fails with
ConnectionFailed (“no connector registered for RTI address”).
Connect methods
| Method | Use it for |
|---|---|
connect(federate_ambassador, model) | the default address, tcp://localhost:15164 |
connect_with_configuration(federate_ambassador, model, &configuration) | an RTI address and connection settings |
connect_with_credentials(federate_ambassador, model, &credentials) | the default address, with credentials |
connect_with_configuration_and_credentials(federate_ambassador, model, &configuration, &credentials) | both |
Each returns a ConfigurationResult saying what was done with the configuration (4.2). The client
completes the answer of the RTI with what its own link did: address_used is true when it reached the
RTI at the address you gave, and the FED_ and TLS_ settings it applied make the result code
SettingsApplied and are named in the message. The MicroRTI server uses no configuration name and no
setting of its own, and names the other keys it ignored. Printed with {:?}, against a local server:
# no additional settings
ConfigurationResult { configuration_used: false, address_used: true, additional_settings_result_code: SettingsIgnored, message: "" }
# "FED_TIMEOUT_CONNECT=5"
ConfigurationResult { configuration_used: false, address_used: true, additional_settings_result_code: SettingsApplied, message: "applied on the federate side: FED_TIMEOUT_CONNECT" }
# "MY_SETTING=1"
ConfigurationResult { configuration_used: false, address_used: true, additional_settings_result_code: SettingsIgnored, message: "additional settings ignored by the RTI: MY_SETTING" }RtiConfiguration is built with with_configuration_name, with_rti_address and
with_additional_settings. An RtiAmbassador holds at most one connection; a second Connect fails with
AlreadyConnected. The ambassador is Send + Sync and cheap to clone: all clones are the same
ambassador, services can be called from several threads at once, and dropping the last clone releases the
connection.
Connection settings
The additional settings of the RtiConfiguration carry the settings of the federate side, one
KEY=VALUE per line. Blank lines and lines starting with # are skipped, keys are not case sensitive,
and times are in seconds and may have a fraction. The first three keys are the federate settings of
Table 32 in IEEE 1516.1-2025.
| Key | Meaning | Default |
|---|---|---|
FED_INT_HEART | idle time after which the federate sends a heartbeat | 60 |
FED_TIMEOUT_HEART | RTI silence after which the connection is given up and the session resumed on a new one | 180 |
FED_TIMEOUT_RECONNECT | time after which resuming is given up and the connection is lost | 600 |
FED_INT_RECONNECT | pause between two reconnection attempts (MicroRTI setting, not in the standard) | 1 |
FED_TIMEOUT_CONNECT | bound on one connection attempt and on the start of the session (MicroRTI setting) | 10 |
TLS_TRUST_ANCHORS | PEM file with the certificates the RTI certificate must chain to; without it, TLS encrypts but does not check who the RTI is | none |
TLS_SERVER_NAME | name the RTI certificate must match, when it is not the host of the address | the host |
For example, to reach an RTI by IP address whose certificate is issued to rti.example.org and signed by
your own certificate authority:
let configuration = RtiConfiguration::new()
.with_rti_address("tls://127.0.0.1")
.with_additional_settings(
"TLS_TRUST_ANCHORS=certs/rti-ca.pem\n\
TLS_SERVER_NAME=rti.example.org\n\
FED_TIMEOUT_CONNECT=5",
);
rti.connect_with_configuration(NullFederateAmbassador, CallbackModel::Evoked, &configuration)?;Without TLS_SERVER_NAME, the certificate does not match the address. Tried against a local server on
port 55853, Connect failed with:
RtiError { kind: ConnectionFailed, message: "cannot reach the RTI: tls://127.0.0.1:55853: transport error: TLS handshake with tls://127.0.0.1:55853 failed: invalid peer certificate: certificate not valid for name \"127.0.0.1\"; certificate is only valid for DnsName(\"rti.example.org\")" }With TLS_SERVER_NAME added, it connected:
ConfigurationResult { configuration_used: false, address_used: true, additional_settings_result_code: SettingsApplied, message: "applied on the federate side: TLS_TRUST_ANCHORS, TLS_SERVER_NAME, FED_TIMEOUT_CONNECT" }An unknown FED_ or TLS_ key, or a value that cannot be used, does not stop Connect (4.2). The client
skips that line, applies the others, connects, and returns SettingsFailedToParse with the line and the
reason:
# "FED_TIMEOUT_CONNECT=0"
ConfigurationResult { configuration_used: false, address_used: true, additional_settings_result_code: SettingsFailedToParse, message: "not usable on the federate side: line 1: FED_TIMEOUT_CONNECT: `0`: the time must be greater than zero" }
# "FED_TIMOUT_CONNECT=5" (misspelt)
ConfigurationResult { configuration_used: false, address_used: true, additional_settings_result_code: SettingsFailedToParse, message: "not usable on the federate side: line 1: FED_TIMOUT_CONNECT: unknown setting (known: FED_INT_HEART, FED_TIMEOUT_HEART, FED_TIMEOUT_RECONNECT, FED_INT_RECONNECT, FED_TIMEOUT_CONNECT, TLS_TRUST_ANCHORS, TLS_SERVER_NAME)" }Check the result code if a mistyped setting matters to you. There is one exception, a deliberate
departure from 4.2: on a
tls:// or wss:// address, when no trust anchors are set in code, a TLS_ line the client cannot use
(an unknown key, an empty value, a line without =) fails Connect with ConnectionFailed. Such a line
may be the trust anchors written wrong, and connecting anyway would skip the check of the RTI’s
certificate that you asked for:
RtiError { kind: ConnectionFailed, message: "cannot reach the RTI: additional settings, line 1: TLS_TRUST_ANCHOR: unknown setting (known: FED_INT_HEART, FED_TIMEOUT_HEART, FED_TIMEOUT_RECONNECT, FED_INT_RECONNECT, FED_TIMEOUT_CONNECT, TLS_TRUST_ANCHORS, TLS_SERVER_NAME): over TLS such a line may be the trust anchors written wrong, and the RTI certificate cannot be validated as asked; no connection is made" }Lines whose key starts with neither FED_ nor TLS_ are not read by the client; the RTI receives the
whole text in the Connect request. The same settings can be set in code, through FedProOptions and a
FedProConnector of your own:
use std::time::Duration;
use microrti_client::fedpro::{FedProConnector, FedProOptions};
let mut options = FedProOptions::new()
.with_trust_anchors_file("certs/rti-ca.pem")
.with_tls_server_name("rti.example.org");
options.fed_timeout_connect = Duration::from_secs(5);
let rti = RtiAmbassador::with_connector(FedProConnector::new(options));
let configuration = RtiConfiguration::new().with_rti_address("tls://127.0.0.1");
rti.connect_with_configuration(NullFederateAmbassador, CallbackModel::Evoked, &configuration)?;Settings given in the additional settings of a Connect are applied on top of these options. TLS and authorisation explains the server side.
Credentials
An RTI that requires authorisation expects credentials with Connect. The predefined
HLAplainTextPassword credentials (12.6) carry a password:
let configuration = RtiConfiguration::new().with_rti_address(address);
let credentials = Credentials::plain_text_password(&password);
rti.connect_with_configuration_and_credentials(
NullFederateAmbassador,
CallbackModel::Evoked,
&configuration,
&credentials,
)?;A microrti started with --authorization true refuses a wrong password with
Unauthorized: wrong password, and a Connect without credentials with
Unauthorized: this RTI requires credentials. The password travels in clear over tcp:// and ws://:
use tls:// or wss://. Credentials::new(type, data) builds credentials of any other type.
When the connection breaks
- A broken connection is repaired by the session layer of the Federate Protocol (12.13.4.4): calls wait, no message is lost and the federate does not notice.
- When the session cannot be resumed within
FED_TIMEOUT_RECONNECT, or the RTI has dropped it, services fail withNotConnectedand the federate ambassador receives Connection Lost (4.4).
The methods of RtiAmbassador block. The Federate Protocol link runs its own small I/O runtime on one
thread, and its methods must not be called from inside an asynchronous task: in an async program, call
the RTI from a thread of its own.
Closing without Disconnect
rti.close() ends the connection whatever state the federate is in. The Federate Protocol session is
terminated, and if the federate is still joined, the RTI resigns it with its Automatic Resign Directive,
as it does for a lost federate (4.1.6). close cannot fail, does nothing when the ambassador is not
connected, and, unlike Disconnect, may be called from inside a callback. Dropping the last clone of an
ambassador does the same. It is an extension of this library, not a service of the standard. A federate
that joined as carol and then called close was logged by the server as:
INFO microrti::service: session closed by the federate session=f745c067ba53241d
WARN microrti::service: federate lost session=f745c067ba53241d federation=Closing federate=carol federate_type=CloserAfterwards rti.is_connected() is false and every service fails with NotConnected.
A time limit on services
By default a service waits for the RTI’s answer as long as the connection lasts.
rti.with_call_timeout(Some(duration)) returns another handle to the same ambassador whose services
give up after that long, with an RTIinternalError that is_call_timeout(&error) recognises;
call_timeout() reads the limit. Here Create Federation Execution named a FOM module by an http: URL
whose server accepted the connection and never answered, so the RTI was still waiting for it:
let bounded = rti.with_call_timeout(Some(Duration::from_secs(1)));
let start = Instant::now();
match bounded.create_federation_execution("Slow", &FomModule::url(slow_url.as_str())) {
Ok(()) => println!("created"),
Err(error) if is_call_timeout(&error) => println!("given up after {:?}: {error}", start.elapsed()),
Err(error) => println!("other: {error}"),
}given up after 1.002678333s: RTIinternalError: no response from the RTI within the call timeout of 1s to CreateFederationExecutionRequest; the RTI may still carry it out, its response will be ignoredThe RTI may still carry out a service that was given up, so do not simply call it again. Its late answer is dropped, never taken for the answer of another call. The calls of one federate are carried out in order: in this run the next call of the same federate waited until the RTI had finished with the first, 30 seconds later. Evoke Callback, Evoke Multiple Callbacks, Enable Callbacks and Disable Callbacks have no time limit, and an embedded RTI answers within the call and ignores it.
Callbacks
Callback models
The callback model is chosen at Connect (4.2, 10.57 to 10.60):
CallbackModel::Evoked: callbacks wait until your code callsevoke_callback(wait), which delivers at most one, orevoke_multiple_callbacks(min, max). They run on the calling thread. Both return whether more callbacks are pending.CallbackModel::Immediate: a thread owned by the RTI ambassador delivers callbacks as they arrive.
In both models the callbacks of one federate never run concurrently. disable_callbacks and
enable_callbacks hold delivery back and let it go again.
evoke_callback_counted and evoke_multiple_callbacks_counted are the same two services, but return an
EvokeOutcome with the number of callbacks delivered as well as the pending flag; an idle federate got
EvokeOutcome { delivered: 0, pending: false }. With it, a long wait can be split into short ones
without ever taking two callbacks where Evoke Callback takes one. This too is an extension of the library.
The FederateAmbassador trait
FederateAmbassador has one method per callback, each with an empty default body, so you implement only
the ones you need. Every method returns CallbackResult:
struct Listener;
impl FederateAmbassador for Listener {
fn receive_interaction(
&mut self,
interaction_class: InteractionClassHandle,
parameter_values: ParameterHandleValueMap,
_user_supplied_tag: Bytes,
_transportation_type: TransportationTypeHandle,
producing_federate: FederateHandle,
_sent_regions: Option<ConveyedRegionSet>,
) -> CallbackResult {
println!(
"interaction {interaction_class} from federate {producing_federate}: {} values",
parameter_values.len()
);
Ok(())
}
fn connection_lost(&mut self, fault_description: String) -> CallbackResult {
eprintln!("connection lost: {fault_description}");
Ok(())
}
}Connected with the immediate model, it prints without any evoke call while the main thread does something else:
rti.connect_with_configuration(Listener, CallbackModel::Immediate, &configuration)?;interaction 0000005d from federate 00000002: 2 valuesHandles print as hexadecimal bytes. NullFederateAmbassador ignores every callback.
The Callback enum and CallbackFn
If you prefer one match, the Callback enum has one variant per callback, with named fields, and
CallbackFn turns a closure taking it into a federate ambassador:
let federate = CallbackFn::new(|callback: Callback| {
match callback {
Callback::ReceiveInteraction {
parameter_values, ..
} => {
println!("received {} parameter values", parameter_values.len());
}
Callback::ConnectionLost { fault_description } => {
eprintln!("connection lost: {fault_description}");
}
other => println!("ignored {}", other.name()),
}
Ok(())
});Callback::name() gives the name of the callback’s Federate Protocol message, such as
ReceiveInteraction. A trait implementation can also override handle_callback to receive the enum.
Calling the RTI from a callback
A callback may call any service except Connect, Disconnect, Join Federation Execution, Resign Federation
Execution, Evoke Callback and Evoke Multiple Callbacks (12.8); those fail with
CallNotAllowedFromWithinCallback. Give the federate ambassador a WeakRtiAmbassador: a strong clone
stored inside it would keep the connection alive until Disconnect.
let rti = RtiAmbassador::new();
let weak = rti.downgrade();
let federate = CallbackFn::new(move |callback: Callback| {
if let Callback::ReceiveInteraction {
producing_federate, ..
} = callback
&& let Some(rti) = weak.upgrade()
{
// Allowed here: any service except the six of 12.8.
let sender = rti.get_federate_name(&producing_federate);
println!("greeting from {}", sender.unwrap_or_default());
}
Ok(())
});Errors inside a callback
A federate ambassador reports a failure by returning Err(FederateInternalError::new("...")); the
client sends it to the RTI as a failed callback with the standard name FederateInternalError. A panic
inside a callback is caught and reported the same way, so the delivery thread of the immediate model
survives it.
Handles, values and time
Handles (InteractionClassHandle, ParameterHandle, ObjectInstanceHandle and the others) are opaque
byte strings produced by the RTI; the client compares and orders them but never looks inside. Sets and
maps are type aliases of BTreeSet and BTreeMap, for example AttributeHandleSet and
ParameterHandleValueMap, whose values are Bytes. The ten handle types implement the trait Handle
(TYPE_NAME, from_encoded, decode, encode, as_bytes, encoded_length), for code that works with
any kind of handle. The enumerations of the API, such as ResignAction and OrderType, have to_i32 and
TryFrom<i32>, their numbers in the protobuf schema of the Federate Protocol.
A FOM module is designated by FomModule::file(path) (read when the service is called),
FomModule::content(name, text), FomModule::compressed(zip_bytes) or FomModule::url(url). The
first three send the module itself. With url, the RTI reads the module: a file: URL on its own
machine, an http: or https: URL from the network. The microrti server and an embedded RTI read all
three schemes by default, and their operator can restrict them
(FOM modules named by URL). A name without a scheme,
such as FomModule::url("Chat.xml"), is not a URL and is refused with CouldNotOpenFOM; for a file of
the federate’s machine, use FomModule::file.
Logical times are LogicalTime and LogicalTimeInterval values, in one of the two standard
representations, HLAinteger64Time and HLAfloat64Time; MicroRTI supports no other. Write them
LogicalTime::Integer64(10) and LogicalTime::Float64(2.5), or convert: LogicalTime::from(10_i64),
and, since version 0.5.0, LogicalTime::try_from(2.5)? for an f64, which refuses NaN. From<f64>,
which panicked on NaN, is gone; code that wrote LogicalTime::from(x) or x.into() with an f64 must
change. The same goes for LogicalTimeInterval:
match LogicalTime::try_from(f64::NAN) {
Ok(time) => println!("time {time}"),
Err(error) => println!("{error}"),
}InvalidLogicalTime: a logical time cannot be NaNcreate_federation_execution_with_time chooses the representation, and rti.time_kind() tells which one
the joined federation execution uses. On MicroRTI, a federation execution created without a time
representation uses HLAfloat64Time. Logical time, explained covers the time
services.
Encode and decode values
The RTI moves attribute and parameter values as bytes; the federates agree on their layout through the data types of the FOM, whose encodings are defined by IEEE 1516.2.
Strings in microrti-client
microrti-client itself has the two helpers that most programs need first:
let bytes = encode_hla_unicode_string("Hello");
assert_eq!(decode_hla_unicode_string(&bytes)?, "Hello");An HLAunicodeString is a 32-bit big-endian count of UTF-16 code units, then the code units:
"Hello" gives 00 00 00 05 00 48 00 65 00 6c 00 6c 00 6f. Decoding fails with CouldNotDecode when
the bytes are truncated or are not valid UTF-16.
The microrti-encoding crate
For the other data types, add microrti-encoding (version 0.5).
Its typed layer has a Rust type for each basic representation (HLAinteger32BE(i32),
HLAfloat64BE(f64), HLAoctet(u8) and the others), the strings, arrays as Vec<T> and [T; N], and
macros for records and enumerations, which apply the padding rules of IEEE 1516.2:
hla_fixed_record! {
/// Where something is and how fast it goes.
pub struct Position {
pub x: HLAfloat64BE,
pub y: HLAfloat64BE,
pub speed: HLAinteger32BE,
}
}let here = Position {
x: HLAfloat64BE(1.5),
y: HLAfloat64BE(-2.0),
speed: HLAinteger32BE(12),
};
let bytes = encode_to_vec(&here);
assert_eq!(decode_from_slice_strict::<Position>(&bytes)?, here);The other macros are hla_enumerated!, hla_variant_record! and hla_extendable_variant_record!. A
dynamic layer (DataElement, HLAfixedRecord, HLAvariableArray and the others) builds data types at
run time. Decoding never panics: it returns a DecoderError.
Values by FOM data type: FomCodec
With its cargo feature fom, microrti-encoding adds FomCodec, which encodes and decodes any data type
of a FOM by its name, to and from a self-describing Value. It needs the FOM modules parsed by
microrti-fom:
[dependencies]
microrti-encoding = { version = "0.5", features = ["fom"] }
microrti-fom = "0.5"let module = parse_module("Greetings.xml", &std::fs::read("Greetings.xml")?)?;
let (fdd, _report) = Fdd::create(None, &[module])?;
let codec = FomCodec::new(&fdd)?;
let bytes = codec.encode("HLAunicodeString", &Value::string("Hello"))?;
println!("{}", codec.decode("HLAunicodeString", &bytes)?);This prints "Hello". The monitor and send commands of microrti-cli use the same codec to decode
and encode values (see Watch and operate a federation).
Errors
Every service returns RtiResult<T>, a Result<T, RtiError>. An RtiError has a kind, of type
ExceptionKind, that names the standard exception, and a message for humans. error.name() gives the
standard name, and Display prints both:
FederatesCurrentlyJoined: federation execution 'Greetings' has joined federates: aliceMatch on kind to handle one exception and pass the others on:
match rti.destroy_federation_execution("Greetings") {
Ok(()) => println!("destroyed"),
Err(error) if error.kind == ExceptionKind::FederatesCurrentlyJoined => {
println!("someone is still joined")
}
Err(error) => return Err(error),
}The exceptions you are most likely to meet first, each produced by a test program on MicroRTI:
| Exception | When |
|---|---|
ConnectionFailed | the RTI cannot be reached, the address scheme is unknown, or a TLS_ setting is unusable on a tls:// or wss:// address |
Unauthorized | the RTI requires credentials, or they are wrong |
NotConnected | a service is called before Connect, or after the connection was lost |
AlreadyConnected | Connect is called twice on one ambassador |
FederateNotExecutionMember | a service that needs a joined federate is called before Join |
FederationExecutionAlreadyExists | Create Federation Execution for a name that exists |
FederationExecutionDoesNotExist | Join or Destroy for a name that does not exist |
CouldNotOpenFOM, ErrorReadingFOM, InvalidFOM | a FOM module file is missing, is not XML, or breaks a rule of the FOM; CouldNotOpenFOM also when the RTI refuses or cannot read a module named with FomModule::url |
FederateNameAlreadyInUse | Join with a federate name another joined federate has |
NameNotFound | a class, attribute or parameter name that is not in the FOM |
InteractionClassNotPublished | Send Interaction without publishing the class first |
FederatesCurrentlyJoined | Destroy Federation Execution while federates are still joined |
ExceptionKind lists every exception of the standard; Compliance lists
which services MicroRTI implements. The error types of the libraries themselves, such as LinkError and
LinkState here and FedProError in microrti-fedpro, are #[non_exhaustive] since version 0.5.0, so
that later versions can add variants: a match on them needs a _ arm. ExceptionKind and the
enumerations that the standard or the Federate Protocol fix stay exhaustive.
An RTI in your process
With the feature embedded, EmbeddedRti runs the MicroRTI engine inside your program, and any number
of RTI ambassadors connect to it:
let embedded = EmbeddedRti::new(RtiConfig::default());
let rti = embedded.ambassador();
rti.connect(NullFederateAmbassador, CallbackModel::Evoked)?;embedded.register("embedded") makes it reachable by RtiAmbassador::new() with the RTI address
embedded:, so code written for a server runs unchanged; the last section of
Your first federate in Rust does that.
An RTI inside your process has the details.
For other transports, RtiLink is the interface between the RTI ambassador and whatever carries the
service messages, LinkFactory opens links for an address, and register_connector adds a connector for
an address scheme.
Examples in the repository
The examples live in the microrti-examples
crate. cargo install microrti-examples installs the programs chat and restaurant; the examples
minimal_federate and interop_scenario run from a clone of the repository.
| Example | What it shows | Command |
|---|---|---|
minimal_federate | a whole federate in about thirty lines: joins the chat room, says hello, prints what it hears | cargo run -p microrti-examples --example minimal_federate -- tcp://127.0.0.1:15164 10 |
chat | interactions, plus one object instance per participant (Discover and Remove Object Instance) | cargo run -p microrti-examples --bin chat -- --rti tcp://127.0.0.1:15164 --name alice |
restaurant | the Restaurant sample FOM of IEEE 1516.2-2025: objects, attribute updates, and values encoded as integers, floats, enumerations, strings, a fixed record and a variant record | cargo run -p microrti-examples --bin restaurant -- demo |
restaurant demo runs a waiter and a guest on an RTI inside the process and checks that the guest saw
everything the waiter sent. It ends with:
demo: PASS: the guest saw everything the waiter sent, once, with the values sentchat and restaurant also take --password, --tls-trust-anchors and --setting KEY=VALUE, which map
to the credentials and connection settings above.
API documentation
docs.rs/microrti-client documents the crate with all its features,
the modules embedded and testing included, and
docs.rs/microrti-encoding has the fom module. To read the
documentation of the exact versions your project uses, offline:
cargo doc -p microrti-client --no-deps --open