v1.3.0.0
WASimCommander::Client::WASimClient Class Reference

WASimCommander Client implementation. Handles all aspects of communication with the WASimCommander Server WASM module. More...

#include "WASimClient.h"

Public Member Functions

 WASimClient (uint32_t clientId, const std::string &configFile=std::string())
 Instantiate the client with a unique ID and optional configuration file path. More...
 
 ~WASimClient ()
 Any open network connections are automatically closed upon destruction, though it is better to close them yourself before deleting the client. More...
 
Network actions, status, and settings
ClientStatus status () const
 Get current connection status of this client. More...
 
bool isInitialized () const
 Check if simulator network link is established. More...
 
bool isConnected () const
 Check WASimCommander server connection status. More...
 
uint32_t clientVersion () const
 Return the current WASimClient version number. Version numbers are in "BCD" format: MAJOR << 24 | MINOR << 16 | PATCH << 8 | BUILD, eg: 1.23.45.67 = 0x01234567 More...
 
uint32_t serverVersion () const
 Return the version number of the last-connected, or successfully pinged, WASimModule (sever), or zero if unknown. See clientVersion() for numbering details. More...
 
HRESULT connectSimulator (uint32_t timeout=0)
 Initialize the simulator network link and set up minimum necessary for WASimCommander server ping or connection. Uses default network SimConnect configuration ID. More...
 
HRESULT connectSimulator (int networkConfigId, uint32_t timeout=0)
 Initialize the simulator network link and set up minimum necessary for WASimCommander server ping or connection. This overload allows specifying a SimConnect configuration ID and optional timeout value. More...
 
void disconnectSimulator ()
 Shut down all network connections (and disconnect WASimCommander server if connected). After calling this method, one must call connectSimulator()/connectServer()/pingServer() again before any other commands. More...
 
uint32_t pingServer (uint32_t timeout=0)
 Check if WASimCommander Server exists (Simulator running, the WASIM module is installed and working). Returns server version number, or zero if server did not respond.
This will implicitly call connectSimulator() first if it hasn't already been done, using the default network configuration settings. Zero will be returned if the connection could not be established. More...
 
HRESULT connectServer (uint32_t timeout=0)
 Connect to WASimCommander server. This will implicitly call connectSimulator() first if it hasn't already been done, using the default network configuration setting. More...
 
void disconnectServer ()
 Disconnect from the WASimCommander server. This does not close the Simulator network connection (use disconnectSimulator() to do that or both at once). More...
 
uint32_t defaultTimeout () const
 Get the current default server response timeout value, which is used in all network requests. The initial default setting is read from the client_conf.ini file or set to 1000ms if no config file was found. More...
 
void setDefaultTimeout (uint32_t ms)
 Get current connection status of this client. More...
 
int networkConfigurationId () const
 SimConnect is used for the network layer. This setting specifies the SimConnect.cfg index to use. The value of -1 forces a local connection. The initial default setting is read from the client_conf.ini file or set to -1 if no config file was found. More...
 
void setNetworkConfigurationId (int configId)
 SimConnect is used for the network layer. This setting specifies the SimConnect.cfg index to use, or -1 to force a local connection. Note that this must be called before connectSimulator() invocation in order to have any effect. More...
 
RPN calculator code execution and reusable events
HRESULT executeCalculatorCode (const std::string &code, WASimCommander::Enums::CalcResultType resultType=WASimCommander::Enums::CalcResultType::None, double *pfResult=nullptr, std::string *psResult=nullptr) const
 Run a string of MSFS Gauge API calculator code in RPN format, possibly with some kind of result expected. More...
 
HRESULT registerEvent (const RegisteredEvent &eventData)
 Register a reusable event which executes a pre-set RPN calculator code string. The code is pre-compiled and stored on the server for quicker execution. The event can have an optional custom name for direct use with any SimConnect client. Registered events can also be triggered by using the transmitEvent() method. If the server is not currently connected, the event registration will be queued and sent next time a connection is established. More...
 
HRESULT removeEvent (uint32_t eventId)
 Remove an event previously registered with registerEvent() method. This is effectively the same as calling registerEvent() with an empty code parameter. If the server is not currently connected, the removal request will be queued and sent next time a connection is established. More...
 
HRESULT transmitEvent (uint32_t eventId)
 Trigger an event previously registered with registerEvent(). This is a more direct alternative to triggering events by name via SimConnect. More...
 
RegisteredEvent registeredEvent (uint32_t eventId)
 Returns a copy of a RegisteredEvent which has been previously added with registerEvent(). If the event with the given eventId doesn't exist, an invalid RegisteredEvent is returned which has the members RegisteredEvent::eventId set to -1, and RegisteredEvent::code and RegisteredEvent::name both empty. More...
 
std::vector< RegisteredEventregisteredEvents () const
 Returns a list of all registered events which have been added to the Client with registerEvent(). The list members are created by copy. More...
 
Variables accessor methods
HRESULT getVariable (const VariableRequest &variable, double *pfResult, std::string *psResult=nullptr)
 Get a Variable value by name, with optional named unit type. This is primarily useful for local ('L') variables, SimVars ('A') and token variables ('T') which can be read via dedicated Gauge API functions (get_named_variable_value()/get_named_variable_typed_value(), aircraft_varget(), and lookup_var() respectively).
Other variables types can also be set this way ('C', 'E', 'M', etc) but such requests are simply converted to a calculator string and evaluated via the Gauge API execute_calculator_code().
Likewise, requesting string-type variables using this method also ends up running a calculator expression on the server side.
In both cases, using WASimClient::executeCalculatorCode() directly may be more efficient. Also, unlike executeCalculatorCode(), this method will not return a string representation of a numeric value. More...
 
HRESULT getLocalVariable (const std::string &variableName, double *pfResult, const std::string &unitName=std::string())
 A convenience version of getVariable(VariableRequest(variableName, false, unitName), pfResult). See getVariable() and VariableRequest for details. More...
 
HRESULT getOrCreateLocalVariable (const std::string &variableName, double *pfResult, double defaultValue=0.0, const std::string &unitName=std::string())
 Gets the value of a local variable just like getLocalVariable() but will also create the variable on the simulator if it doesn't already exist. More...
 
HRESULT setVariable (const VariableRequest &variable, const double value)
 Set a Variable value by name, with optional named unit type. Although any settable variable type can set this way, it is primarily useful for local (L) variables which can be set via dedicated Gauge API functions (set_named_variable_value() and set_named_variable_typed_value()).

Other variables types can also be set this way but such requests are simply converted to a calculator string and evaluated via the Gauge API execute_calculator_code(). Using WASimClient::executeCalculatorCode() directly may be more efficient.
The following conditions must be observed: More...
 
HRESULT setVariable (const VariableRequest &variable, const std::string &stringValue)
 This is an overloaded method. This version allows setting an 'A' type (SimVar) variable to a string value. Only 'A' type variables can be set this way.
Since there is actually no direct way to set string-type values from WASM code, this is just a conveneince method and simply invokes SimConnect to do the work. On first use with a new variable name it will set up a mapping of the name to an internally-assigned ID (calling SimConnect_AddToDataDefinition()) and cache that mapping. Then on subsequent invocations on the same variable the mapped ID will be used directly. The mappings are invalidated when disconnecting from the simulator. More...
 
HRESULT setLocalVariable (const std::string &variableName, const double value, const std::string &unitName=std::string())
 A convenience version of setVariable() for Local variable types. Equivalent to setVariable(VariableRequest(variableName, false, unitName), value). See setVariable() and VariableRequest for details. More...
 
HRESULT setOrCreateLocalVariable (const std::string &variableName, const double value, const std::string &unitName=std::string())
 Set a Local Variable value by variable name, creating it first if it does not already exist. This first calls the register_named_variable() Gauge API function to get the ID from the name, which creates the variable if it doesn't exist. The returned ID (new or existing) is then used to set the value. Use the lookup() method to check for the existence of a variable name. Equivalent to setVariable(VariableRequest(variableName, true, unitName), value). See setVariable() and VariableRequest for details. More...
 
HRESULT setSimVarVariable (const std::string &variableName, const std::string &unitName, double value)
 Sets a numeric value on an 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to setVariable(VariableRequest(variableName, unitName), value). See setVariable() and VariableRequest for details.
Note that variableName can optionally contain an index after a colon (eg. VAR NAME:1), or the setSimVarVariable(const string& name, uint8_t index, const string& unit, double value) overload could be used to provide the index separately. More...
 
HRESULT setSimVarVariable (const std::string &variableName, uint8_t simVarIndex, const std::string &unitName, double value)
 Sets a numeric value on an indexed 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to setVariable(VariableRequest(variableName, unitName, simVarIndex), value). See setVariable() and VariableRequest for details. More...
 
