WebSocket
ws
X-Plane Web API access through Websocket API
Classes:
-
Request–Pythonic dataclass to host X-Plane Beacon data.
-
WS_RESPONSE_TYPE–X-Plane Websocket API response types
-
XPWebsocketAPI–X-Plane Websocket Client.
Request
dataclass
Request(
r_id: int,
body: dict,
ts: datetime,
ts_ack: datetime | None = None,
success: bool | None = None,
error: str | None = None,
)
Pythonic dataclass to host X-Plane Beacon data.
WS_RESPONSE_TYPE
flowchart TD
xpwebapi.ws.WS_RESPONSE_TYPE[WS_RESPONSE_TYPE]
click xpwebapi.ws.WS_RESPONSE_TYPE href "" "xpwebapi.ws.WS_RESPONSE_TYPE"
X-Plane Websocket API response types
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.ws.XPWebsocketAPI[XPWebsocketAPI]
xpwebapi.rest.XPRestAPI[XPRestAPI]
xpwebapi.api.API[API]
xpwebapi.rest.XPRestAPI --> xpwebapi.ws.XPWebsocketAPI
xpwebapi.api.API --> xpwebapi.rest.XPRestAPI
click xpwebapi.ws.XPWebsocketAPI href "" "xpwebapi.ws.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