Package
xpwebapi
Modules:
-
api–Abstract base classes and core classes like Dataref and Command.
-
async_rest–Asynchronous X-Plane Web API access through REST.
-
beacon–X-Plane UDP Beacon Monitor
-
capture_cli–Command-line entry point for strictly read-only X-Plane capture.
-
capture_events–Strict event, status, and version models for capture protocol version 1.
-
capture_output–Durable JSONL events, atomic status output, and source provenance.
-
capture_protocol–Strict version-1 request protocol for the read-only capture worker.
-
capture_runner–Bounded lifecycle, readiness, sampling, and cleanup for capture workers.
-
capture_transport–Deadline-bounded, read-only transport adapters for capture workers.
-
logging_config–Logging configuration helpers for xpwebapi.
-
read_only–Restricted raw-handle proxies for read-only API clients.
-
rest–X-Plane Web API access through REST API
-
retry–Retry helpers for transient X-Plane connection probes.
-
schemas–Installed JSON Schema resources for the capture protocol.
-
udp–X-Plane access through UDP messages
-
ws–X-Plane Web API access through Websocket API
Classes:
-
AsyncXPRestAPI–Opt-in asynchronous REST client for X-Plane Web API.
-
BeaconData–Pythonic dataclass to host X-Plane Beacon data.
-
Command–X-Plane Web API Command
-
DATAREF_DATATYPE–X-Plane API dataref types
-
Dataref–X-Plane Web API Dataref
-
JsonLogFormatter–Format log records as one JSON object per line.
-
LoggingConfig–Validated logging configuration.
-
XPBeaconMonitor–X-Plane «beacon» monitor.
-
XPRestAPI–XPlane REST API
-
XPUDPAPI–Get data from XPlane via network.
-
XPWebsocketAPI–X-Plane Websocket Client.
Functions:
-
configure_logging–Configure xpwebapi application and traffic logging explicitly.
-
write_logging_config–Write a starter JSON logging config file.
AsyncXPRestAPI
AsyncXPRestAPI(
host: str = "127.0.0.1",
port: int = 8086,
api: str = "/api",
api_version: str = "v1",
use_cache: bool = False,
retry_attempts: int = 1,
retry_backoff: float = 0.0,
retry_backoff_max: float = 5.0,
read_only: bool = False,
)
Opt-in asynchronous REST client for X-Plane Web API.
Methods:
-
aclose–Close the underlying async HTTP session.
-
capabilities–Fetch and cache API capabilities.
-
changed–If rounding applies, determine if value has changed.
-
command–Create a Command bound to this async API.
-
dataref–Create a Dataref bound to this async API.
-
dataref_value–Get dataref value through REST API.
-
execute_command–Execute command through REST API.
-
get_command_meta_by_id–Get cached command metadata by command identifier.
-
get_command_meta_by_name–Get cached command metadata by command path.
-
get_dataref_meta_by_id–Get cached dataref metadata by dataref identifier.
-
get_dataref_meta_by_name–Get cached dataref metadata by dataref name.
-
get_rest_meta–Get metadata from X-Plane through REST API for an object.
-
invalidate_caches–Remove cached metadata.
-
rest_api_reachable–Whether the REST API is reachable.
-
set_network–Set network and API parameters for connection.
-
set_roundings–Add rounding to simulator variable value change detection.
-
write_dataref–Write single dataref value through REST API.
Attributes:
-
connected(bool) –Whether the last async REST probe succeeded.
-
rest_url(str) –URL for the REST API.
-
status(CONNECTION_STATUS) –Connection status.
-
status_str(str) –Connection status as a string.
-
use_cache(bool) –Use cache for object metadata.
-
xp_version(str | None) –Returns reported X-Plane version from simulator.
connected
property
connected: bool
Whether the last async REST probe succeeded.
rest_url
property
rest_url: str
URL for the REST API.
status_str
property
status_str: str
Connection status as a string.
use_cache
property
writable
use_cache: bool
Use cache for object metadata.
xp_version
property
xp_version: str | None
Returns reported X-Plane version from simulator.
aclose
async
aclose() -> None
Close the underlying async HTTP session.
capabilities
async
capabilities() -> dict
Fetch and cache API capabilities.
changed
changed(dataref: str, value: Any) -> bool
If rounding applies, determine if value has changed.
dataref
dataref(path: str, auto_save: bool = False) -> Dataref
Create a Dataref bound to this async API.
dataref_value
async
dataref_value(
dataref: Dataref, raw: bool = False, no_decode: bool = False
) -> DatarefReadResult
Get dataref value through REST API.
execute_command
async
execute_command(command: Command, duration: float = 0.0) -> bool
Execute command through REST API.
get_command_meta_by_id
get_command_meta_by_id(ident: int) -> CommandMeta | None
Get cached command metadata by command identifier.
get_command_meta_by_name
get_command_meta_by_name(path: str) -> CommandMeta | None
Get cached command metadata by command path.
get_dataref_meta_by_id
get_dataref_meta_by_id(ident: int) -> DatarefMeta | None
Get cached dataref metadata by dataref identifier.
get_dataref_meta_by_name
get_dataref_meta_by_name(path: str) -> DatarefMeta | None
Get cached dataref metadata by dataref name.
get_rest_meta
async
get_rest_meta(
obj: Dataref | Command, force: bool = False
) -> DatarefMeta | CommandMeta | None
Get metadata from X-Plane through REST API for an object.
invalidate_caches
invalidate_caches() -> None
Remove cached metadata.
rest_api_reachable
async
rest_api_reachable() -> bool
Whether the REST API is reachable.
set_network
set_network(host: str, port: int, api: str, api_version: str) -> bool
Set network and API parameters for connection.
set_roundings
set_roundings(roundings: dict[str, int]) -> None
Add rounding to simulator variable value change detection.
write_dataref
async
write_dataref(dataref: Dataref) -> bool
Write single dataref value through REST API.
BeaconData
dataclass
BeaconData(host: str, port: int, hostname: str, xplane_version: int, role: int)
Pythonic dataclass to host X-Plane Beacon data.
Command
Command(api: API, path: str, duration: float = 0.0)
X-Plane Web API Command
Methods:
-
execute–Execute command through API supplied at creation
-
monitor–Monitor command activation through Websocket API
-
unmonitor–Suppress monitor command activation through Websocket API
Attributes:
-
description(str | None) –Get command description as provided by X-Plane
-
ident(int | None) –Get command identifier meta data
-
meta(CommandMeta | None) –Meta data of command
-
valid(bool) –Returns whether meta data for command was acquired sucessfully to carry on operations on it
description
property
description: str | None
Get command description as provided by X-Plane
ident
property
ident: int | None
Get command identifier meta data
valid
property
valid: bool
Returns whether meta data for command was acquired sucessfully to carry on operations on it
execute
execute(duration: float = 0.0) -> APIResult
Execute command through API supplied at creation
monitor
monitor(on: bool = True) -> bool
Monitor command activation through Websocket API
unmonitor
unmonitor() -> bool
Suppress monitor command activation through Websocket API
DATAREF_DATATYPE
flowchart TD
xpwebapi.DATAREF_DATATYPE[DATAREF_DATATYPE]
click xpwebapi.DATAREF_DATATYPE href "" "xpwebapi.DATAREF_DATATYPE"
X-Plane API dataref types
Dataref
Dataref(path: str, api: API, auto_save: bool = False)
X-Plane Web API Dataref
Methods:
-
dec_monitor–Unregister dataref from monitoring
-
get_string_value–Decodes current dataref value and replaces it with the decoded string value
-
get_value–Return current value of dataref in local application
-
inc_monitor–Register dataref for monitoring
-
monitor–Monitor dataref value change
-
set_string_value–Set dataref value to base64 encoded representation of string value
-
unmonitor–Unmonitor dataref value change
-
write–Write new value to X-Plane through REST API
Attributes:
-
ident(int | None) –Get dataref identifier meta data
-
is_array(bool) –Whether dataref is an array
-
is_monitored–Whether dataref is currently monitored
-
is_writable(bool) –Whether dataref can be written back to X-Plane
-
last_updated(datetime) –Returns last time of modification
-
meta(DatarefMeta | None) –Meta data of dataref
-
monitored_count(int) –How many times dataref is monitored
-
valid(bool) –Returns whether meta data for dataref was acquired sucessfully to carry on operations on it
-
value–Return current value of dataref in local application
-
value_type(str | None) –Get dataref value type meta data
ident
property
ident: int | None
Get dataref identifier meta data
is_array
property
is_array: bool
Whether dataref is an array
is_monitored
property
is_monitored
Whether dataref is currently monitored
is_writable
property
is_writable: bool
Whether dataref can be written back to X-Plane
last_updated
property
last_updated: datetime
Returns last time of modification
monitored_count
property
monitored_count: int
How many times dataref is monitored
valid
property
valid: bool
Returns whether meta data for dataref was acquired sucessfully to carry on operations on it
value
property
writable
value
Return current value of dataref in local application
value_type
property
value_type: str | None
Get dataref value type meta data
Valid value types are
- INTEGER = "int"
- FLOAT = "float"
- DOUBLE = "double"
- INTARRAY = "int_array"
- FLOATARRAY = "float_array"
- DATA = "data"
dec_monitor
dec_monitor() -> bool
Unregister dataref from monitoring
Returns bool: Whether dataref is still monitored after this unmonitoring() call
get_string_value
get_string_value(encoding: str) -> str | None
Decodes current dataref value and replaces it with the decoded string value
Parameters:
-
(encodingstr) –Encoding used to decode the bytes value.
Returns:
-
str | None–
get_value
get_value()
Return current value of dataref in local application
inc_monitor
inc_monitor()
Register dataref for monitoring
monitor
monitor() -> bool
Monitor dataref value change
set_string_value
Set dataref value to base64 encoded representation of string value
[description]
Parameters:
-
(valuestr) –[description]
-
(encodingstr) –[description]
unmonitor
unmonitor() -> bool
Unmonitor dataref value change
write
write() -> APIResult
Write new value to X-Plane through REST API
Dataref value is saved locally and written to X-Plane when write() or save() is called.
JsonLogFormatter
flowchart TD
xpwebapi.JsonLogFormatter[JsonLogFormatter]
click xpwebapi.JsonLogFormatter href "" "xpwebapi.JsonLogFormatter"
Format log records as one JSON object per line.
LoggingConfig
flowchart TD
xpwebapi.LoggingConfig[LoggingConfig]
click xpwebapi.LoggingConfig href "" "xpwebapi.LoggingConfig"
Validated logging configuration.
XPBeaconMonitor
XPBeaconMonitor(
retry_attempts: int = 1, retry_backoff: float = 0.0, retry_backoff_max: float = 5.0
)
X-Plane «beacon» monitor.
Monitors X-Plane beacon which betrays X-Plane UDP port reachability. Beacon monitor listen for X-Plane beacon on UDP port. When beacon is detected, Beacon Monitor calls back a user-supplied function whenever the reachability status changes.
Attributes:
-
MCAST_GRP(str) –default 239.255.1.1
-
MCAST_PORT(int) –default 49707 (MCAST_PORT was 49000 for XPlane10)
-
BEACON_TIMEOUT(float) –default 3.0 seconds
-
MAX_WARNING(int) –After MAX_WARNING warnings of "no connection", stops reporting "no connection". Default 3.
-
BEACON_PROBING_TIMEOUT(float) –Times between attempts to reconnect to X-Plane when not connected (default 10 seconds)
-
WARN_FREQ(float) –Report absence of connection every WARN_FREQ seconds. Default 10 seconds.
-
socket(socket | None) –Socket to multicast listener
-
status(BEACON_MONITOR_STATUS) –Beacon monitor status
-
data(BeaconData | None) –BeaconData | None - Beacon data as broadcasted by X-Plane in its beacon. None if beacon is not received.
-
my_ips(list[str]) –List of this host IP addresses
-
_already_warned(bool) – -
_callback(set[Callable]) –(Callable | None):
-
should_not_connect(Event) – -
connect_thread(Event) –(threading.Thread | None):
Usage;
import xpwebapi
def callback(connected: bool, beacon_data: xpwebapi.BeaconData, same_host: bool):
print("reachable" if connected else "unreachable")
beacon = xpwebapi.beacon()
beacon.set_callback(callback)
beacon.start_monitor()
Methods:
-
callback–Execute all callback functions
-
get_beacon–Attempts to capture an X-Plane beacon using configured transient retries.
-
same_host–Attempt to determine if X-Plane is running on local host (where beacon monitor runs) or remote host
-
set_callback–Add callback function
-
start_monitor–Starts beacon monitor
-
stop_monitor–Terminates beacon monitor
consecutive_failures
property
consecutive_failures: int
Returns number of recent consecutive failures
This can be used to detect temporary failures. When X-Plane is extremely busy, it may not send a beacon, or beacon emission can be delayed.
X-Plane is up and running but no beacon has been detected. "Missing" a few detections in a row does not mean X-Plane is not running.
This consecutive_failures allows to wait for a few failures to detect X-Plane before concluding its unavailability.
receiving_beacon
property
receiving_beacon: bool
Returns whether beacon from X-Plane is periodically received
status
property
writable
status: BEACON_MONITOR_STATUS
Report beacon monitor status
returns:
BEACON_MONITOR_STATUS: Monitor status
status_str
property
status_str: str
Report beacon monitor status as a string
callback
callback(connected: bool, beacon_data: BeaconData | None, same_host: bool | None)
Execute all callback functions
Callback function prototype
callback(connected: bool, beacon_data: BeaconData | None, same_host: bool | None)
Connected is True is beacon is detected at regular interval, False otherwise
get_beacon
get_beacon(timeout: float = BEACON_TIMEOUT) -> BeaconData | None
Attempts to capture an X-Plane beacon using configured transient retries.
same_host
same_host() -> bool
Attempt to determine if X-Plane is running on local host (where beacon monitor runs) or remote host
set_callback
set_callback(callback: Callable | None = None)
Add callback function
Callback functions will be called whenever the status of the "connection" changes.
Parameters:
-
(callbackCallable, default:None) –Callback function Callback function prototype
callback(connected: bool, beacon_data: BeaconData | None, same_host: bool | None)
Connected is True is beacon is detected at regular interval, False otherwise
start_monitor
start_monitor()
Starts beacon monitor
stop_monitor
stop_monitor()
Terminates beacon monitor
XPRestAPI
XPRestAPI(
host: str = "127.0.0.1",
port: int = 8086,
api: str = "/api",
api_version: str = "v1",
use_cache: bool = False,
retry_attempts: int = 1,
retry_backoff: float = 0.0,
retry_backoff_max: float = 5.0,
pool_connections: bool = False,
max_connections: int | None = None,
max_keepalive_connections: int | None = None,
keepalive_expiry: float | None = None,
timeout: float | None = None,
read_only: bool = False,
)
flowchart TD
xpwebapi.XPRestAPI[XPRestAPI]
xpwebapi.api.API[API]
xpwebapi.api.API --> xpwebapi.XPRestAPI
click xpwebapi.XPRestAPI href "" "xpwebapi.XPRestAPI"
click xpwebapi.api.API href "" "xpwebapi.api.API"
XPlane REST API
Adds cache for datarefs and commands meta data.
There is no permanent connection to REST API. When needed, connection can be probed with XPRestAPI.connected which is True if API is reachable. Most API call test for reachability before issuing their request(s).
See Also
Methods:
-
beacon_callback–Minimal beacon callback function.
-
changed–If rounding applies, determine if value has changed according to its rounding.
-
close–Close the underlying HTTP session.
-
command–Create Command with current API
-
commands_meta–Get dataref meta data through REST API for all dataref supplied
-
dataref–Create Dataref with current API
-
dataref_meta–Get dataref meta data through REST API
-
dataref_value–Get dataref value through REST API
-
datarefs_meta–Get dataref meta data through REST API for all dataref supplied
-
execute_command–Executes Command through REST API
-
get_command_meta_by_id–Get command meta data by command identifier
-
get_command_meta_by_name–Get command meta data by command path
-
get_dataref_meta_by_id–Get dataref meta data by dataref identifier
-
get_dataref_meta_by_name–Get dataref meta data by dataref name
-
get_rest_meta–Get meta data from X-Plane through REST API for object.
-
invalidate_caches–Remove cache data
-
rebuild_dataref_ids–Rebuild dataref idenfier index
-
reload_caches–Reload meta data caches
-
set_api_version–Set API version
-
set_network–Set network and API parameters for connection
-
set_roundings–Add rounding to simulator variable value.
-
write_dataref–Write single dataref value through REST API
Attributes:
-
capabilities(dict) –Fetches API capabilties and caches it
-
connected(bool) –Whether API is reachable
-
rest_api_reachable(bool) –Whether API is reachable
-
rest_url(str) –URL for the REST API
-
status(CONNECTION_STATUS) –Connection status
-
status_str(str) –Connection status as a string
-
uptime(float) –Time X-Plane has been running in seconds since start
-
use_cache(bool) –Use cache for object meta data
-
use_rest(bool) –Should use REST API for some purpose
-
xp_version(str | None) –Returns reported X-Plane version from simulator
capabilities
property
capabilities: dict
Fetches API capabilties and caches it
connected
property
connected: bool
Whether API is reachable
API may not be reachable if
- X-Plane version before 12.1.4,
- X-Plane is not running
rest_api_reachable
property
rest_api_reachable: bool
Whether API is reachable
API may not be reachable if
- X-Plane version before 12.1.4,
- X-Plane is not running
rest_url
property
rest_url: str
URL for the REST API
status_str
property
status_str: str
Connection status as a string
uptime
property
uptime: float
Time X-Plane has been running in seconds since start
Value is fetched from simulator dataref sim/time/total_running_time_sec
use_cache
property
writable
use_cache: bool
Use cache for object meta data
use_rest
property
writable
use_rest: bool
Should use REST API for some purpose
xp_version
property
xp_version: str | None
Returns reported X-Plane version from simulator
beacon_callback
beacon_callback(connected: bool, beacon_data: 'BeaconData', same_host: bool)
Minimal beacon callback function.
Provided for convenience.
Parameters:
-
(connectedbool) –Whether beacon is received
-
(beacon_dataBeaconData) –Beacon data
-
(same_hostbool) –Whether beacon is issued from same host as host running the monitor
changed
changed(dataref, value) -> bool
If rounding applies, determine if value has changed according to its rounding.
close
close() -> None
Close the underlying HTTP session.
command
Create Command with current API
Parameters:
-
(pathstr) –Command "path"
Returns:
-
Command(Command) –Created command
commands_meta
commands_meta(
commands: list[Command],
fields: list[str] | str = "all",
start: int | None = None,
limit: int | None = None,
) -> list[CommandMeta]
Get dataref meta data through REST API for all dataref supplied
@todo: commands_meta(self, dataref, fields:list[str]|str = "all", start: int|None = None, limit: int|None = None) # fields={id, name, description, all}
dataref
Create Dataref with current API
Parameters:
-
(pathstr) –Dataref "path"
-
(auto_savebool, default:False) –Save dataref back to X-Plane if value has changed and writable (default:
False)
Returns:
-
Dataref(Dataref) –Created dataref
dataref_meta
dataref_meta(dataref, fields: list[str] | str = 'all') -> DatarefMeta | None
Get dataref meta data through REST API
@todo: dataref_meta(self, dataref, fields:list[str]|str = "all") # fields={id, name, value_type, all}
dataref_value
dataref_value(
dataref: Dataref, raw: bool = False, no_decode: bool = False
) -> DatarefReadResult
Get dataref value through REST API
Value is not stored or cached.
datarefs_meta
datarefs_meta(
datarefs: list[Dataref],
fields: list[str] | str = "all",
start: int | None = None,
limit: int | None = None,
) -> list[DatarefMeta]
Get dataref meta data through REST API for all dataref supplied
@todo: datarefs_meta(self, dataref, fields:list[str]|str = "all", start: int|None = None, limit: int|None = None) # fields={id, name, value_type, all}
execute_command
execute_command(command: Command, duration: float = 0.0) -> APIResult
Executes Command through REST API
Returns:
bool: success of operation
get_command_meta_by_id
get_command_meta_by_id(ident: int) -> CommandMeta | None
Get command meta data by command identifier
get_command_meta_by_name
get_command_meta_by_name(path: str) -> CommandMeta | None
Get command meta data by command path
get_dataref_meta_by_id
get_dataref_meta_by_id(ident: int) -> DatarefMeta | None
Get dataref meta data by dataref identifier
get_dataref_meta_by_name
get_dataref_meta_by_name(path: str) -> DatarefMeta | None
Get dataref meta data by dataref name
get_rest_meta
get_rest_meta(
obj: Dataref | Command, force: bool = False
) -> DatarefMeta | CommandMeta | None
Get meta data from X-Plane through REST API for object.
Fetches meta data and cache it unless force = True.
Parameters:
-
(objDataref | Command) –Objet (Dataref or Command) to get the meta data for
-
(forcebool, default:False) –Force new fetch, do not read from cache (default:
False)
Returns:
-
DatarefMeta | CommandMeta | None–DatarefMeta| CommandMeta: Meta data for object.
invalidate_caches
invalidate_caches()
Remove cache data
rebuild_dataref_ids
rebuild_dataref_ids()
Rebuild dataref idenfier index
reload_caches
Reload meta data caches
Must be performed regularly, if aircraft changed, etc.
Later, Laminar Research has plan for a notification of additing of datarefs
Parameters:
-
(forcebool, default:False) –Force reloading (default:
False) -
(savebool, default:False) –Save raw meta data in JSON formatted files (default:
False)
set_api_version
set_api_version(api_version: str | None = None)
Set API version
Version is often specified with a v# short string. If no version is supplied, try to take the latest version available. Version numbering is not formally specified, ordering is performed using natural sorting. (See natsort.)
set_network
set_network(host: str, port: int, api: str, api_version: str) -> bool
Set network and API parameters for connection
Parameters:
-
(hoststr) –Host name or IP address
-
(portint) –TCP port number for API
-
(apistr) –API root path, starts with /.
-
(api_versionstr) –API version string, starts with /, appended to api string to form full path to API.
Returns:
-
bool(bool) –True if some network parameter has changed
set_roundings
set_roundings(roundings)
Add rounding to simulator variable value. Rounding is applied to value before it is sent to callback function.
write_dataref
write_dataref(dataref: Dataref) -> APIResult
Write single dataref value through REST API
Returns:
bool: success of operation
XPUDPAPI
XPUDPAPI(**kwargs)
flowchart TD
xpwebapi.XPUDPAPI[XPUDPAPI]
xpwebapi.api.API[API]
xpwebapi.api.API --> xpwebapi.XPUDPAPI
click xpwebapi.XPUDPAPI href "" "xpwebapi.XPUDPAPI"
click xpwebapi.api.API href "" "xpwebapi.api.API"
Get data from XPlane via network. Use a class to implement RAI Pattern for the UDP socket.
Methods:
-
abort–Signal the listener before immediately closing its socket.
-
add_callback–Add callback function to set of callback functions
-
beacon_callback–Callback waits a little bit before shutting down websocket handler on beacon miss.
-
changed–If rounding applies, determine if value has changed according to its rounding.
-
close–Stop monitored datarefs and close the UDP socket.
-
command–Create Command with current API
-
dataref–Create Dataref with current API
-
dataref_value–Returns Dataref value from simulator
-
execute_callbacks–Execute list of callback functions, all with same arguments passed as keyword arguments
-
execute_command–Execute command
-
monitor_dataref–Starts monitoring single dataref.
-
read_monitored_dataref_values–Do a single read and populate dataref with values.
-
set_network–Set network and API parameters for connection
-
set_roundings–Add rounding to simulator variable value.
-
simple_connection_probe–Exeprimental
-
start–Start UDP monitoring
-
stop–Stop UDP monitoring
-
unmonitor_datarefs–Stops monitoring supplied datarefs.
-
write_dataref–Write Dataref value to X-Plane if Dataref is writable
Attributes:
-
connected(bool) –Whether X-Plane API is reachable through this API
-
rest_url(str) –URL for the REST API
-
status(CONNECTION_STATUS) –Connection status
-
status_str(str) –Connection status as a string
-
use_rest(bool) –Should use REST API for some purpose
connected
property
connected: bool
Whether X-Plane API is reachable through this API
rest_url
property
rest_url: str
URL for the REST API
status_str
property
status_str: str
Connection status as a string
use_rest
property
writable
use_rest: bool
Should use REST API for some purpose
abort
abort() -> None
Signal the listener before immediately closing its socket.
add_callback
add_callback(callback: Callable)
Add callback function to set of callback functions
Please note that in the case of UDP, callback is called for each value it received, whether the value has changed or not.
Parameters:
-
(callbackCallable) –Callback function
beacon_callback
beacon_callback(connected: bool, beacon_data: BeaconData, same_host: bool)
Callback waits a little bit before shutting down websocket handler on beacon miss. Starts or make sure it is running on beacon hit.
Parameters:
-
(connectedbool) –Whether beacon is received
-
(beacon_dataBeaconData) –Beacon data
-
(same_hostbool) –Whether beacon is issued from same host as host running the monitor
changed
changed(dataref, value) -> bool
If rounding applies, determine if value has changed according to its rounding.
close
close() -> None
Stop monitored datarefs and close the UDP socket.
command
Create Command with current API
Parameters:
-
(pathstr) –Command "path"
Returns:
-
Command(Command) –Created command
dataref
Create Dataref with current API
Parameters:
-
(pathstr) –Dataref "path"
-
(auto_savebool, default:False) –Save dataref back to X-Plane if value has changed and writable (default:
False)
Returns:
-
Dataref(Dataref) –Created dataref
dataref_value
Returns Dataref value from simulator
Parameters:
-
(datarefDataref) –Dataref to get the value from
Returns:
-
DatarefReadResult(DatarefReadResult) –Value of dataref.
execute_callbacks
execute_callbacks(**kwargs) -> bool
Execute list of callback functions, all with same arguments passed as keyword arguments
returns
bool: Whether error reported during execution
execute_command
Execute command
Parameters:
-
(commandCommand) –Command to execute
-
(durationfloat, default:0.0) –Duration of execution for long commands (default:
0.0)
Returns:
-
bool(bool) –[description]
monitor_dataref
Starts monitoring single dataref.
[description]
Parameters:
-
(datarefDataref) –Dataref to monitor
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
read_monitored_dataref_values
read_monitored_dataref_values() -> dict
Do a single read and populate dataref with values.
This function should be called at regular intervals to collect all requested datarefs. (A single read returns about 15 values.)
Returns:
-
dict(dict) –{path: value} for received datarefs so far.
Raises:
-
XPlaneTimeout–[description]
set_network
set_network(host: str, port: int, api: str, api_version: str) -> bool
Set network and API parameters for connection
Parameters:
-
(hoststr) –Host name or IP address
-
(portint) –TCP port number for API
-
(apistr) –API root path, starts with /.
-
(api_versionstr) –API version string, starts with /, appended to api string to form full path to API.
Returns:
-
bool(bool) –True if some network parameter has changed
set_roundings
set_roundings(roundings)
Add rounding to simulator variable value. Rounding is applied to value before it is sent to callback function.
simple_connection_probe
simple_connection_probe() -> bool
Exeprimental
Do we receive a UPD message within TIMEOUT seconds?
returns:
(bool) UPD message recieved
start
start(release: bool = True)
Start UDP monitoring
stop
stop(timeout_seconds: float | None = None)
Stop UDP monitoring
unmonitor_datarefs
Stops monitoring supplied datarefs.
[description]
Parameters:
-
(datarefsdict) –{path: Dataref} dictionary of datarefs
-
(reasonstr | None, default:None) –Documentation only string to identify call to function.
Returns:
-
tuple[int | bool, dict]–tuple[int | bool, dict]: [description]
XPWebsocketAPI
XPWebsocketAPI(
host: str = "127.0.0.1",
port: int = 8086,
api: str = "api",
api_version: str = "v2",
use_rest: bool = False,
retry_attempts: int = 1,
retry_backoff: float = 0.0,
retry_backoff_max: float = 5.0,
http_timeout: float | None = None,
open_timeout: float = 10.0,
close_timeout: float = 10.0,
read_only: bool = False,
)
flowchart TD
xpwebapi.XPWebsocketAPI[XPWebsocketAPI]
xpwebapi.rest.XPRestAPI[XPRestAPI]
xpwebapi.api.API[API]
xpwebapi.rest.XPRestAPI --> xpwebapi.XPWebsocketAPI
xpwebapi.api.API --> xpwebapi.rest.XPRestAPI
click xpwebapi.XPWebsocketAPI href "" "xpwebapi.XPWebsocketAPI"
click xpwebapi.rest.XPRestAPI href "" "xpwebapi.rest.XPRestAPI"
click xpwebapi.api.API href "" "xpwebapi.api.API"
X-Plane Websocket Client.
The XPWebsocketAPI is a client interface to X-Plane Web API, Websocket server.
The XPWebsocketAPI has a connection monitor (XPWebsocketAPI.connection_monitor) that can be started (XPWebsocketAPI.connect) and stopped (XPWebsocketAPI.disconnect). The monitor tests for REST API reachability, and if reachable, creates a Websocket. If the websocket exists and is opened, requests can be made through it and responses expected.
To handle responses, a receiver (XPWebsocketAPI.ws_listener) can be started (XPWebsocketAPI.start) and stopped (XPWebsocketAPI.stop) to process responses coming through the websocket.
See https://developer.x-plane.com/article/x-plane-web-api/#Websockets_API.
Methods:
-
abort_websocket–Immediately terminate the socket to interrupt a blocked operation.
-
add_callback–Add callback function to set of callback functions
-
beacon_callback–Callback waits a little bit before shutting down websocket handler on beacon miss.
-
changed–If rounding applies, determine if value has changed according to its rounding.
-
close–Disconnect the websocket monitor and close the HTTP session.
-
command–Create Command with current API
-
commands_meta–Get dataref meta data through REST API for all dataref supplied
-
connect–Starts connection to Websocket monitor
-
connect_websocket–Create and open Websocket connection if REST API is reachable
-
connection_monitor–Attempts to connect to X-Plane Websocket indefinitely until self.should_not_connect is set.
-
dataref–Create Dataref with current API
-
dataref_meta–Get dataref meta data through REST API
-
dataref_value–Get dataref value through REST API
-
datarefs_meta–Get dataref meta data through REST API for all dataref supplied
-
disconnect–Ends connection to Websocket monitor and closes websocket
-
disconnect_websocket–Gracefully closes Websocket connection
-
execute_callbacks–Execute list of callback functions, all with same arguments passed as keyword arguments
-
execute_command–Execute command in simulator.
-
get_command_meta_by_id–Get command meta data by command identifier
-
get_command_meta_by_name–Get command meta data by command path
-
get_dataref_meta_by_id–Get dataref meta data by dataref identifier
-
get_dataref_meta_by_name–Get dataref meta data by dataref name
-
get_rest_meta–Get meta data from X-Plane through REST API for object.
-
invalidate_caches–Remove cache data
-
monitor_command_active–Starts monitoring single command for activity.
-
monitor_dataref–Starts monitoring single dataref.
-
monitor_datarefs–Starts monitoring of supplied datarefs.
-
rebuild_dataref_ids–Rebuild dataref idenfier index
-
register_bulk_command_is_active_event–Register multiple commands for active reporting.
-
register_command_is_active_event–Register single command for active reporting.
-
reload_caches–Reload meta data caches
-
reset_connection–Reset Websocket connection
-
send–Send payload message (JSON) through Websocket
-
set_api_version–Set API version
-
set_command_is_active_false_without_duration–Execute command inactive with no duration
-
set_command_is_active_true_without_duration–Execute command active with no duration
-
set_command_is_active_with_duration–Execute command active with duration.
-
set_command_is_active_without_duration–Execute command active with no duration
-
set_dataref_value–Set single dataref value through Websocket
-
set_network–Set network and API parameters for connection
-
set_roundings–Add rounding to simulator variable value.
-
start–Start Websocket monitoring
-
stop–Stop Websocket monitoring
-
unmonitor_command_active–Stops monitoring single command for activity.
-
unmonitor_dataref–Stops monitoring single dataref.
-
unmonitor_datarefs–Stops monitoring supplied datarefs.
-
wait_connection–Waits that connection to Websocket opens.
-
write_dataref–Writes dataref value to simulator.
-
ws_listener–Read and decode websocket messages and calls back
Attributes:
-
capabilities(dict) –Fetches API capabilties and caches it
-
connected(bool) –Whether client software is connect to Websoket
-
next_req(int) –Provides request number for Websocket requests
-
rest_api_reachable(bool) –Whether API is reachable
-
rest_url(str) –URL for the REST API
-
status(CONNECTION_STATUS) –Connection status
-
status_str(str) –Connection status as a string
-
uptime(float) –Time X-Plane has been running in seconds since start
-
use_cache(bool) –Use cache for object meta data
-
ws_url(str) –URL for the Websocket API
-
xp_version(str | None) –Returns reported X-Plane version from simulator
capabilities
property
capabilities: dict
Fetches API capabilties and caches it
connected
property
connected: bool
Whether client software is connect to Websoket
next_req
property
next_req: int
Provides request number for Websocket requests
Current request number is available through attribute req_number.
rest_api_reachable
property
rest_api_reachable: bool
Whether API is reachable
API may not be reachable if
- X-Plane version before 12.1.4,
- X-Plane is not running
rest_url
property
rest_url: str
URL for the REST API
status_str
property
status_str: str
Connection status as a string
uptime
property
uptime: float
Time X-Plane has been running in seconds since start
Value is fetched from simulator dataref sim/time/total_running_time_sec
use_cache
property
writable
use_cache: bool
Use cache for object meta data
ws_url
property
ws_url: str
URL for the Websocket API
xp_version
property
xp_version: str | None
Returns reported X-Plane version from simulator
abort_websocket
abort_websocket() -> None
Immediately terminate the socket to interrupt a blocked operation.
add_callback
add_callback(cbtype: CALLBACK_TYPE, callback: Callable)
Add callback function to set of callback functions
Parameters:
-
(callbackCallable) –Callback function
beacon_callback
beacon_callback(connected: bool, beacon_data: BeaconData, same_host: bool)
Callback waits a little bit before shutting down websocket handler on beacon miss. Starts or make sure it is running on beacon hit.
Parameters:
-
(connectedbool) –Whether beacon is received
-
(beacon_dataBeaconData) –Beacon data
-
(same_hostbool) –Whether beacon is issued from same host as host running the monitor
changed
changed(dataref, value) -> bool
If rounding applies, determine if value has changed according to its rounding.
close
close() -> None
Disconnect the websocket monitor and close the HTTP session.
command
Create Command with current API
Parameters:
-
(pathstr) –Command "path"
Returns:
-
Command(Command) –Created command
commands_meta
commands_meta(
commands: list[Command],
fields: list[str] | str = "all",
start: int | None = None,
limit: int | None = None,
) -> list[CommandMeta]
Get dataref meta data through REST API for all dataref supplied
@todo: commands_meta(self, dataref, fields:list[str]|str = "all", start: int|None = None, limit: int|None = None) # fields={id, name, description, all}
connect
connect(reload_cache: bool = False)
Starts connection to Websocket monitor
connect_websocket
connect_websocket(timeout_resolver: WebsocketTimeoutResolver | None = None)
Create and open Websocket connection if REST API is reachable
connection_monitor
connection_monitor()
Attempts to connect to X-Plane Websocket indefinitely until self.should_not_connect is set. If a connection fails, drops, disappears, will try periodically to restore it.
dataref
Create Dataref with current API
Parameters:
-
(pathstr) –Dataref "path"
-
(auto_savebool, default:False) –Save dataref back to X-Plane if value has changed and writable (default:
False)
Returns:
-
Dataref(Dataref) –Created dataref
dataref_meta
dataref_meta(dataref, fields: list[str] | str = 'all') -> DatarefMeta | None
Get dataref meta data through REST API
@todo: dataref_meta(self, dataref, fields:list[str]|str = "all") # fields={id, name, value_type, all}
dataref_value
dataref_value(
dataref: Dataref, raw: bool = False, no_decode: bool = False
) -> DatarefReadResult
Get dataref value through REST API
Value is not stored or cached.
datarefs_meta
datarefs_meta(
datarefs: list[Dataref],
fields: list[str] | str = "all",
start: int | None = None,
limit: int | None = None,
) -> list[DatarefMeta]
Get dataref meta data through REST API for all dataref supplied
@todo: datarefs_meta(self, dataref, fields:list[str]|str = "all", start: int|None = None, limit: int|None = None) # fields={id, name, value_type, all}
disconnect
disconnect(timeout_seconds: float | None = None)
Ends connection to Websocket monitor and closes websocket
disconnect_websocket
disconnect_websocket(
silent: bool = False, timeout_resolver: WebsocketCloseTimeoutResolver | None = None
)
Gracefully closes Websocket connection
execute_callbacks
execute_callbacks(cbtype: CALLBACK_TYPE, **kwargs) -> bool
Execute list of callback functions, all with same arguments passed as keyword arguments
returns
bool: Whether error reported during execution
execute_command
Execute command in simulator.
Execution is done through REST API if use_rest is True, or Websocket API if use_rest is False and Websocket is opened.
Parameters:
-
(commandCommand) –Command to execute
Returns:
-
APIResult–bool if fails
-
APIResult–request id if succeeded
get_command_meta_by_id
get_command_meta_by_id(ident: int) -> CommandMeta | None
Get command meta data by command identifier
get_command_meta_by_name
get_command_meta_by_name(path: str) -> CommandMeta | None
Get command meta data by command path
get_dataref_meta_by_id
get_dataref_meta_by_id(ident: int) -> DatarefMeta | None
Get dataref meta data by dataref identifier
get_dataref_meta_by_name
get_dataref_meta_by_name(path: str) -> DatarefMeta | None
Get dataref meta data by dataref name
get_rest_meta
get_rest_meta(
obj: Dataref | Command, force: bool = False
) -> DatarefMeta | CommandMeta | None
Get meta data from X-Plane through REST API for object.
Fetches meta data and cache it unless force = True.
Parameters:
-
(objDataref | Command) –Objet (Dataref or Command) to get the meta data for
-
(forcebool, default:False) –Force new fetch, do not read from cache (default:
False)
Returns:
-
DatarefMeta | CommandMeta | None–DatarefMeta| CommandMeta: Meta data for object.
invalidate_caches
invalidate_caches()
Remove cache data
monitor_command_active
Starts monitoring single command for activity.
Parameters:
-
(commandCommand) –Command to monitor
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
monitor_dataref
Starts monitoring single dataref.
[description]
Parameters:
-
(datarefDataref) –Dataref to monitor
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
monitor_datarefs
Starts monitoring of supplied datarefs.
Sends a single WebSocket subscribe request for all newly monitored datarefs.
Parameters:
-
(datarefsDatarefBatch) –Mapping of {path: Dataref} or iterable of datarefs.
-
(reasonstr | None, default:None) –Documentation only string to identify call to function.
Returns:
-
tuple[int | bool, dict]–tuple[int | bool, dict]: Request id or False, and effective datarefs by name.
rebuild_dataref_ids
rebuild_dataref_ids()
Rebuild dataref idenfier index
register_bulk_command_is_active_event
Register multiple commands for active reporting.
Parameters:
-
(pathsstr) –Command paths
-
(onbool, default:True) –True registers for active reporting, False unregisters.
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
register_command_is_active_event
Register single command for active reporting.
Parameters:
-
(pathstr) –Command path
-
(onbool, default:True) –True registers for active reporting, False unregisters.
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
reload_caches
Reload meta data caches
Must be performed regularly, if aircraft changed, etc.
Later, Laminar Research has plan for a notification of additing of datarefs
Parameters:
-
(forcebool, default:False) –Force reloading (default:
False) -
(savebool, default:False) –Save raw meta data in JSON formatted files (default:
False)
reset_connection
reset_connection()
Reset Websocket connection
Stop existing Websocket connect and create a new one. Initialize and reload cache. If datarefs/commands identifier have changed, reassign new identifiers.
send
Send payload message (JSON) through Websocket
Parameters:
-
(payloaddict) –JSON message
-
(mappingdict, default:{}) –corresponding {idenfier: path} for printing/debugging
Returns:
-
int | bool–bool if fails
-
int | bool–request id if succeeded
set_api_version
set_api_version(api_version: str | None = None)
Set API version
Version is often specified with a v# short string. If no version is supplied, try to take the latest version available. Version numbering is not formally specified, ordering is performed using natural sorting. (See natsort.)
set_command_is_active_false_without_duration
set_command_is_active_false_without_duration(path) -> bool | int
Execute command inactive with no duration
Parameters:
-
(pathstr) –Command path
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
set_command_is_active_true_without_duration
set_command_is_active_true_without_duration(path) -> bool | int
Execute command active with no duration
Parameters:
-
(pathstr) –Command path
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
set_command_is_active_with_duration
Execute command active with duration.
Parameters:
-
(pathstr) –Command path
-
(durationfloat, default:0.0) –float: Duration, should be between 0.0 and 10.0.
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
set_command_is_active_without_duration
Execute command active with no duration
Parameters:
-
(pathstr) –Command path
-
(activebool) –Command active status.
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
set_dataref_value
set_dataref_value(path, value) -> bool | int
Set single dataref value through Websocket
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
set_network
set_network(host: str, port: int, api: str, api_version: str) -> bool
Set network and API parameters for connection
Parameters:
-
(hoststr) –Host name or IP address
-
(portint) –TCP port number for API
-
(apistr) –API root path, starts with /.
-
(api_versionstr) –API version string, starts with /, appended to api string to form full path to API.
Returns:
-
bool(bool) –True if some network parameter has changed
set_roundings
set_roundings(roundings)
Add rounding to simulator variable value. Rounding is applied to value before it is sent to callback function.
start
start(release: bool = True)
Start Websocket monitoring
stop
stop(timeout_seconds: float | None = None)
Stop Websocket monitoring
unmonitor_command_active
Stops monitoring single command for activity.
Parameters:
-
(commandCommand) –Command to monitor
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
unmonitor_dataref
Stops monitoring single dataref.
[description]
Parameters:
-
(datarefDataref) –Dataref to stop monitoring
Returns:
-
bool | int–bool if fails
-
bool | int–request id if succeeded
unmonitor_datarefs
Stops monitoring supplied datarefs.
Sends a single WebSocket unsubscribe request for all datarefs whose monitor count reaches zero.
Parameters:
-
(datarefsDatarefBatch) –Mapping of {path: Dataref} or iterable of datarefs.
-
(reasonstr | None, default:None) –Documentation only string to identify call to function.
Returns:
-
tuple[int | bool, dict]–tuple[int | bool, dict]: Request id or False, and effective datarefs by name.
wait_connection
wait_connection()
Waits that connection to Websocket opens.
write_dataref
Writes dataref value to simulator.
Writing is done through REST API if use_rest is True, or Websocket API if use_rest is False and Websocket is opened.
Parameters:
-
(datarefDataref) –Dataref write to simulator
Returns:
-
APIResult–bool if fails
-
APIResult–request id if succeeded
ws_listener
ws_listener()
Read and decode websocket messages and calls back
configure_logging
configure_logging(
config_file: str | Path | None = None,
*,
format: Literal["text", "json"] | None = None,
level: str | None = None,
traffic_level: str | None = None,
components: Mapping[str, str] | None = None,
stream: TextIO | None = None,
) -> LoggingConfig
Configure xpwebapi application and traffic logging explicitly.
write_logging_config
write_logging_config(
path: str | Path, *, config: LoggingConfig | None = None, overwrite: bool = False
) -> Path
Write a starter JSON logging config file.