xpwebapi
Modules:
api
Classes:
-
API
–API Abstract class with connection information
-
APIObjMeta
–Container for XP Web API models meta data
-
CONNECTION_STATUS
–Internal Beacon Connector status
-
Cache
–Stores dataref or command meta data in cache
-
Command
–X-Plane Web API Command
-
CommandMeta
–Container for XP Web API command meta data
-
DATAREF_DATATYPE
–X-Plane API dataref types
-
Dataref
–X-Plane Web API Dataref
-
DatarefMeta
–Container for XP Web API dataref meta data
-
XPLANE_API_VERSIONS
–API version number (string) versus X-Plane release number of that version
API
API(host: str, port: int, api: str, api_version: str)
API Abstract class with connection information
Methods:
-
beacon_callback
–Minimal beacon callback function.
-
command
–Create Command with current API
-
dataref
–Create Dataref with current API
-
dataref_value
–Returns Dataref value from simulator
-
execute
–Execute command
-
set_network
–Set network and API parameters for connection
-
write_dataref
–Write Dataref value to X-Plane if Dataref is writable
Attributes:
-
connected
(bool
) –Whether X-Plane API is reachable through this instance
-
rest_url
(str
) –URL for the REST API
-
status
(CONNECTION_STATUS
) –Should use REST API for some purpose
-
status_str
(str
) –Should use REST API for some purpose
-
use_rest
(bool
) –Should use REST API for some purpose
connected
abstractmethod
property
connected: bool
Whether X-Plane API is reachable through this instance
rest_url
property
rest_url: str
URL for the REST API
status_str
property
status_str: str
Should use REST API for some purpose
use_rest
property
writable
use_rest: bool
Should use REST API for some purpose
beacon_callback
beacon_callback(connected: bool, beacon_data: 'BeaconData', same_host: bool)
Minimal beacon callback function.
Provided for convenience.
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
command
Create Command with current API
Parameters:
-
path
str
) –Command "path"
Returns:
-
Command
(Command
) –Created command
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_value
abstractmethod
Returns Dataref value from simulator
Parameters:
-
dataref
Dataref
) –Dataref to get the value from
Returns:
-
DatarefValueType
–bool | str | int | float: Value of dataref
execute
abstractmethod
Execute command
Parameters:
-
command
Command
) –Command to execute
-
duration
float
, default:0.0
) –Duration of execution for long commands (default:
0.0
)
Returns:
-
bool
(bool | int
) –[description]
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
APIObjMeta
APIObjMeta(name: str, ident: int)
Container for XP Web API models meta data
CONNECTION_STATUS
Internal Beacon Connector status
Cache
Cache(api: API)
Stores dataref or command meta data in cache
Must be "refreshed" each time a new connection is created. Must be refreshed each time a new aircraft is loaded (for new datarefs, commands, etc.) reload_cache() is provided in xpwebapi.
There is no faster structure than a python dict() for (name,value) pair storage.
Methods:
-
equiv
–Return identifier/name equivalence, for diaply prupose in format 1234(path/to/object)
-
get
–Get meta data from cache by name
-
get_by_id
–Get meta data from cache by dataref or command identifier
-
get_by_name
–Get meta data from cache by name
-
load
–Load cache data
-
meta
–Create DatarefMeta or CommandMeta from dictionary of meta data returned by X-Plane Web API
-
save
–Saved cached data into file
Attributes:
count
property
count: int
Number of data in cache
has_data
property
has_data: bool
Cache contains data
equiv
equiv(ident) -> str | None
Return identifier/name equivalence, for diaply prupose in format 1234(path/to/object)
get_by_id
get_by_id(ident: int) -> DatarefMeta | CommandMeta | None
Get meta data from cache by dataref or command identifier
load
load(path)
Load cache data
meta
classmethod
meta(**kwargs) -> DatarefMeta | CommandMeta
Create DatarefMeta or CommandMeta from dictionary of meta data returned by X-Plane Web API
save
save(filename)
Saved cached data into file
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) -> bool
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
CommandMeta
CommandMeta(name: str, description: str, **kwargs)
Container for XP Web API command meta data
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
-
inc_monitor
–Register dataref for monitoring
-
monitor
–Monitor dataref value change
-
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
-
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
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
inc_monitor
inc_monitor()
Register dataref for monitoring
monitor
monitor() -> bool
Monitor dataref value change
unmonitor
unmonitor() -> bool
Unmonitor dataref value change
write
write() -> bool
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.
DatarefMeta
DatarefMeta(name: str, value_type: str, is_writable: bool, **kwargs)
Container for XP Web API dataref meta data
Methods:
-
append_index
–Add index to list of requested indices for dataref of type array of value
-
last_indices
–Get list of last requested indices
-
save_indices
–Keep a copy of indices as requested
Attributes:
-
is_array
(bool
) –Is dataref an array of values
is_array
property
is_array: bool
Is dataref an array of values
append_index
append_index(i)
Add index to list of requested indices for dataref of type array of value
Note from Web API instruction/manual: If you subscribed to certain indexes of the dataref, they’ll be sent in the index order but no sparse arrays will be sent. For example if you subscribed to indexes [1, 5, 7] you’ll get a 3 item array like [200, 200, 200], meaning you need to remember that the first item of that response corresponds to index 1, the second to index 5 and the third to index 7 of the dataref. This also means that if you subscribe to index 2 and later to index 0 you’ll get them as [0,2]. So bottom line is — keep it simple: either ask for a single index, or a range, or all; and if later your requirements change, unsubscribe, then subscribe again.
last_indices
last_indices() -> list
Get list of last requested indices
save_indices
save_indices()
Keep a copy of indices as requested
XPLANE_API_VERSIONS
API version number (string) versus X-Plane release number of that version
beacon
X-Plane UDP Beacon Monitor
Beacon Monitor listen to X-Plane UDP multicast port for a «beacon» emitted by X-Plane network API, if enabled. If no beacon is ever detected, either X-Plane is not running, or it is busy starting. If a beacon is detected, the message contains connection information to reach X-Plane instance through the network. Beacon also contains information about the version of X-Plane.
Attributes:
-
logger
(Logger
) –Loger for functions and classes in this file.
Classes:
-
BEACON_DATA
–X-Plane names of attributes inside its beacon.
-
BEACON_MONITOR_STATUS
–Internal status of Beacon Monitor.
-
BeaconData
–Pythonic dataclass to host X-Plane Beacon data.
-
XPBeaconMonitor
–X-Plane «beacon» monitor.
Functions:
-
list_my_ips
–Utility function that list most if not all IP addresses of this host.
BEACON_DATA
X-Plane names of attributes inside its beacon.
BEACON_MONITOR_STATUS
Internal status of Beacon Monitor.
- NOT_RUNNING - Beacon is not running
- RUNNING - Beacon monitor is running but no beacon detected
- DETECTING_BEACON - Beacon monitor is running and beacon detected
BeaconData
dataclass
BeaconData(host: str, port: int, hostname: str, xplane_version: int, role: int)
Pythonic dataclass to host X-Plane Beacon data.
XPBeaconMonitor
XPBeaconMonitor()
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
–Attemps to capture X-Plane beacon. Returns first occurence of beacon data encountered
-
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_str
property
status_str: str
Should use REST API for some purpose
callback
callback(connected: bool, beacon_data: BeaconData, same_host: bool)
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
Attemps to capture X-Plane beacon. Returns first occurence of beacon data encountered or None if no beacon was detected before timeout.
It returns the first beacon it receives.
BeaconData is a python dataclass with the following attributes:
class BeaconData:
host: str
port: int
hostname: str
xplane_version: int
role: int
Parameters:
-
timeout
float
, default:BEACON_TIMEOUT
) –Time to wait for receiving beacon (typical range 1 to 10 seconds.)
Returns:
-
BeaconData | None
–BeaconData | None: beacon data or None if no beacon received
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:
-
callback
Callable
, 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
list_my_ips
list_my_ips() -> List[str]
Utility function that list most if not all IP addresses of this host.
Returns:
-
List[str]
–List[str]: List of IP v4 addresses of this host on most, if not all interfaces (cable, wi-fi, bluetooth...)
rest
Classes:
REST_KW
REST requests and response JSON keywords.
XPRestAPI
XPRestAPI(host: str = '127.0.0.1', port: int = 8086, api: str = '/api', api_version: str = 'v1', use_cache: bool = False)
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.
-
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
–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
-
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
) –Should use REST API for some purpose
-
status_str
(str
) –Should use REST API for some purpose
-
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
Should use REST API for some purpose
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:
-
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
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}
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
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
execute(command: Command, duration: float = 0.0) -> bool | int
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:
-
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:
-
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:
-
force
bool
, default:False
) –Force reloading (default:
False
) -
save
bool
, 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:
-
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
write_dataref
write_dataref(dataref: Dataref) -> bool | int
Write single dataref value through REST API
Returns:
bool: success of operation
udp
Classes:
-
XPUDPAPI
–Get data from XPlane via network.
XPUDPAPI
XPUDPAPI(**kwargs)
Get data from XPlane via network. Use a class to implement RAI Pattern for the UDP socket.
Methods:
-
beacon_callback
–Minimal beacon callback function.
-
command
–Create Command with current API
-
dataref
–Create Dataref with current API
-
dataref_value
–Returns Dataref value from simulator
-
execute
–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
-
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
) –Should use REST API for some purpose
-
status_str
(str
) –Should use REST API for some purpose
-
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
Should use REST API for some purpose
use_rest
property
writable
use_rest: bool
Should use REST API for some purpose
beacon_callback
beacon_callback(connected: bool, beacon_data: 'BeaconData', same_host: bool)
Minimal beacon callback function.
Provided for convenience.
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
command
Create Command with current API
Parameters:
-
path
str
) –Command "path"
Returns:
-
Command
(Command
) –Created command
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_value
Returns Dataref value from simulator
Parameters:
-
dataref
Dataref
) –Dataref to get the value from
Returns:
-
DatarefValueType
–bool | str | int | float: Value of dataref
execute
Execute command
Parameters:
-
command
Command
) –Command to execute
-
duration
float
, default:0.0
) –Duration of execution for long commands (default:
0.0
)
Returns:
-
bool
(bool | int
) –[description]
monitor_dataref
Starts monitoring single dataref.
[description]
Parameters:
-
dataref
Dataref
) –Dataref to monitor
Returns:
-
bool | int
–bool if fails
-
bool | int
–request id if succeeded
read_monitored_dataref_values
read_monitored_dataref_values()
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
–{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:
-
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
unmonitor_datarefs
Stops monitoring supplied datarefs.
[description]
Parameters:
-
datarefs
dict
) –{path: Dataref} dictionary of datarefs
-
reason
str | None
, default:None
) –Documentation only string to identify call to function.
Returns:
-
Tuple[int | bool, Dict]
–Tuple[int | bool, Dict]: [description]
ws
Classes:
-
WS_RESPONSE_TYPE
–X-Plane Websocket API response types
-
XPWebsocketAPI
–X-Plane Websocket Client.
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)
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_receiver) 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:
-
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.
-
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
–Execute command in simulator.
-
execute_callbacks
–Execute list of callback functions, all with same arguments passed as keyword arguments
-
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
-
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
) –Should use REST API for some purpose
-
status_str
(str
) –Should use REST API for some purpose
-
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
Should use REST API for some purpose
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
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
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()
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:
-
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
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()
Ends connection to Websocket monitor and closes websocket
disconnect_websocket
disconnect_websocket(silent: bool = False)
Gracefully closes Websocket connection
execute
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:
-
bool | int
–bool if fails
-
bool | int
–request id if succeeded
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
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:
-
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:
-
command
Command
) –Command to monitor
Returns:
-
bool | int
–bool if fails
-
bool | int
–request id if succeeded
monitor_dataref
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
Starts monitoring of supplied datarefs.
[description]
Parameters:
-
datarefs
dict
) –{path: Dataref} dictionary of datarefs
-
reason
str | None
, default:None
) –Documentation only string to identify call to function.
Returns:
-
Tuple[int | bool, Dict]
–Tuple[int | bool, Dict]: [description]
rebuild_dataref_ids
rebuild_dataref_ids()
Rebuild dataref idenfier index
register_bulk_command_is_active_event
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 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 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 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
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
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
start
start(release: bool = True)
Start Websocket monitoring
stop
stop()
Stop Websocket monitoring
unmonitor_command_active
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
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
Stops monitoring supplied datarefs.
[description]
Parameters:
-
datarefs
dict
) –{path: Dataref} dictionary of datarefs
-
reason
str | None
, default:None
) –Documentation only string to identify call to function.
Returns:
-
Tuple[int | bool, Dict]
–Tuple[int | bool, Dict]: [description]
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:
-
dataref
Dataref
) –Dataref write to simulator
Returns:
-
bool | int
–bool if fails
-
bool | int
–request id if succeeded
ws_listener
ws_listener()
Read and decode websocket messages and calls back