HRESULT setSimVarVariable (const std::string &variableName, const std::string &stringValue)
 Sets a string value on an 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to ‘setVariable(VariableRequest('A’, variableName), stringValue). SeesetVariable(const VariableRequest &, const std::string &)` for details. More...
 
HRESULT setSimVarVariable (const std::string &variableName, uint8_t index, const std::string &stringValue)
 Sets a string value on an indexed 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to setVariable(VariableRequest(variableName, {}, index), stringValue). See setVariable(const VariableRequest &, const std::string &) for details. More...
 
Data change subscriptions (variables and calculated results)
HRESULT saveDataRequest (const DataRequest &request, bool async=false)
 Add a new WASimCommander::DataRequest for a variable or calculated result, or update an existing data request with the same DataRequest::requestId. Data changes (updates) are delivered asynchronously via the callback function set with setDataCallback(), which then passes a DataRequestRecord structure as the callback argument (this provides both a reference to the original DataRequest registered here, as well as result data). More...
 
HRESULT removeDataRequest (const uint32_t requestId)
 Remove a previously-added DataRequest. This clears the subscription and any tracking/meta data from both server and client sides. Using this method is effectively the same as calling dataRequest() with a DataRequest of type RequestType::None. More...
 
HRESULT updateDataRequest (uint32_t requestId)
 Trigger a data update on a previously-added DataRequest. Designed to refresh data on subscriptions with update periods of UpdatePeriod::Never or UpdatePeriod::Once, though it can be used with any subscription. Using this update method also skips any equality checks on the server side (though any delta epsilon value remains in effect on client side). More...
 
DataRequestRecord dataRequest (uint32_t requestId) const
 Returns a copy of a DataRequestRecord which has been previously added. If the request with the given requestId doesn't exist, an invalid DataRequestRecord is returned which has the members DataRequest::requestId set to -1, DataRequest::valueSize set to 0, and DataRequest::requestType set to RequestType::None. More...
 
std::vector< DataRequestRecorddataRequests () const
 Returns a list of all data requests which have been added to the Client so far. (These are returned by copy operation, so for a long list it may get "expensive.") More...
 
std::vector< uint32_t > dataRequestIdsList () const
 Returns a list of all DataRequest::requestIds which have been added to the Client so far. More...
 
HRESULT setDataRequestsPaused (bool paused) const
 Enables or disables all data request subscription updates at the same time. Use this to temporarily suspend value update checks when they are not needed, but may be again in the future. This is a lot more efficient than disconnecting and re-connecting to the server, since all the data requests need to be re-created upon every new connection (similar to SimConnect itself). More...
 
Simulator Key Events
HRESULT sendKeyEvent (uint32_t keyEventId, uint32_t v1=0, uint32_t v2=0, uint32_t v3=0, uint32_t v4=0, uint32_t v5=0) const
 Can be used to trigger standard Simulator "Key Events" as well as "custom" Gauge API/SimConnect events. Up to 5 optional values can be passed onto the event handler. This provides functionality similar to the Gauge API function trigger_key_event_EX1() and SimConnect_TransmitClientEvent[_EX1()].

Standard Key Event IDs can be found in the SimConnect SDK header file 'MSFS/Legacy/gauges.h' in the form of KEY_* macro values, and event names can also be resolved to IDs programmatically using the lookup() method. No preliminary setup is required to trigger these events, but a full connection to WASimModule ("Server") is needed. These are triggered on the simulator side using trigger_key_event_EX1() function calls.

Custom Events for which a numeric ID is already known (typically in the Gauge API THIRD_PARTY_EVENT_ID_MIN/THIRD_PARTY_EVENT_ID_MAX ID range) can also be triggered directly as with standard events. These types of events are also passed directly to trigger_key_event_EX1().

Named Custom Events, for which an ID is not known or predefined, must first be registered with registerCustomKeyEvent(), which creates and maps (and optionally returns) a unique ID corresponding to the custom event name. An active simulator (SimConnect) connection is required to trigger these types of events. They are invoked via SimConnect_TransmitClientEvent[_EX1()] method directly from this client (this is actually just a convenience for the WASimClient user to avoid needing a separate SimConnect session). Which actual SimConnect function is used depends on how the custom event was registered (default is to use the newer "_EX1" version which allows up to 5 event values).
See docs for registerCustomKeyEvent() for further details on using custom simulator events. More...
 
HRESULT sendKeyEvent (const std::string &keyEventName, uint32_t v1=0, uint32_t v2=0, uint32_t v3=0, uint32_t v4=0, uint32_t v5=0)
 This is an overloaded method. See sendKeyEvent(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) const for main details. This version allows triggering Key Events by name instead of an ID.

All simulator event names must be resolved, or mapped, to a numeric ID before they can be triggered (used). The first time this method is invoked with a particular event name, it tries to associate that name with an ID (based on the event name, as described below). If successful, the ID is cached, so subsequent calls to this method, with the same event name, will use the cached ID instead of trying to resolve the name again. More...
 
HRESULT registerCustomKeyEvent (const std::string &customEventName, uint32_t *puiCustomEventId=nullptr, bool useLegacyTransmit=false)
 Register a "Custom Simulator [Key] Event" by providing an event name. The method optionally returns the generated event ID, which can later be used with sendKeyEvent() method instead of the event name. It can also be used to look up a previous registration's ID if the event name has already been registered.

Custom event names are mapped to internally-generated unique IDs using a standard SimConnect call to MapClientEventToSimEvent, which briefly describes custom event usage and name syntax in the EventName parameter description. This method serves a similar purpose (and in fact eventually calls that same SimConnect function).

The mappings must be re-established every time a new connection with SimConnect is made, which WASimClient takes care of automatically. If currently connected to the simulator, the event is immediately mapped, otherwise it will be mapped upon the next connection. An event registration can be removed with removeCustomKeyEvent() which will prevent any SimConnect mapping from being created upon the next connection.

Note that the custom event mapping/triggering feature is actually just a convenience for the WASimClient user and doesn't involve the usual Server interactions (WASimModule) at all.
. More...
 
HRESULT removeCustomKeyEvent (const std::string &customEventName)
 Remove a Custom Event previously registered with registerCustomEvent() method using the event's name. This will prevent the custom event from being mapped next time the client connects to SimConnect. More...
 
HRESULT removeCustomKeyEvent (uint32_t eventId)
 This is an overloaded method. Same as removeCustomKeyEvent(const string &) but the event can be specified using the associated numeric event ID (originally returned from registerCustomKeyEvent()) instead of the name. More...
 
Metadata retrieval
HRESULT list (WASimCommander::Enums::LookupItemType itemsType=WASimCommander::Enums::LookupItemType::LocalVariable)
 Send a request for a list update to the server. The results are delivered using the callback set in setListResultsCallback(). More...
 
HRESULT lookup (WASimCommander::Enums::LookupItemType itemType, const std::string &itemName, int32_t *piResult)
 Request server-side lookup of an named item to find the corresponding numeric ID. More...
 
Low level API
HRESULT sendCommand (const Command &command) const
 Sends a command, in the form of a WASimCommander::Command structure, to the server for processing. The various command types and the data requirements for each are described in the WASimCommander::Enums::CommandId documentation. To receive command responses from the server, set a callback with setCommandResultCallback(), then check the results for a Command::token which matches the token set in the command you're sending here. More...
 
HRESULT sendCommandWithResponse (const Command &command, Command *response, uint32_t timeout=0)
 Sends a command, in the form of a WASimCommander::Command structure, to the server for processing and waits for a reply (an Ack/Nak response Command). The various command types and the data requirements for each are described in the WASimCommander::Enums::CommandId documentation. More...
 
Logging settings
WASimCommander::Enums::LogLevel logLevel (WASimCommander::Enums::LogFacility facility, LogSource source=LogSource::Client) const
 Get the current minimum logging severity level for the specified facility and source. More...
 
void setLogLevel (WASimCommander::Enums::LogLevel level, WASimCommander::Enums::LogFacility facility=WASimCommander::Enums::LogFacility::Remote, LogSource source=LogSource::Client)
 Set the current minimum logging severity level for the specified facility and source to level. More...
 
Callbacks
Note
In general, callbacks may be invoked concurrently (and possibly from different threads). The callback handler functions should at least be reentrant (if not thread-safe) since they could be called at any time. Check the individual method documentation for more details about possible concurrency and threading.
The client can be built with WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS macro/definition set to 0 to disable concurrency.

void setClientEventCallback (clientEventCallback_t cb)
 Sets a callback for Client event updates which indicate status changes. Pass a nullptr value to remove a previously set callback.
Usage: More...
 
template<class Tcaller >
void setClientEventCallback (void(__stdcall Tcaller::*const member)(const ClientEvent &), Tcaller *const caller)
 Same as setClientEventCallback(clientEventCallback_t). Convenience for avoiding a std::bind expression.
Usage: More...
 
void setListResultsCallback (listResultsCallback_t cb)
 Sets a callback for list results arriving from the server. Pass a nullptr value to remove a previously set callback.
Usage: More...
 
template<class Tcaller >
void setListResultsCallback (void(__stdcall Tcaller::*const member)(const ListResult &), Tcaller *const caller)
 Same as setListResultsCallback(listResultsCallback_t). Convenience for avoiding a std::bind expression.
Usage: More...
 
void setDataCallback (dataCallback_t cb)
 Sets a callback for value update data arriving from the server. Pass a nullptr value to remove a previously set callback.
Usage: More...
 
template<class Tcaller >
void setDataCallback (void(__stdcall Tcaller::*const member)(const DataRequestRecord &), Tcaller *const caller)
 Same as setDataCallback(dataCallback_t). Convenience overload template for avoiding a std::bind expression.
Usage: More...
 
void setLogCallback (logCallback_t cb)
 Sets a callback for logging activity, both from the server and the client itself. Pass a nullptr value to remove a previously set callback.
Usage: More...
 
template<class Tcaller >
void setLogCallback (void(__stdcall Tcaller::*const member)(const LogRecord &, LogSource), Tcaller *const caller)
 Same as setLogCallback(logCallback_t). Convenience template for avoiding a std::bind expression.
Usage: More...
 
void setCommandResultCallback (commandCallback_t cb)
 Sets a callback for delivering command results returned by the server. Pass a nullptr value to remove a previously set callback. While some of the high-level Client API calls do return an immediate status or result, many of the server commands are sent asynchronously, in a fire-and-forget fashion. If you would like to be notified about all command responses, set this callback. The Command type delivered will have the Command::commandId of type CommandId::Ack or CommandId::Nak. The Command::uData member is set to the commandId of the original command being responded to. Other Command struct members may have other meanings, depending on the actual command being responded to. See documentation for WASimCommander::Enums::CommandId for details.
Usage: More...
 
template<class Tcaller >
void setCommandResultCallback (void(__stdcall Tcaller::*const member)(const Command &), Tcaller *const caller)
 Same as setCommandResultCallback(commandCallback_t). Convenience overload template for avoiding a std::bind expression.
Usage: More...
 
void setResponseCallback (commandCallback_t cb)
 Sets a callback for delivering response commands sent to this client by the server module. Note that the server may also initiate a few types of commands (not in response to client commands) such as Ping, List, and Disconnect. In contrast to setCommandResultCallback(commandCallback_t), this one will report on all commands from the server, not just Ack/Nak. This callback is meant for low-level API usage.
Usage: More...
 
template<class Tcaller >
void setResponseCallback (void(__stdcall Tcaller::*const member)(const Command &), Tcaller *const caller)
 Same as setResponseCallback(commandCallback_t). Convenience overload template for avoiding a std::bind expression.
Usage: More...
 

Detailed Description

WASimCommander Client implementation. Handles all aspects of communication with the WASimCommander Server WASM module.

Definition at line 84 of file WASimClient.h.

Constructor & Destructor Documentation

◆ WASimClient()

WASimCommander::Client::WASimClient::WASimClient ( uint32_t  clientId,
const std::string &  configFile = std::string() 
)
explicit

Instantiate the client with a unique ID and optional configuration file path.

Parameters
clientIdThis ID must not be shared with any other Client accessing the Server. The ID is also used as the client name by converting it to a 8-character hexadecimal string. For example 3235839725 = "C0DEFEED". Get creative. The client name is used as a key component of data exchange with the simulator engine. The ID cannot be zero, and server connections will fail if it is. It can also be set/changed after class creation using the setClientId() method, but before connecting to the server.
configFileOptionally provide the path to a configuration file for reading initial startup settings. By default the client will look for a client_conf.ini file in the current working directory. The parameter value may include the file name (with extension), or be only a file system path, in which case the default file name of "client_conf.ini" will be appended.

Definition at line 1613 of file WASimClient.cpp.

◆ ~WASimClient()

WASimClient::~WASimClient ( )

Any open network connections are automatically closed upon destruction, though it is better to close them yourself before deleting the client.

Definition at line 1617 of file WASimClient.cpp.

Member Function Documentation

◆ status()

ClientStatus WASimCommander::Client::WASimClient::status ( ) const

Get current connection status of this client.

See also
WASimCommander::Client::ClientStatus

Definition at line 2041 of file WASimClient.cpp.

◆ isInitialized()

bool WASimCommander::Client::WASimClient::isInitialized ( ) const

Check if simulator network link is established.

See also
connectSimulator()

Definition at line 2042 of file WASimClient.cpp.

◆ isConnected()

bool WASimCommander::Client::WASimClient::isConnected ( ) const

Check WASimCommander server connection status.

See also
connectServer()

Definition at line 2043 of file WASimClient.cpp.

◆ clientVersion()

uint32_t WASimCommander::Client::WASimClient::clientVersion ( ) const

Return the current WASimClient version number. Version numbers are in "BCD" format: MAJOR << 24 | MINOR << 16 | PATCH << 8 | BUILD, eg: 1.23.45.67 = 0x01234567

Definition at line 2044 of file WASimClient.cpp.

◆ serverVersion()

uint32_t WASimCommander::Client::WASimClient::serverVersion ( ) const

Return the version number of the last-connected, or successfully pinged, WASimModule (sever), or zero if unknown. See clientVersion() for numbering details.

Definition at line 2045 of file WASimClient.cpp.

◆ connectSimulator() [1/2]

HRESULT WASimCommander::Client::WASimClient::connectSimulator ( uint32_t  timeout = 0)

Initialize the simulator network link and set up minimum necessary for WASimCommander server ping or connection. Uses default network SimConnect configuration ID.

Parameters
timeoutMaximum time to wait for response, in milliseconds. Zero (default) means to use the defaultTimeout() value.
Returns
S_OK (0) - Success;
E_FAIL (0x80004005) - General failure (most likely simulator is not running);
E_TIMEOUT (0x800705B4) - Connection attempt timed out (simulator/network issue);
E_INVALIDARG (0x80070057) - The Client ID set in constructor is invalid (zero) or the SimConnect.cfg file did not contain the default config index (see networkConfigurationId() ) ;
Note
This method blocks until either the Simulator responds or the timeout has expired.
See also
defaultTimeout(), setDefaultTimeout(), networkConfigurationId() setNetworkConfigurationId(), connectSimulator(int, uint32_t)

Definition at line 1626 of file WASimClient.cpp.

◆ connectSimulator() [2/2]

HRESULT WASimCommander::Client::WASimClient::connectSimulator ( int  networkConfigId,
uint32_t  timeout = 0 
)

Initialize the simulator network link and set up minimum necessary for WASimCommander server ping or connection. This overload allows specifying a SimConnect configuration ID and optional timeout value.

Parameters
networkConfigIdSimConnect is used for the network layer. Specify the SimConnect.cfg index to use, or -1 (default) to force a local connection.
timeoutMaximum time to wait for response, in milliseconds. Zero (default) means to use the defaultTimeout() value.
Returns
S_OK (0) - Success;
E_FAIL (0x80004005) - General failure (most likely simulator is not running);
E_TIMEOUT (0x800705B4) - Connection attempt timed out (simulator/network issue);
E_INVALIDARG (0x80070057) - The Client ID set in constructor is invalid (zero) or the SimConnect.cfg file did not contain the config index requested in the simConnectConfigId parameter;
Note
This method blocks until either the Simulator responds or the timeout has expired.
See also
connectSimulator(), defaultTimeout(), setDefaultTimeout()

Definition at line 1635 of file WASimClient.cpp.

◆ disconnectSimulator()

void WASimCommander::Client::WASimClient::disconnectSimulator ( )

Shut down all network connections (and disconnect WASimCommander server if connected). After calling this method, one must call connectSimulator()/connectServer()/pingServer() again before any other commands.

Definition at line 1639 of file WASimClient.cpp.

◆ pingServer()

uint32_t WASimCommander::Client::WASimClient::pingServer ( uint32_t  timeout = 0)

Check if WASimCommander Server exists (Simulator running, the WASIM module is installed and working). Returns server version number, or zero if server did not respond.
This will implicitly call connectSimulator() first if it hasn't already been done, using the default network configuration settings. Zero will be returned if the connection could not be established.

Parameters
timeoutMaximum time to wait for response, in milliseconds. Zero (default) means to use the defaultTimeout() value.
Returns
Server version number, or zero (0) if server (or simulator) didn't respond within the timeout period.
Note
This method blocks until either the Server responds or the timeout has expired.
See also
defaultTimeout(), setDefaultTimeout()

Definition at line 1651 of file WASimClient.cpp.

◆ connectServer()

HRESULT WASimCommander::Client::WASimClient::connectServer ( uint32_t  timeout = 0)

Connect to WASimCommander server. This will implicitly call connectSimulator() first if it hasn't already been done, using the default network configuration setting.

Parameters
timeoutMaximum time to wait for response, in milliseconds. Zero (default) means to use the defaultTimeout() value.
Returns
S_OK (0) - Success.
E_FAIL (0x80004005) - General failure (most likely simulator is not running).
E_TIMEOUT (0x800705B4) - Connection attempt timed out (simulator/network issue or WASimCommander WASM module is not installed/running).
E_INVALIDARG (0x80070057) - The Client ID set in constructor is invalid (zero) or the SimConnect.cfg file did not contain the default config index.
Note
This method blocks until either the Server responds or the timeout has expired.
See also
defaultTimeout(), setDefaultTimeout()

Definition at line 1643 of file WASimClient.cpp.

◆ disconnectServer()

void WASimCommander::Client::WASimClient::disconnectServer ( )

Disconnect from the WASimCommander server. This does not close the Simulator network connection (use disconnectSimulator() to do that or both at once).

Definition at line 1647 of file WASimClient.cpp.

◆ defaultTimeout()

uint32_t WASimCommander::Client::WASimClient::defaultTimeout ( ) const

Get the current default server response timeout value, which is used in all network requests. The initial default setting is read from the client_conf.ini file or set to 1000ms if no config file was found.

See also
setDefaultTimeout(). Set the default timeout period for server responses. The default may be inadequate on slow network links or a very busy simulator.
defaultTimeout()

Definition at line 2047 of file WASimClient.cpp.

◆ setDefaultTimeout()

void WASimCommander::Client::WASimClient::setDefaultTimeout ( uint32_t  ms)

Get current connection status of this client.

See also
WASimCommander::Client::ClientStatus

Definition at line 2048 of file WASimClient.cpp.

◆ networkConfigurationId()

int WASimCommander::Client::WASimClient::networkConfigurationId ( ) const

SimConnect is used for the network layer. This setting specifies the SimConnect.cfg index to use. The value of -1 forces a local connection. The initial default setting is read from the client_conf.ini file or set to -1 if no config file was found.

See also
setNetworkConfigurationId().

Definition at line 2050 of file WASimClient.cpp.

◆ setNetworkConfigurationId()

void WASimCommander::Client::WASimClient::setNetworkConfigurationId ( int  configId)

SimConnect is used for the network layer. This setting specifies the SimConnect.cfg index to use, or -1 to force a local connection. Note that this must be called before connectSimulator() invocation in order to have any effect.

See also
networkConfigurationId().

Definition at line 2051 of file WASimClient.cpp.

◆ executeCalculatorCode()

HRESULT WASimCommander::Client::WASimClient::executeCalculatorCode ( const std::string &  code,
WASimCommander::Enums::CalcResultType  resultType = WASimCommander::Enums::CalcResultType::None,
double *  pfResult = nullptr,
std::string *  psResult = nullptr 
) const

Run a string of MSFS Gauge API calculator code in RPN format, possibly with some kind of result expected.

Parameters
codeThe text of the code to execute. See https://docs.flightsimulator.com/html/Additional_Information/Reverse_Polish_Notation.htm
resultTypeExpected result type, or Enums::CalcResultType::None (default) if no result is expected. If the type is Enums::CalcResultType::Formatted then the server runs the code using format_calculator_string() Gauge API function (see @ bottom of RPN docs for formatting options) and the result type is always a string. Otherwise execute_calculator_code() is used and any of the result types can be returned (in fact execute_calculator_code() always returns any results in all 3 types at once, so even if a numeric result is requested, the string result will also be populated).
pfResultA pointer to an initialized variable of double to store the result into if resultType is Enums::CalcResultType::Double or Enums::CalcResultType::Integer.
psResultA string pointer to store the string result into. The string version is typically populated even for numeric type requests, but definitely for Enums::CalcResultType::String or Enums::CalcResultType::Formatted type requests.
Returns
S_OK on success, E_NOT_CONNECTED if not connected to server;
If a result is expected, may also return E_FAIL if the server returned Nak response, or E_TIMEOUT on general server communication failure.
Note
If a result is expected (resultType != Enums::CalcResultType::None) then this method blocks until either the Server responds or the timeout has expired (see defaultTimeout()). To request calculated results in a non-blocking fashion, use a data request instead.

If you need to execute the same code multiple times, it would be more efficient to save the code as either a data request (for code returning values) or a registered event (for code not returning values). The advantage is that in those cases the calculator string is pre-compiled to byte code and saved once, then each invocation of the Gauge API calculator functions uses the more efficient byte code version. (To prevent automatic data updates for data requests, just set the data request period to Enums::UpdatePeriod::Never or Enums::UpdatePeriod::Once and use the updateDataRequest() method to poll for value updates as needed.) See saveDataRequest() and registerEvent() respectively for details.

See also
Enums::CommandId::Exec, defaultTimeout(), setDefaultTimeout()

Definition at line 1679 of file WASimClient.cpp.

◆ getVariable()

HRESULT WASimCommander::Client::WASimClient::getVariable ( const VariableRequest variable,
double *  pfResult,
std::string *  psResult = nullptr 
)

Get a Variable value by name, with optional named unit type. This is primarily useful for local ('L') variables, SimVars ('A') and token variables ('T') which can be read via dedicated Gauge API functions (get_named_variable_value()/get_named_variable_typed_value(), aircraft_varget(), and lookup_var() respectively).
Other variables types can also be set this way ('C', 'E', 'M', etc) but such requests are simply converted to a calculator string and evaluated via the Gauge API execute_calculator_code().
Likewise, requesting string-type variables using this method also ends up running a calculator expression on the server side.
In both cases, using WASimClient::executeCalculatorCode() directly may be more efficient. Also, unlike executeCalculatorCode(), this method will not return a string representation of a numeric value.

Parameters
variableSee VariableRequest documentation for descriptions of the individual fields.
pfResultPointer to a double precision variable to hold the numeric result.
psResultPointer to a string type variable to hold a string-type result. See notes above regarding string types.
Returns
S_OK on success, E_INVALIDARG on parameter validation errors, E_NOT_CONNECTED if not connected to server, E_TIMEOUT on server communication failure, or E_FAIL if server returns a Nak response.
Note
This method blocks until either the Server responds or the timeout has expired.
See also
Client::VariableRequest, Enums::CommandId::Get, defaultTimeout(), setDefaultTimeout()

Definition at line 1708 of file WASimClient.cpp.

◆ getLocalVariable()

HRESULT WASimCommander::Client::WASimClient::getLocalVariable ( const std::string &  variableName,
double *  pfResult,
const std::string &  unitName = std::string() 
)

A convenience version of getVariable(VariableRequest(variableName, false, unitName), pfResult). See getVariable() and VariableRequest for details.

Parameters
variableNameName of the local variable.
pfResultPointer to a double precision variable to hold the result.
unitNameOptional unit specifier to use. Most Local vars do not specify a unit and default to a generic "number" type.
Returns
S_OK on success, E_INVALIDARG on parameter validation errors, E_NOT_CONNECTED if not connected to server, E_TIMEOUT on server communication failure, or E_FAIL if server returns a Nak response.
Note
This method blocks until either the Server responds or the timeout has expired.
See also
Enums::CommandId::Get, defaultTimeout(), setDefaultTimeout()

Definition at line 1717 of file WASimClient.cpp.

◆ getOrCreateLocalVariable()

HRESULT WASimCommander::Client::WASimClient::getOrCreateLocalVariable ( const std::string &  variableName,
double *  pfResult,
double  defaultValue = 0.0,
const std::string &  unitName = std::string() 
)

Gets the value of a local variable just like getLocalVariable() but will also create the variable on the simulator if it doesn't already exist.

Parameters
variableNameName of the local variable.
pfResultPointer to a double precision variable to hold the result.
defaultValueThe L var will be created on the simulator if it doesn't exist yet using this initial value (and this same value will be returned in pfResult).
unitNameOptional unit specifier to use. Most Local vars do not specify a unit and default to a generic "number" type.
Returns
S_OK on success, E_INVALIDARG on parameter validation errors, E_NOT_CONNECTED if not connected to server, E_TIMEOUT on server communication failure, or E_FAIL if server returns a Nak response.
Note
This method blocks until either the Server responds or the timeout has expired.
See also
Enums::CommandId::GetCreate, defaultTimeout(), setDefaultTimeout()

Definition at line 1721 of file WASimClient.cpp.

◆ setVariable() [1/2]

HRESULT WASimCommander::Client::WASimClient::setVariable ( const VariableRequest variable,
const double  value 
)

Set a Variable value by name, with optional named unit type. Although any settable variable type can set this way, it is primarily useful for local (L) variables which can be set via dedicated Gauge API functions (set_named_variable_value() and set_named_variable_typed_value()).

Other variables types can also be set this way but such requests are simply converted to a calculator string and evaluated via the Gauge API execute_calculator_code(). Using WASimClient::executeCalculatorCode() directly may be more efficient.
The following conditions must be observed:

  • The variable type in VariableRequest::variableType must be "settable" ('A', 'C', 'H', 'K', 'L', or 'Z'), otherwise an E_INVALIDARG result is returned.
  • Setting an 'A' type variable this way requires the actual variable name in VariableRequest::variableName – using just an ID returns E_INVALIDARG.
    (Other settable variable types don't have any associated ID anyway, so this is not an issue.)
  • For any variable type other than 'L', a Unit can only be specified as a string (in VariableRequest::unitName), not an ID. Using only an ID will not cause an error, but the unit will not be included in the generated RPN code.
    For 'L' variable types, if both a name and ID are provided, the numeric ID is used insted of the name (this avoids a lookup on the server side).
Parameters
variableSee VariableRequest documentation for descriptions of the individual fields.
valueThe numeric value to set.
Returns
S_OK on success, E_INVALIDARG on parameter validation errors, E_NOT_CONNECTED if not connected to server, or E_FAIL on general failure (unlikely).
See also
Enums::CommandId::Set

Definition at line 1726 of file WASimClient.cpp.

◆ setVariable() [2/2]

HRESULT WASimCommander::Client::WASimClient::setVariable ( const VariableRequest variable,
const std::string &  stringValue 
)

This is an overloaded method. This version allows setting an 'A' type (SimVar) variable to a string value. Only 'A' type variables can be set this way.
Since there is actually no direct way to set string-type values from WASM code, this is just a conveneince method and simply invokes SimConnect to do the work. On first use with a new variable name it will set up a mapping of the name to an internally-assigned ID (calling SimConnect_AddToDataDefinition()) and cache that mapping. Then on subsequent invocations on the same variable the mapped ID will be used directly. The mappings are invalidated when disconnecting from the simulator.

Definition at line 1730 of file WASimClient.cpp.

◆ setLocalVariable()

HRESULT WASimCommander::Client::WASimClient::setLocalVariable ( const std::string &  variableName,
const double  value,
const std::string &  unitName = std::string() 
)

A convenience version of setVariable() for Local variable types. Equivalent to setVariable(VariableRequest(variableName, false, unitName), value). See setVariable() and VariableRequest for details.

Parameters
variableNameName of the local variable.
valueThe value to set.
unitNameOptional unit specifier to use. Most Local vars do not specify a unit and default to a generic "number" type.
Returns
S_OK on success, E_INVALIDARG on parameter validation errors, E_NOT_CONNECTED if not connected to server, or E_FAIL on general failure (unlikely).
See also
Enums::CommandId::Set

Definition at line 1734 of file WASimClient.cpp.

◆ setOrCreateLocalVariable()

HRESULT WASimCommander::Client::WASimClient::setOrCreateLocalVariable ( const std::string &  variableName,
const double  value,
const std::string &  unitName = std::string() 
)

Set a Local Variable value by variable name, creating it first if it does not already exist. This first calls the register_named_variable() Gauge API function to get the ID from the name, which creates the variable if it doesn't exist. The returned ID (new or existing) is then used to set the value. Use the lookup() method to check for the existence of a variable name. Equivalent to setVariable(VariableRequest(variableName, true, unitName), value). See setVariable() and VariableRequest for details.

Parameters
variableNameName of the local variable.
valueThe value to set. Becomes the intial value if the variable is created.
unitNameOptional unit specifier to use. Most Local vars do not specify a unit and default to a generic "number" type.
Returns
S_OK on success, E_INVALIDARG on parameter validation errors, E_NOT_CONNECTED if not connected to server, or E_FAIL on general failure (unlikely).
See also
Enums::CommandId::SetCreate

Definition at line 1738 of file WASimClient.cpp.

◆ setSimVarVariable() [1/4]

HRESULT WASimCommander::Client::WASimClient::setSimVarVariable ( const std::string &  variableName,
const std::string &  unitName,
double  value 
)
inline

Sets a numeric value on an 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to setVariable(VariableRequest(variableName, unitName), value). See setVariable() and VariableRequest for details.
Note that variableName can optionally contain an index after a colon (eg. VAR NAME:1), or the setSimVarVariable(const string& name, uint8_t index, const string& unit, double value) overload could be used to provide the index separately.

Since
v1.3.0

Definition at line 262 of file WASimClient.h.

◆ setSimVarVariable() [2/4]

HRESULT WASimCommander::Client::WASimClient::setSimVarVariable ( const std::string &  variableName,
uint8_t  simVarIndex,
const std::string &  unitName,
double  value 
)
inline

Sets a numeric value on an indexed 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to setVariable(VariableRequest(variableName, unitName, simVarIndex), value). See setVariable() and VariableRequest for details.

Since
v1.3.0

Definition at line 266 of file WASimClient.h.

◆ setSimVarVariable() [3/4]

HRESULT WASimCommander::Client::WASimClient::setSimVarVariable ( const std::string &  variableName,
const std::string &  stringValue 
)
inline

Sets a string value on an 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to ‘setVariable(VariableRequest('A’, variableName), stringValue). SeesetVariable(const VariableRequest &, const std::string &)` for details.

Since
v1.3.0

Definition at line 270 of file WASimClient.h.

◆ setSimVarVariable() [4/4]

HRESULT WASimCommander::Client::WASimClient::setSimVarVariable ( const std::string &  variableName,
uint8_t  index,
const std::string &  stringValue 
)
inline

Sets a string value on an indexed 'A' (aka "SimVar" / "Simulator Variable") type variable.
This is a convenience version of setVariable(), equivalent to setVariable(VariableRequest(variableName, {}, index), stringValue). See setVariable(const VariableRequest &, const std::string &) for details.

Since
v1.3.0

Definition at line 274 of file WASimClient.h.

◆ saveDataRequest()

HRESULT WASimCommander::Client::WASimClient::saveDataRequest ( const DataRequest request,
bool  async = false 
)

Add a new WASimCommander::DataRequest for a variable or calculated result, or update an existing data request with the same DataRequest::requestId. Data changes (updates) are delivered asynchronously via the callback function set with setDataCallback(), which then passes a DataRequestRecord structure as the callback argument (this provides both a reference to the original DataRequest registered here, as well as result data).

Parameters
requestThe WASimCommander::DataRequest structure to process. See WASimCommander::DataRequest documentation for details of the structure members.
asyncSet to false (default) to wait for an Ack/Nak response from the server before returning from this method, or true to return without waiting for a response. See return values and the Note below for more details.
Returns
S_OK on success, E_INVALIDARG if there is a problem with the DataRequest contents.
If currently connected to the server and async is false, may also return E_FAIL if the server returned Nak response, or E_TIMEOUT on general server communication failure.
Note
If currently connected to the server and the async param is false, this method will block until either the Server responds or the timeout has expired (see defaultTimeout()). If the client is not currently connected to the server, the request is queued until the next connection is established (and this method is non-blocking regardless of async argument).
Tracking async calls
To track the status of an async request, set a callback function with setCommandResultCallback(). The server should respond with an Enums::CommandId::Ack or Enums::CommandId::Nak Command where the uData value is Enums::CommandId::Subscribe and the Command::token will be the requestId value from the given request struct.
See also
DataRequest Enums::CommandId::Subscribe, removeDataRequest(), updateDataRequest(), setDataCallback(), DataRequestRecord

Definition at line 1746 of file WASimClient.cpp.

◆ removeDataRequest()

HRESULT WASimCommander::Client::WASimClient::removeDataRequest ( const uint32_t  requestId)

Remove a previously-added DataRequest. This clears the subscription and any tracking/meta data from both server and client sides. Using this method is effectively the same as calling dataRequest() with a DataRequest of type RequestType::None.

Parameters
requestIdID of the request to remove.
Returns
S_OK on success, E_FAIL if the original request wasn't found.
Note
If the subscription data may be needed again in the future, it would be more efficient to edit the request (using saveDataRequest()) and suspend updates by setting the DataRequest::period to UpdatePeriod::Never. To resume updates change the period again.
See also
DataRequest, Enums::CommandId::Subscribe, saveDataRequest(), updateDataRequest()

Definition at line 1750 of file WASimClient.cpp.

◆ updateDataRequest()

HRESULT WASimCommander::Client::WASimClient::updateDataRequest ( uint32_t  requestId)

Trigger a data update on a previously-added DataRequest. Designed to refresh data on subscriptions with update periods of UpdatePeriod::Never or UpdatePeriod::Once, though it can be used with any subscription. Using this update method also skips any equality checks on the server side (though any delta epsilon value remains in effect on client side).

Parameters
requestIdThe ID of a previously added DataRequest.
Returns
S_OK on success, E_FAIL if the original request wasn't found,.
See also
Enums::CommandId::Update, saveDataRequest(), removeDataRequest()

Definition at line 1754 of file WASimClient.cpp.

◆ dataRequest()

DataRequestRecord WASimCommander::Client::WASimClient::dataRequest ( uint32_t  requestId) const

Returns a copy of a DataRequestRecord which has been previously added. If the request with the given requestId doesn't exist, an invalid DataRequestRecord is returned which has the members DataRequest::requestId set to -1, DataRequest::valueSize set to 0, and DataRequest::requestType set to RequestType::None.

Definition at line 1761 of file WASimClient.cpp.

◆ dataRequests()

vector< DataRequestRecord > WASimCommander::Client::WASimClient::dataRequests ( ) const

Returns a list of all data requests which have been added to the Client so far. (These are returned by copy operation, so for a long list it may get "expensive.")

Definition at line 1772 of file WASimClient.cpp.

◆ dataRequestIdsList()

vector< uint32_t > WASimCommander::Client::WASimClient::dataRequestIdsList ( ) const

Returns a list of all DataRequest::requestIds which have been added to the Client so far.

Definition at line 1784 of file WASimClient.cpp.

◆ setDataRequestsPaused()

HRESULT WASimCommander::Client::WASimClient::setDataRequestsPaused ( bool  paused) const

Enables or disables all data request subscription updates at the same time. Use this to temporarily suspend value update checks when they are not needed, but may be again in the future. This is a lot more efficient than disconnecting and re-connecting to the server, since all the data requests need to be re-created upon every new connection (similar to SimConnect itself).

Since v1.2
This method can be called while not connected to the server. In this case the setting is saved and sent to the server upon next connection, before sending any data request subscriptions. This way updates could be suspended upon initial connection, then re-enabled when the data is actually needed.
Returns
S_OK on success; If currently connected to the server, may also return E_TIMEOUT on general server communication failure.

Definition at line 1796 of file WASimClient.cpp.

◆ registerEvent()

HRESULT WASimCommander::Client::WASimClient::registerEvent ( const RegisteredEvent eventData)

Register a reusable event which executes a pre-set RPN calculator code string. The code is pre-compiled and stored on the server for quicker execution. The event can have an optional custom name for direct use with any SimConnect client. Registered events can also be triggered by using the transmitEvent() method. If the server is not currently connected, the event registration will be queued and sent next time a connection is established.

Returns
S_OK on success, E_INVALIDARG if the resulting code string is too long or if trying to change the name of an already registered event.
See also
RegisteredEvent, Enums::CommandId::Register, removeEvent(), transmitEvent()

Definition at line 1811 of file WASimClient.cpp.

◆ removeEvent()

HRESULT WASimCommander::Client::WASimClient::removeEvent ( uint32_t  eventId)

Remove an event previously registered with registerEvent() method. This is effectively the same as calling registerEvent() with an empty code parameter. If the server is not currently connected, the removal request will be queued and sent next time a connection is established.

Parameters
eventIdID of the previously registered event.
Returns
S_OK on success, E_INVALIDARG if the eventId wasn't found.
See also
Enums::CommandId::Register, registerEvent(), transmitEvent()

Definition at line 1846 of file WASimClient.cpp.

◆ transmitEvent()

HRESULT WASimCommander::Client::WASimClient::transmitEvent ( uint32_t  eventId)

Trigger an event previously registered with registerEvent(). This is a more direct alternative to triggering events by name via SimConnect.

Parameters
eventIdID of the previously registered event. If the event hasn't been registerd, the server will log a warning but otherwise nothing will happen.
Returns
S_OK on success, E_FAIL on general failure (unlikely), E_NOT_CONNECTED if not connected to server.
See also
Enums::CommandId::Transmit, registerEvent(), removeEvent()

Definition at line 1866 of file WASimClient.cpp.

◆ registeredEvent()

RegisteredEvent WASimCommander::Client::WASimClient::registeredEvent ( uint32_t  eventId)

Returns a copy of a RegisteredEvent which has been previously added with registerEvent(). If the event with the given eventId doesn't exist, an invalid RegisteredEvent is returned which has the members RegisteredEvent::eventId set to -1, and RegisteredEvent::code and RegisteredEvent::name both empty.

Definition at line 1870 of file WASimClient.cpp.

◆ registeredEvents()

vector< RegisteredEvent > WASimCommander::Client::WASimClient::registeredEvents ( ) const

Returns a list of all registered events which have been added to the Client with registerEvent(). The list members are created by copy.

Definition at line 1879 of file WASimClient.cpp.

◆ sendKeyEvent() [1/2]

HRESULT WASimCommander::Client::WASimClient::sendKeyEvent ( uint32_t  keyEventId,
uint32_t  v1 = 0,
uint32_t  v2 = 0,
uint32_t  v3 = 0,
uint32_t  v4 = 0,
uint32_t  v5 = 0 
) const

Can be used to trigger standard Simulator "Key Events" as well as "custom" Gauge API/SimConnect events. Up to 5 optional values can be passed onto the event handler. This provides functionality similar to the Gauge API function trigger_key_event_EX1() and SimConnect_TransmitClientEvent[_EX1()].

Standard Key Event IDs can be found in the SimConnect SDK header file 'MSFS/Legacy/gauges.h' in the form of KEY_* macro values, and event names can also be resolved to IDs programmatically using the lookup() method. No preliminary setup is required to trigger these events, but a full connection to WASimModule ("Server") is needed. These are triggered on the simulator side using trigger_key_event_EX1() function calls.

Custom Events for which a numeric ID is already known (typically in the Gauge API THIRD_PARTY_EVENT_ID_MIN/THIRD_PARTY_EVENT_ID_MAX ID range) can also be triggered directly as with standard events. These types of events are also passed directly to trigger_key_event_EX1().

Named Custom Events, for which an ID is not known or predefined, must first be registered with registerCustomKeyEvent(), which creates and maps (and optionally returns) a unique ID corresponding to the custom event name. An active simulator (SimConnect) connection is required to trigger these types of events. They are invoked via SimConnect_TransmitClientEvent[_EX1()] method directly from this client (this is actually just a convenience for the WASimClient user to avoid needing a separate SimConnect session). Which actual SimConnect function is used depends on how the custom event was registered (default is to use the newer "_EX1" version which allows up to 5 event values).
See docs for registerCustomKeyEvent() for further details on using custom simulator events.

Parameters
keyEventIdNumeric ID of the Event to trigger.
v1,v2,v3,v4,v5Optional values to pass to the event handler. Defaults are all zeros.
Returns
S_OK on success, E_NOT_CONNECTED if not connected (server or sim, see above), E_TIMEOUT on server communication failure, or E_FAIL on unexpected SimConnect error.
Note
For Key Events triggered via trigger_key_event_EX1(), Server responds asynchronously with an Ack/Nak response to Enums::CommandId::SendKey command type; A 'Nak' means the event ID is clearly not valid (eg. zero), but otherwise the simulator provides no feedback about event execution (from their docs: "If the event requested is not appropriate, it will simply not happen.").

For custom named events, triggered via SimConnect_TransmitClientEvent[_EX1()], SimConnect may asynchronously send EXCEPTION type response messages if the ID isn't valid (likely because the event hasn't been successfully registered with registerCustomKeyEvent()). These messages are passed through to WASimClient's logging facilities at the Warning level. But again there is no actual confirmation that the event is going to do anything.
Since
v1.3.0 - Added ability to trigger custom named events.

Definition at line 1895 of file WASimClient.cpp.

◆ sendKeyEvent() [2/2]

HRESULT WASimCommander::Client::WASimClient::sendKeyEvent ( const std::string &  keyEventName,
uint32_t  v1 = 0,
uint32_t  v2 = 0,
uint32_t  v3 = 0,
uint32_t  v4 = 0,
uint32_t  v5 = 0 
)

This is an overloaded method. See sendKeyEvent(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) const for main details. This version allows triggering Key Events by name instead of an ID.

All simulator event names must be resolved, or mapped, to a numeric ID before they can be triggered (used). The first time this method is invoked with a particular event name, it tries to associate that name with an ID (based on the event name, as described below). If successful, the ID is cached, so subsequent calls to this method, with the same event name, will use the cached ID instead of trying to resolve the name again.

  • For standard Key Events, the name is resolved to an ID using the 'lookup()' method and the resulting ID (if valid) is cached for future uses. There must be an active server connection for this to work.
  • For custom events (names that contain a "." (period) or start with a "#"), the event is first registered using registerCustomKeyEvent() and the resulting ID is cached if that succeeds.
Parameters
keyEventNameName of the Event to trigger.
v1,v2,v3,v4,v5Optional values to pass to the event handler. Defaults are all zeros.
Returns
S_OK on success, E_INVALIDARG if event name could not be resolved to an ID, E_NOT_CONNECTED if not connected (server or sim, depending on event type), E_TIMEOUT on server communication failure, or E_FAIL on unexpected SimConnect error.
Note
The name-to-ID cache is kept as a simple std::unordered_map type, so if you have a better way to save the event IDs from lookup() or registerCustomKeyEvent(), use that instead, and call the more efficient sendKeyEvent(eventId, ...) overload directly.
Since
v1.3.0 - Added ability to trigger custom named events.

Definition at line 1907 of file WASimClient.cpp.

◆ registerCustomKeyEvent()

HRESULT WASimCommander::Client::WASimClient::registerCustomKeyEvent ( const std::string &  customEventName,
uint32_t *  puiCustomEventId = nullptr,
bool  useLegacyTransmit = false 
)

Register a "Custom Simulator [Key] Event" by providing an event name. The method optionally returns the generated event ID, which can later be used with sendKeyEvent() method instead of the event name. It can also be used to look up a previous registration's ID if the event name has already been registered.

Custom event names are mapped to internally-generated unique IDs using a standard SimConnect call to MapClientEventToSimEvent, which briefly describes custom event usage and name syntax in the EventName parameter description. This method serves a similar purpose (and in fact eventually calls that same SimConnect function).

The mappings must be re-established every time a new connection with SimConnect is made, which WASimClient takes care of automatically. If currently connected to the simulator, the event is immediately mapped, otherwise it will be mapped upon the next connection. An event registration can be removed with removeCustomKeyEvent() which will prevent any SimConnect mapping from being created upon the next connection.

Note that the custom event mapping/triggering feature is actually just a convenience for the WASimClient user and doesn't involve the usual Server interactions (WASimModule) at all.
.

Parameters
customEventNameName of the Event to register. The event name must contain a "." (period) or start with a "#", otherwise an E_INVALIDARG result is returned.
If an event with the same name has already been registered, the method returns S_OK and no further actions are performed (besides setting the optional puiCustomEventId pointer value, see below).
puiCustomEventIdOptional pointer to 32-bit unsigned integer variable to return the generated event ID. This ID can be used to trigger the event later using sendKeyEvent() (which is more efficient than using the event name each time). The ID will always be unique per given event name, and is always equal to or greater than the Client::CUSTOM_KEY_EVENT_ID_MIN constant value.
The pointer's value will be populated even if the event name was already registered (with the result of the previously generated ID).
useLegacyTransmitOptional, default false. Boolean value indicating that the deprecated SimConnect_TransmitClientEvent() function should be used to trigger the event instead of the newer SimConnect_TransmitClientEvent_EX1(). This may be necessary to support models which haven't updated to the newer version of the event handler. Note that the old TransmitClientEvent() function only supports sending 1 event value (vs. 5 for the "_EX1" version).
To re-register the same event name but with a different value for useLegacyTransmit parameter, first remove the initial registration with removeCustomKeyEvent() and then call this method again.
Returns
S_OK on success, E_INVALIDARG if the event name is invalid.
Since
v1.3.0

Definition at line 1946 of file WASimClient.cpp.

◆ removeCustomKeyEvent() [1/2]

HRESULT WASimCommander::Client::WASimClient::removeCustomKeyEvent ( const std::string &  customEventName)

Remove a Custom Event previously registered with registerCustomEvent() method using the event's name. This will prevent the custom event from being mapped next time the client connects to SimConnect.

Note
SimConnect provides no way to remove a registered Custom event. Any active SimConnect mapping will remain in effect until SimConnect is disconnected (and can still be invoked with the corresponding ID, but not by name).
Parameters
customEventNamefull name of the previously registered event. Must be the same name as used with registerCustomKeyEvent().
Returns
S_OK on success, E_INVALIDARG if the eventId wasn't found.
Since
v1.3.0

Definition at line 1965 of file WASimClient.cpp.

◆ removeCustomKeyEvent() [2/2]

HRESULT WASimCommander::Client::WASimClient::removeCustomKeyEvent ( uint32_t  eventId)

This is an overloaded method. Same as removeCustomKeyEvent(const string &) but the event can be specified using the associated numeric event ID (originally returned from registerCustomKeyEvent()) instead of the name.

Parameters
eventIdID of the previously registered event.
Returns
S_OK on success, E_INVALIDARG if the eventId wasn't found.
Since
v1.3.0

Definition at line 1955 of file WASimClient.cpp.

◆ list()

HRESULT WASimCommander::Client::WASimClient::list ( WASimCommander::Enums::LookupItemType  itemsType = WASimCommander::Enums::LookupItemType::LocalVariable)

Send a request for a list update to the server. The results are delivered using the callback set in setListResultsCallback().

Parameters
itemsTypeThe type of thing to list. Supported types are local variables (Enums::LookupItemType::LocalVariable, default), subscribed Data Requests (Enums::LookupItemType::DataRequest), and Registered Events (Enums::LookupItemType::RegisteredEvent).
Returns
S_OK on success, E_INVALIDARG if the item type is not supported, E_NOT_CONNECTED if not connected to server.
Note
The list result callback is invoked from a new thread which delivers the results (Client::ListResult structure). Also check the ListResult::result HRESULT return code to be sure the list command completed successfully (which may be S_OK, E_FAIL if server returned Nak, or E_TIMEOUT if the list request did not complete (results may be empty or partial)).
See also
Enums::CommandId::List

Definition at line 1975 of file WASimClient.cpp.

◆ lookup()

HRESULT WASimCommander::Client::WASimClient::lookup ( WASimCommander::Enums::LookupItemType  itemType,
const std::string &  itemName,
int32_t *  piResult 
)

Request server-side lookup of an named item to find the corresponding numeric ID.

Parameters
itemTypeThe type of item to look up. A type of variable or a measurement unit. See the WASimCommander::LookupItemType documentation for details.
itemNameThe name of the thing to check for.
piResultPointer to 32-bit signed integer variable to hold the result.
Returns
S_OK on success, E_FAIL if server returns a Nak response (typically means the item name wasn't found), E_NOT_CONNECTED if not connected to server, E_TIMEOUT on server communication failure.
Note
This method blocks until either the Server responds or the timeout has expired.
See also
defaultTimeout(), setDefaultTimeout()

Definition at line 2005 of file WASimClient.cpp.

◆ sendCommand()

HRESULT WASimCommander::Client::WASimClient::sendCommand ( const Command command) const

Sends a command, in the form of a WASimCommander::Command structure, to the server for processing. The various command types and the data requirements for each are described in the WASimCommander::Enums::CommandId documentation. To receive command responses from the server, set a callback with setCommandResultCallback(), then check the results for a Command::token which matches the token set in the command you're sending here.

Returns
S_OK on success, E_NOT_CONNECTED if not connected to server, E_TIMEOUT on server communication failure.

Definition at line 2029 of file WASimClient.cpp.

◆ sendCommandWithResponse()

HRESULT WASimCommander::Client::WASimClient::sendCommandWithResponse ( const Command command,
Command response,
uint32_t  timeout = 0 
)

Sends a command, in the form of a WASimCommander::Command structure, to the server for processing and waits for a reply (an Ack/Nak response Command). The various command types and the data requirements for each are described in the WASimCommander::Enums::CommandId documentation.

Parameters
commandThe Command struct defining the command and associated data to send.
responsePointer to an initialised Command structure for storing the resulting response (a Command with a commandId of Ack or Nak), if any.
timeoutThe maximum time to wait for a response, in milliseconds. If 0 (default) then the default network timeout value is used (defaultTimeout(), setDefaultTimeout()).
Returns
S_OK on success, E_NOT_CONNECTED if not connected to server, E_TIMEOUT on server communication failure, or possibly E_FAIL on unknown error (check log for details).

Definition at line 2033 of file WASimClient.cpp.

◆ logLevel()

LogLevel WASimCommander::Client::WASimClient::logLevel ( WASimCommander::Enums::LogFacility  facility,
LogSource  source = LogSource::Client 
) const

Get the current minimum logging severity level for the specified facility and source.

See also
setLogLevel(), setLogCallback(), Enums::CommandId::Log
Parameters
facilityOne of WASimCommander::LogFacility enum flag values. This must be only one of the available flags, not a combination. The Remote facility is the one delivered via the log callback handler.
sourceOne of Client::LogSource enum values.
Returns
The current WASimCommander::LogLevel value, or LogLevel::None if the parameters were ivalid or the actual level is unknown (see Note below).
Note
The remote server logging level for File and Console facilities is unknown at Client startup. The returned values are only going to be correct if they were set by this instance of the Client (using setLogLevel()).

Definition at line 2053 of file WASimClient.cpp.

◆ setLogLevel()

void WASimCommander::Client::WASimClient::setLogLevel ( WASimCommander::Enums::LogLevel  level,
WASimCommander::Enums::LogFacility  facility = WASimCommander::Enums::LogFacility::Remote,
LogSource  source = LogSource::Client 
)

Set the current minimum logging severity level for the specified facility and source to level.

See also
logLevel(), setLogCallback(), Enums::CommandId::Log
Parameters
levelThe new minimum level. One of WASimCommander::LogLevel enum values. Use LogLevel::None to disable logging on the given faciliity/source.
facilityOne or more of WASimCommander::LogFacility enum flags. The LogFacility::Remote facility is the one delivered via the log callback handler.
sourceOne of Client::LogSource enum values.

Definition at line 2054 of file WASimClient.cpp.

◆ setClientEventCallback() [1/2]

void WASimCommander::Client::WASimClient::setClientEventCallback ( clientEventCallback_t  cb)

Sets a callback for Client event updates which indicate status changes. Pass a nullptr value to remove a previously set callback.
Usage:

client->setClientEventCallback(std::bind(&MyClass::onClientEvent, this, std::placeholders::_1));

This callback may be invoked from the main thread (where WASimClient was created), the dedicated "dispatch" thread the client maintains, or a temporary thread in one specific case when SimConnect sends a "Quit" command.

See also
ClientEventType, ClientEvent, WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 2070 of file WASimClient.cpp.

◆ setClientEventCallback() [2/2]

template<class Tcaller >
void WASimCommander::Client::WASimClient::setClientEventCallback ( void(__stdcall Tcaller::*)(const ClientEvent &)  member,
Tcaller *const  caller 
)
inline

Same as setClientEventCallback(clientEventCallback_t). Convenience for avoiding a std::bind expression.
Usage:

client->setClientEventCallback(&MyClass::onClientEvent, this);
See also
ClientEvent, WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 578 of file WASimClient.h.

◆ setListResultsCallback() [1/2]

void WASimCommander::Client::WASimClient::setListResultsCallback ( listResultsCallback_t  cb)

Sets a callback for list results arriving from the server. Pass a nullptr value to remove a previously set callback.
Usage:

client->setListResultsCallback(std::bind(&MyClass::onListResult, this, std::placeholders::_1));

This callback is invoked from temporary thread which accumulates incoming list results until the listing is complete (or times out). Currently, only one pending list request can be active at any time, though this may change in the future.

See also
ListResult, list(), Enums::CommandId::List, WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 2071 of file WASimClient.cpp.

◆ setListResultsCallback() [2/2]

template<class Tcaller >
void WASimCommander::Client::WASimClient::setListResultsCallback ( void(__stdcall Tcaller::*)(const ListResult &)  member,
Tcaller *const  caller 
)
inline

Same as setListResultsCallback(listResultsCallback_t). Convenience for avoiding a std::bind expression.
Usage:

client->setListResultsCallback(&MyClass::onListResult, this);
See also
list(), Enums::CommandId::List, WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 584 of file WASimClient.h.

◆ setDataCallback() [1/2]

void WASimCommander::Client::WASimClient::setDataCallback ( dataCallback_t  cb)

Sets a callback for value update data arriving from the server. Pass a nullptr value to remove a previously set callback.
Usage:

client->setDataCallback(std::bind(&MyClass::onDataResult, this, std::placeholders::_1));

This callback is invoked from the dedicated "dispatch" thread the client maintains.

See also
DataRequestRecord, saveDataRequest(), WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 2072 of file WASimClient.cpp.

◆ setDataCallback() [2/2]

template<class Tcaller >
void WASimCommander::Client::WASimClient::setDataCallback ( void(__stdcall Tcaller::*)(const DataRequestRecord &)  member,
Tcaller *const  caller 
)
inline

Same as setDataCallback(dataCallback_t). Convenience overload template for avoiding a std::bind expression.
Usage:

client->setDataCallback(&MyClass::onDataResult, this)
See also
dataCallback_t, DataRequestRecord, saveDataRequest(), WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 590 of file WASimClient.h.

◆ setLogCallback() [1/2]

void WASimCommander::Client::WASimClient::setLogCallback ( logCallback_t  cb)

Sets a callback for logging activity, both from the server and the client itself. Pass a nullptr value to remove a previously set callback.
Usage:

client->setLogCallback(std::bind(&MyClass::onLogMessage, this, std::placeholders::_1));

This callback may be invoked from either the main thread (where WASimClient was created), or the dedicated "dispatch" thread which the client maintains.

See also
setLogLevel(), WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 2073 of file WASimClient.cpp.

◆ setLogCallback() [2/2]

template<class Tcaller >
void WASimCommander::Client::WASimClient::setLogCallback ( void(__stdcall Tcaller::*)(const LogRecord &, LogSource member,
Tcaller *const  caller 
)
inline

Same as setLogCallback(logCallback_t). Convenience template for avoiding a std::bind expression.
Usage:

client->setLogCallback(&MyClass::onLogMessage, this)
See also
setLogLevel(), WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 596 of file WASimClient.h.

◆ setCommandResultCallback() [1/2]

void WASimCommander::Client::WASimClient::setCommandResultCallback ( commandCallback_t  cb)

Sets a callback for delivering command results returned by the server. Pass a nullptr value to remove a previously set callback. While some of the high-level Client API calls do return an immediate status or result, many of the server commands are sent asynchronously, in a fire-and-forget fashion. If you would like to be notified about all command responses, set this callback. The Command type delivered will have the Command::commandId of type CommandId::Ack or CommandId::Nak. The Command::uData member is set to the commandId of the original command being responded to. Other Command struct members may have other meanings, depending on the actual command being responded to. See documentation for WASimCommander::Enums::CommandId for details.
Usage:

client->setCommandResultCallback(std::bind(&MyClass::onCommandResult, this, std::placeholders::_1));

This callback is invoked from the dedicated "dispatch" thread the client maintains.

See also
Enums::CommandId, WASimCommander::Command, WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 2074 of file WASimClient.cpp.

◆ setCommandResultCallback() [2/2]

template<class Tcaller >
void WASimCommander::Client::WASimClient::setCommandResultCallback ( void(__stdcall Tcaller::*)(const Command &)  member,
Tcaller *const  caller 
)
inline

Same as setCommandResultCallback(commandCallback_t). Convenience overload template for avoiding a std::bind expression.
Usage:

client->setCommandResultCallback(&MyClass::onCommandResult, this);
See also
setCommandResultCallback(commandCallback_t), WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 602 of file WASimClient.h.

◆ setResponseCallback() [1/2]

void WASimCommander::Client::WASimClient::setResponseCallback ( commandCallback_t  cb)

Sets a callback for delivering response commands sent to this client by the server module. Note that the server may also initiate a few types of commands (not in response to client commands) such as Ping, List, and Disconnect. In contrast to setCommandResultCallback(commandCallback_t), this one will report on all commands from the server, not just Ack/Nak. This callback is meant for low-level API usage.
Usage:

client->setResponseCallback(std::bind(&MyClass::onServerResponse, this, std::placeholders::_1));

This callback is invoked from the dedicated "dispatch" thread the client maintains.

See also
sendServerCommand(), WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 2075 of file WASimClient.cpp.

◆ setResponseCallback() [2/2]

template<class Tcaller >
void WASimCommander::Client::WASimClient::setResponseCallback ( void(__stdcall Tcaller::*)(const Command &)  member,
Tcaller *const  caller 
)
inline

Same as setResponseCallback(commandCallback_t). Convenience overload template for avoiding a std::bind expression.
Usage:

client->setResponseCallback(&MyClass::onServerResponse, this);
See also
setResponseCallback(responseCallback_t), WSMCMND_CLIENT_USE_CONCURRENT_CALLBACKS

Definition at line 608 of file WASimClient.h.


The documentation for this class was generated from the following files: