Skip to content

WebSocket

ws

X-Plane Web API access through Websocket API

Classes:

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:

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 property writable

Connection status

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:

  • callback

    (Callable) –

    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:

  • connected

    (bool) –

    Whether beacon is received

  • beacon_data

    (BeaconData) –

    Beacon data

  • same_host

    (bool) –

    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

command(path: str) -> Command

Create Command with current API

Parameters:

  • path

    (str) –

    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

dataref(path: str, auto_save: bool = False) -> Dataref

Create Dataref with current API

Parameters:

  • path

    (str) –

    Dataref "path"

  • auto_save

    (bool, 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(command: Command, duration: float = 0.0) -> APIResult

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:

  • command

    (Command) –

    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:

  • obj

    (Dataref | Command) –

    Objet (Dataref or Command) to get the meta data for

  • force

    (bool, default: False ) –

    Force new fetch, do not read from cache (default: False)

Returns:

invalidate_caches

invalidate_caches()

Remove cache data

monitor_command_active

monitor_command_active(command: Command) -> bool | int

Starts monitoring single command for activity.

Parameters:

  • command

    (Command) –

    Command to monitor

Returns:

  • bool | int

    bool if fails

  • bool | int

    request id if succeeded

monitor_dataref

monitor_dataref(dataref: Dataref) -> bool | int

Starts monitoring single dataref.

[description]

Parameters:

  • dataref

    (Dataref) –

    Dataref to monitor

Returns:

  • bool | int

    bool if fails

  • bool | int

    request id if succeeded

monitor_datarefs

monitor_datarefs(
    datarefs: DatarefBatch, reason: str | None = None
) -> tuple[int | bool, dict]

Starts monitoring of supplied datarefs.

Sends a single WebSocket subscribe request for all newly monitored datarefs.

Parameters:

  • datarefs

    (DatarefBatch) –

    Mapping of {path: Dataref} or iterable of datarefs.

  • reason

    (str | 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_bulk_command_is_active_event(paths, on: bool = True) -> bool | int

Register multiple commands for active reporting.

Parameters:

  • paths

    (str) –

    Command paths

  • on

    (bool, 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_command_is_active_event(path: str, on: bool = True) -> bool | int

Register single command for active reporting.

Parameters:

  • path

    (str) –

    Command path

  • on

    (bool, default: True ) –

    True registers for active reporting, False unregisters.

Returns:

  • bool | int

    bool if fails

  • bool | int

    request id if succeeded

reload_caches

reload_caches(force: bool = False, save: bool = False)

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:

  • force

    (bool, default: False ) –

    Force reloading (default: False)

  • save

    (bool, 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: dict, mapping: dict = {}) -> int | bool

Send payload message (JSON) through Websocket

Parameters:

  • payload

    (dict) –

    JSON message

  • mapping

    (dict, 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:

  • path

    (str) –

    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:

  • path

    (str) –

    Command path

Returns:

  • bool | int

    bool if fails

  • bool | int

    request id if succeeded

set_command_is_active_with_duration

set_command_is_active_with_duration(path: str, duration: float = 0.0) -> bool | int

Execute command active with duration.

Parameters:

  • path

    (str) –

    Command path

  • duration

    (float, 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

set_command_is_active_without_duration(path: str, active: bool) -> bool | int

Execute command active with no duration

Parameters:

  • path

    (str) –

    Command path

  • active

    (bool) –

    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:

  • host

    (str) –

    Host name or IP address

  • port

    (int) –

    TCP port number for API

  • api

    (str) –

    API root path, starts with /.

  • api_version

    (str) –

    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

unmonitor_command_active(command: Command) -> bool | int

Stops monitoring single command for activity.

Parameters:

  • command

    (Command) –

    Command to monitor

Returns:

  • bool | int

    bool if fails

  • bool | int

    request id if succeeded

unmonitor_dataref

unmonitor_dataref(dataref: Dataref) -> bool | int

Stops monitoring single dataref.

[description]

Parameters:

  • dataref

    (Dataref) –

    Dataref to stop monitoring

Returns:

  • bool | int

    bool if fails

  • bool | int

    request id if succeeded

unmonitor_datarefs

unmonitor_datarefs(
    datarefs: DatarefBatch, reason: str | None = None
) -> tuple[int | bool, dict]

Stops monitoring supplied datarefs.

Sends a single WebSocket unsubscribe request for all datarefs whose monitor count reaches zero.

Parameters:

  • datarefs

    (DatarefBatch) –

    Mapping of {path: Dataref} or iterable of datarefs.

  • reason

    (str | 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

write_dataref(dataref: Dataref) -> APIResult

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:

  • dataref

    (Dataref) –

    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