Git Product home page Git Product logo

python-simconnect's Introduction

PyPI version

Python-SimConnect

Python interface for Microsoft Flight Simulator 2020 (MSFS2020) using SimConnect

This library allows Python scripts to read and set variables within MSFS2020 and trigger events within the simulation.

It also includes, as an example, "Cockpit Companion", a flask mini http server which runs locally. It provides a web UI with a moving map and simulation variables. It also provides simulation data in JSON format in response to REST API requests.

Full documentation for this example can be found at https://msfs2020.cc and it is included in a standalone repo here on Github as MSFS2020-cockpit-companion.

Mobiflight Simconnect events:

Yes this supports the new SimConnect commands that DocMoebiuz of MobiFlight developed. A full list of commands and install instructions

At this time MobiFlight SimConnect commands are not include in the AircraftEvents class and as so the AircraftEvents.find() and AircraftEvents.get() will not work. You will need to pass the Event ID to a new Event class as the Example below shows.

from SimConnect import *
# Create SimConnect link
sm = SimConnect()
# Creat a function to call the MobiFlight AS1000_MFD_SOFTKEYS_3 event.
Sk3 = Event(b'MobiFlight.AS1000_MFD_SOFTKEYS_3', sm)
# Call the Event.
Sk3()
sm.exit()
quit()

Python interface example

from SimConnect import *

# Create SimConnect link
sm = SimConnect()
# Note the default _time is 2000 to be refreshed every 2 seconds
aq = AircraftRequests(sm, _time=2000)
# Use _time=ms where ms is the time in milliseconds to cache the data.
# Setting ms to 0 will disable data caching and always pull new data from the sim.
# There is still a timeout of 4 tries with a 10ms delay between checks.
# If no data is received in 40ms the value will be set to None
# Each request can be fine tuned by setting the time param.

# To find and set timeout of cached data to 200ms:
altitude = aq.find("PLANE_ALTITUDE")
altitude.time = 200

# Get the aircraft's current altitude
altitude = aq.get("PLANE_ALTITUDE")
altitude = altitude + 1000

# Set the aircraft's current altitude
aq.set("PLANE_ALTITUDE", altitude)

ae = AircraftEvents(sm)
# Trigger a simple event
event_to_trigger = ae.find("AP_MASTER")  # Toggles autopilot on or off
event_to_trigger()

# Trigger an event while passing a variable
target_altitude = 15000
event_to_trigger = ae.find("AP_ALT_VAR_SET_ENGLISH")  # Sets AP autopilot hold level
event_to_trigger(target_altitude)
sm.exit()
quit()

HTTP interface example

Run glass_server.py using Python 3.

http://localhost:5000

Method: GET

Variables: None

Output: Web interface with moving map and aircraft information

http://localhost:5000/dataset/<dataset_name>

Method: GET

Arguments to pass:

Argument Location Description
dataset_name in path can be navigation, airspeed compass, vertical_speed, fuel, flaps, throttle, gear, trim, autopilot, cabin

Description: Returns set of variables from simulator in JSON format

http://localhost:5000/datapoint/<datapoint_name>/get

Method: GET

Arguments to pass:

Argument Location Description
datapoint_name in path any variable name from MS SimConnect documentation

Description: Returns individual variable from simulator in JSON format

http://localhost:5000/datapoint/<datapoint_name>/set

Method: POST

Arguments to pass:

Argument Location Description
datapoint_name in path any variable name from MS SimConnect documentation
index (optional) form or json the relevant index if required (eg engine number) - if not passed defaults to None
value_to_use (optional) value to set variable to - if not passed defaults to 0

Description: Sets datapoint in the simulator

http://localhost:5000/event/<event_name>/trigger

Method: POST

Arguments to pass:

Argument Location Description
event_name in path any event name from MS SimConnect documentation
value_to_use (optional) value to pass to the event

Description: Triggers an event in the simulator

Running SimConnect on a separate system.

Note: At this time SimConnect can only run on Windows hosts.

Create a file called SimConnect.cfg in the same folder as your script.

Sample SimConnect.cfg:

; Example SimConnect client configurations
[SimConnect]
Protocol=IPv4
Address=<ip of server>
Port=500

To enable the host running the sim to share over network,

add <Address>0.0.0.0</Address>

under the <Port>500</Port> in SimConnect.xml

SimConnect.xml can be located at

%AppData%\Microsoft Flight Simulator\SimConnect.xml

Sample SimConnect.xml:

<?xml version="1.0" encoding="Windows-1252"?>

<SimBase.Document Type="SimConnect" version="1,0">
    <Descr>SimConnect Server Configuration</Descr>
    <Filename>SimConnect.xml</Filename>
    <SimConnect.Comm>
        <Descr>Static IP4 port</Descr>
        <Protocol>IPv4</Protocol>
        <Scope>local</Scope>
        <Port>500</Port>
        <Address>0.0.0.0</Address>
        <MaxClients>64</MaxClients>
        <MaxRecvSize>41088</MaxRecvSize>
    </SimConnect.Comm>
...

Notes:

Python 64-bit is needed. You may see this Error if running 32-bit python:

OSError: [WinError 193] %1 is not a valid Win32 application

Per mracko on COM_RADIO_SET:

MSFS uses the European COM frequency spacing of 8.33kHz for all default aircraft. 
This means that in practice, you increment the frequency by 0.005 MHz and 
skip x.x20, x.x45, x.x70, and x.x95 MHz frequencies. 
Have a look here http://g3asr.co.uk/calculators/833kHz.htm

Events and Variables

Below are links to the Microsoft documentation

Function

Event IDs

Simulation Variables

python-simconnect's People

Contributors

chssn avatar codebizarre avatar daheise avatar dff180 avatar flymypi avatar gregretkowski avatar hankhank10 avatar heiss avatar kant avatar kleinjakob avatar koseng avatar maartentamboer avatar mikeneilson avatar odwdinc avatar sdshlanta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-simconnect's Issues

Asyncio and Multithreading Idea/Proposal

I've been working on performance improvements and came up with a multithreaded implementation using asyncio. The results so far were very promising. I was able to lower the JS setInterval to 50 and access the webserver from 4 different browsers/devices concurrently without any issues.

Here is how I did it:

# init global vars
ui_friendly_dictionary = {}
event_name = None
value_to_use = None
sm = None
ae = None

# Thread 1: Flask WebApp
def flask_thread_func(threadname):
    global ui_friendly_dictionary
    global event_name
    global value_to_use
    global sm
    global ae
    
    app = Flask(__name__)
    
    @app.route('/ui')
    def output_ui_variables():
        # Initialise dictionaru
        ui_friendly_dictionary["STATUS"] = "success"
        return jsonify(ui_friendly_dictionary)
    
    #### Rest of the functions like trigger_event and trigger_event_endpoint...

    app.run(host='0.0.0.0', port=4000, debug=False)

# Thread 2: SimConnect
def simconnect_thread_func(threadname):
    
    global ui_friendly_dictionary
    global event_name
    global value_to_use
    global sm
    global ae
    
    sm = SimConnect()
    ae = AircraftEvents(sm)
    aq = AircraftRequests(sm)

    async def ui_dictionary(ui_friendly_dictionary):
        ui_friendly_dictionary["LATITUDE"] = await aq.get("PLANE_LATITUDE")
        #### Rest of all SimConnect vars...

    while True:
        asyncio.run(ui_dictionary(ui_friendly_dictionary))


if __name__ == "__main__":
    thread1 = Thread(target = simconnect_thread_func, args=('Thread-1', ))
    thread2 = Thread(target = flask_thread_func, args=('Thread-2', ))
    thread1.start()
    thread2.start()

I was still experiencing a ~0.5 seconds delay when retrieving quite a lot of SimConnect vars, but the app ran stable. Maybe, you could separete the SimConnect var retrieval onto multiple threads and minimize the latency even more. I'm no Python expert so I might be wrong on this. Maybe it's fundamentally flawed, most likely there is a better way to solve this. Nevertheless, I'd like to hear your thoughts on this.

Thanks!

Status

hey,

i want to contribute to a python module for simconnect, to build new applications on top of it. But i am not familiar with simconnect.

After some searching, i found your module and the simscript(abandoned). Can you name differences between this two implementations for simconnect? (I did not work with ctypes previously.)

After take a small look into your test.py, i think that your module would benefit of a new abstract layer on top of it and an async implementation to get it more pythonic.

Additionally, i would like to know some things to contribute to your project:

  • What is the status of your first implementation? (Is it feature complete?)
  • What are your plans for the near future? (Do you want to publish your module on pypi?)

Thank you and have a nice day,
Peter

LoadFlight Function doesn't work

Hi, I've tried to feed the .flt path to the load_flight() function but it never worked, any idea what I have done wrong? Thanks.

Problem getting started

I apologize for wasting your time on something that's probably a non-issue. I"m a relative newbie to python, totally new to github, but pretty proficient at arduino. My plan is to build some generic instruments controlled via an arduino like altimeter, AOA, heading, etc and found this project that uses python to retrieve the simconnect data. When I run the local_example script I'm getting:

Traceback (most recent call last):
  File "C:/Users/Scott/PycharmProjects/SimConnect/main.py", line 1, in <module>
    from SimConnect import *
  File "C:\Users\Scott\PycharmProjects\SimConnect\venv\lib\site-packages\SimConnect\__init__.py", line 2, in <module>
    from .Entities import Plane
ModuleNotFoundError: No module named 'SimConnect.Entities'

Is this a problem on my end?

Issue tracker for web app

  • Autopilot on/off buttons (except master) turn settings on but not off
  • Autopilot set variable buttons do not work
  • Autopilot airspeed variable not displaying
  • Flaps slider displays wrong way round
  • Trim data not working

COM_RADIO_SET not working for the third decimal place

I've been trying to implement COM_RADIO_SET, but wasn't able to fully make it work. The problem is the third decimal place.

Example:

I want to tune in to 130.000 MHz. To achieve this, I take 130 * 100 and convert it to BCD16 which is 77824. This value is used in the trigger_event function and works without problems

Next I take the frequency 130.010 MHz. I use the same procedure: 130.01 * 100 converted to BCD16 which is 77825. Works perfectly fine.

I don't know, however, how I can tune in to 130.005 MHz. Obviously, a BCD value of 77824.5 will not work. Or am I missing something?

Run error for local_example

New run error for local_example

C:\Python38\python.exe C:/Users/Scott/PycharmProjects/Python-SimConnect/local_example.py
INFO:__main__:START
Traceback (most recent call last):
  File "C:/Users/Scott/PycharmProjects/Python-SimConnect/local_example.py", line 14, in <module>
    sm = SimConnect()
  File "C:\Users\Scott\PycharmProjects\Python-SimConnect\SimConnect\SimConnect.py", line 196, in __init__
    self.dll = SimConnectDll(library_path)
  File "C:\Users\Scott\PycharmProjects\Python-SimConnect\SimConnect\Attributes.py", line 18, in __init__
    self.SimConnect = cdll.LoadLibrary(library_path)
  File "C:\Python38\lib\ctypes\__init__.py", line 447, in LoadLibrary
    return self._dlltype(name)
  File "C:\Python38\lib\ctypes\__init__.py", line 369, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application

Listen to an event

Hi,
Is it possible to create a listener to capture events triggered in the sim, not by a program?
For example, listen for the event GEAR_TOGGLE when retracting gears using the in-sim lever.

Loading/Saving Flights

Hello,
first of all hats off to you, this is an amazing project!

I know they aren't documented yet but I have been experimenting with your load_flight() and save_flight() methods.
As I have noticed, flights saved by this method cannot be opened by the sim in its current version.

Upon further investigation, it turns out, that an incomplete [Main] section in the .flt is to blame for that.
Missing the line MissionType=FreeFlight will result in the sim not recognizing a flight. When I added it, your flight worked fine.

I don't know if this is new information to you or whether you can even adapt those saving/loading SimConnect functions, but I thought I'd let you know what I found out.

Many -999999 when using Python-SimConnect and Godot

Hi everyone, I'm attempting to integrate Python-SimConnect with the Godot game engine using its python bindings . The purpose is to use Godot as the front end for an application I want to develop. I was able to get it working, but, for some reason, when using godot I get many more -999999 as the result for requests than purely using python.

Here's the code I'm using to workaround the issue. Even with 10 attempts per request, sometimes it takes up to 300 calls before I get a value different from -999999.

from godot import *
from SimConnect import *

sim_connection = SimConnect()
aircraft_events = AircraftEvents(sim_connection)
aircraft_requests = AircraftRequests(sim_connection, _time = 2000, _attemps = 10)

@exposed
class GodotSimConnect(Node2D):
	def _ready(self):
		print('GodotSimConnect loaded')
	
	def get_variable(self, variable):
		result = -999999
		for i in range(1000):
			result = aircraft_requests.get(str(variable))
			if result != -999999:
				print(i)
				return result
		return result

This is the script that's calling the function. It's in gdscript (godot's scripting language), but what it does is call get_variable( ) in the python script with the plane's altitude as the parameter every 2 seconds.

extends Timer

onready var godot_simconnect = get_node("..")

func _ready() -> void:
	connect("timeout", self, "_on_Timer_timeout")
	

func _on_Timer_timeout() -> void:
	print(godot_simconnect.get_variable("PLANE_ALTITUDE"))

Using this code, I get a proper value most of the time, but that's because I'm brute forcing it by doing an excessive number of requests, which is far from ideal. Any help would be appreciated.

Error in "Python Interface Example"

In the README.md, you have "sm.quit()" which causes an error and causes subsequent runs of the script not to behave correctly.
Changing to "sm.exit()" solves the issue.

Pitch Roll Yaw

Hi,

Thanks for doing this wrapper. I have a quick question.

Can we extract Pitch Yaw Roll values with this wrapper? I'm not looking to get these values into a web app, just trough a simple script for the moment.

Thanks in advance

Example for writing back values

Thank you for this nice project. Im a beginner at programming, so this helped me a lot to build something that can control my desk / room lights based on ingame events.

Would it be possible to add an example how i can write back values to things like

PROP RPM:index
or
GENERAL ENG THROTTLE LEVER POSITION:index

?

Similar to your example with the toggle event for the Gear which helped me a lot.
I tried to figure it out through the SDK Examples but that was a bit too overwhemling for my beginner level.

Version Check

I think a function/parameter which provides the installed version number of the Python-SimConnect would be worth adding so that if things start become less backward-compatible a check can be performed at import for the version required.

Eg:

from SimConnect import *
if sc_version < (0,4,2):
  print("Python-SimConnect must be at least 0.4.2")
  exit()

# Create SimConnect link
sm = SimConnect()
# Note the default _time is 2000 as to refreshed at 2s
aq = AircraftRequests(sm, _time=2000)

`Name 'Request' is not defined`

Hello,
When trying to set altitude using aq.set("PLANE_ALTITUDE",20000), I get Name 'Request' is not defined.
It seems that an underscore is missing in set_data

YOKE_X_POSITION and YOKE_Y_POSITION throw error

Im trying to read the status of the yoke (joystick) by using this code

position = aq.get("YOKE_X_POSITION")
print(position)

and im getting this error:

SIMCONNECT_EXCEPTION_NAME_UNRECOGNIZED
SIMCONNECT_EXCEPTION_UNRECOGNIZED_ID: in (b'YOKE X POSITION', b'Position (-16K to 0) -16K =')
-999999

Add support for sending text messages to the screen?

It has been possible since FSX to send short text messages to the screen via SimConnect (ATIS messages, etc.), and that ability remains in MSFS2020—the vPilot client, for example, makes use of it to transmit text communications from ATC.

It would be great to have an easy hook to use that feature! (Thanks for your great work on this so far, by the way.)

Data Update Rate

Hi!

First, thanks for your hard work developing this!

I'm having an issue with the data update rate.

  • If I poll the data, and log it with a timestamp, say every 250ms, I only get a change in the data every 4 or 5 samples, suggesting that SimConnect's data set is only being refreshed every second.
  • I am only using requests.

Is there an issue or am I doing something wrong?

from SimConnect import *
from datetime import datetime
import requests
import time

sm = SimConnect()
aq = AircraftRequests(sm)

while not sm.quit:

    baralt = aq.PositionandSpeedData.get('PLANE_ALTITUDE')
    vs = aq.FlightInstrumentationData.get('VERTICAL_SPEED')
    gs = aq.PositionandSpeedData.get('GROUND_VELOCITY')
    ias = aq.FlightInstrumentationData.get('AIRSPEED_INDICATED')
    lat = aq.PositionandSpeedData.get('PLANE_LATITUDE')
    long = aq.PositionandSpeedData.get('PLANE_LONGITUDE')
    heading = aq.PositionandSpeedData.get('PLANE_HEADING_DEGREES_TRUE') * 57.2958 # rads to degrees

    data = { 
      "ts": datetime.now().strftime('%H:%M:%S.%f')
      "baralt": round(baralt), 
      "vs": round(vs),
      "gs": round(gs),
      "ias": round(ias),
      "lat": lat,
      "long": long,
      "heading":round(heading),
    }

    # the post method is just an example. Have also tested appending the dataset to a list each time, then dumping the list to a JSON file.
    r = requests.post(url = "http://server/api/set/", data = data)
    time.sleep(0.25)

sm.exit()

Lot's of None values received

Very nice package, the glass cockpit demo is great, however I cannot get it to work with both the local_exemple.py and glass_server. I am getting a lot of None values returned from aq.get. I am using MSFS 2020 version 1.9.5.0 and SimConnect 0.6.1 DLL (as present in the branch).

Have you experienced any of this?

  File "C:\Dev\python\simconnect\Python-SimConnect-master\glass_server.py", line 307, in output_ui_variables
    fuel_percentage = (aq.get("FUEL_TOTAL_QUANTITY") / aq.get("FUEL_TOTAL_CAPACITY")) * 100
TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType'

Or in some local_example.py fiddling.

Throttle = aq.find('GENERAL_ENG_THROTTLE_LEVER_POSITION:1')
altitude_f = aq.find("PLANE_ALTITUDE")
altitude_f.time = 200
while not sm.quit:
	print("Throttle:", Throttle.value)
	#altitude = aq.get("PLANE_ALTITUDE")
	
	#print ("Altitude:", altitude)
	print("Altitude_f:", altitude_f.value)
	sleep(2)

Altitude_f: 1175.8360727116944
Throttle: 0.0
Altitude_f: None
Throttle: 0.0
Altitude_f: None
Throttle: 0.0
Altitude_f: 1175.8360727116944
Throttle: 0.0
Altitude_f: None
Throttle: 0.0
Altitude_f: 1175.8360727116944
Throttle: 0.0
Altitude_f: None
Throttle: 0.0
Altitude_f: None
Throttle: 0.0
Altitude_f: 1175.8360727116944

Run python-simconnect on remote machine

Is there a way for me to run the python-simconnect on a remote machine? I have seen other programs that are able to use the ip and port 500.

For example i want to run all my python and scripting on 192.168.1.101

My MSFS is running on 192.168.1.102.

so I "should" be able to connect from 192.168.1.101 using 192.168.1.102:500

Accessing SimVars that are not listed

How can one access unlisted SimVars?
I tried manually accessing a LocalVar, but I get SIMCONNECT_EXCEPTION_NAME_UNRECOGNIZED.
For example, when loading the A320, in DevMode I go to Model Behaviors window (Windows->Model Behaviors), I see a LocalVar named LANDING_1_Retracted.

Question : FSX support ?

Thank you for all the work that has been put in this library.

The question if fairly simple, does this library supports interfacing with FSX:SE ?

If not, will this be a feature or a no-go ? If yes, is it hard to do ?
How could I help ?

Speed up connection refresh

I would like to do some testing, but i can not seem to figure out how to speed up the connection and refreshes to simconnect.

It looks like the default is 2 sec.

library causes python exit if connect() is called when sim is not running

Thanks for a great library! I've been working on my first project using it - a simple app to control the simrate up/down since that is not displayed in-game. The library is working really well in this application. When connect() is called and MSFS is not running python exits. It does not print an error nor does it raise an exception. I was hoping to catch exceptions when connect() fails but afaict that cannot currently be done. The ask is that connect() raise an catchable exception instead of exiting python.

Steps To Reproduce:

PS C:\Users\greg\msfstime> python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from SimConnect import SimConnect
>>> sm = SimConnect(auto_connect=False)
>>> sm.connect()
PS C:\Users\greg\msfstime>

GPS Coordinates of all Waypoints

Hi everyone,

I do not see a possibility to get all waypoint coordinates. I want to build the A320 Navigation Display in hardware. Is it possible to implement the index option for these requests? If somebody shared some basic documentation for the SDK used, I would try to implement it myself and contribute it to the project.

Event THROTTLE_FULL not working

I dont know why but when I try to trigger 'THROTTLE_FULL' gives this error

event_to_trigger()
TypeError:` 'NoneType' object is not callable

I tried with 'THROTTLE_CUT' and it works like it should

-999999.0 values

Dear all,

First thanks for your awesome work. This is superb.
I am more on the data analytics side of things (and a hobby programmer) and I would have a few questions.

I have taken a detailed look to RequestList.py and found most of the interesting KPIs I need.

  1. To your knowledge, is there a way to get the flight Origin and Destination (provided they are entered in the flight plan) ?
    I understand this is doable by using 'GPS_WP_PREV_ID', "GPS_WP_NEXT_ID", but does this exist somehwere?

  2. Same regarding the whole Flight plan, is there a way to programatically fetch it?

  3. Is there a way to get something like a flightid or sessionID (independant from what the player enters), to have a unique key for data storage processes?

Thanks a lot!

Sebastien

Web app: development roadmap

I have created a Trello board for the features that I plan to add to the web app and where there are bugs which need fixing.

I have colour coded the issues based on whether they are front end (for me to do) and where I will need help on the back end.

If you would like to be added to the Trello board to contribute then please let me know.

https://trello.com/b/lYT0cfTt/glass-cockpit

Thoughts about the user side

Hi, I came here from the reddit post, this looks quite promising.

I had a quick go at condensing the user side of the api to the level I reckon is pretty good and kinda feels consistent with other python libraries. At least to me.
Most of the stuff under 'library code' is wrappers, and isn't meant to be how it actually works, just get it kinda going.
The important bit is under 'user code'.

https://gist.github.com/dooglewoogle/5f06422829b528a699c16766a70b0065

Please let me know what you think.

Removing simconnect.dll

Do I understand correctly that the plan before distributing this is to remove simconnect.dll from the repo given it is not open source?

If so, could I understand what the simplest ways are for users to get this file and where they should put the file once they have it (in the python directory?)

I think it would be helpful to add this to the readme

CPU Usage

Any thoughts on how to lower the CPU usage?

image

[Request] CHANGELOG.md

Hi, thank you for making this great library.

Given that FS2020 and Python-Simconnect is both moving very fast, it's hard to figure out and discover what's added with a new version.

It would be awesome to have a changelog file that tells us what are new things.

TypeError RequestList.py

Hey guys,

i have a problem with the RequestList.py. I cloned this repo and tried to execute local_example.py and glass_server.py.

Could someone help me?

Python version: 3.8.6 64Bit

Log:

python glass_server.py
Traceback (most recent call last):
  File "glass_server.py", line 14, in <module>
    aq = AircraftRequests(sm, _time=10)
  File "C:\Users\Michael\Desktop\Python-SimConnect\SimConnect\RequestList.py", line 192, in __init__
    self.EngineData = self.__AircraftEngineData(_sm, _time, _attemps)
TypeError: __init__() takes from 2 to 3 positional arguments but 4 were given

python local_example.py
INFO:__main__:START
DEBUG:SimConnect.SimConnect:Connected to Flight Simulator!
INFO:SimConnect.SimConnect:SIM OPEN
Traceback (most recent call last):
  File "local_example.py", line 15, in <module>
    aq = AircraftRequests(sm)
  File "C:\Users\Michael\Desktop\Python-SimConnect\SimConnect\RequestList.py", line 192, in __init__
    self.EngineData = self.__AircraftEngineData(_sm, _time, _attemps)
TypeError: __init__() takes from 2 to 3 positional arguments but 4 were given

User display through browser

I am very pleased to have found a python project attempting to work with SimConnect.

What is the end goal of the project?

I would have thought it would be helpful to expose the information pulled out of the sim (and allow control of certain aspects) to the user in a GUI. I would also suggest that the most straightforward way to do this would be through a web based interface so it is platform agnostic.

If this is the plan then I would be very happy to work on the web aspects, which I would propose to run through flask which I am fairly experienced with.

Flight to Dic Issue

The fix for #55, has broken how flight_to_dic used to work. It now needs a file to read from, where it used to use a temporary file.
I'm unsure how to make it work with the save_flight function.

Python-SimConnect Help with P3D?

Hello,
First of all, I really want to thank you for providing such an amazing piece of software.

My name is Vamshi, a PhD student from Ryerson University, Toronto, we are working on a project in which we need to control a Prepar3D(P3D) simulation with external data sources (data coming in from a python program...we are using a gps data log file to send data into the simulation.)

I have landed on Python-SimConnect and have been thanking the gods for it serves the exact purpose. I am trying to run the setup and keep running into the following error:

"SIMCONNECT_EXCEPTION_VERSION_MISMATCH"

This is obviously because the SimConnect version being used and the s/w was designed for is FS2020. The P3D sim i am using is P3D V5 which has a simconnect version of 5.1.0. Thus, the server (P3D) does not match the Client SimConnect version.
Since both FS2020 and P3D all develop with SimConnect to send/receive data, this should work.

I've also tried another thing, I've moved the simconnect.dll files from the P3D path into the python project file so that it can reference a dll generated with the libraries compiled on the P3D side. However, I get the following error:

" File "C:\Users\MIMS-PC\AppData\Local\Programs\Python\Python38\lib\ctypes_init_.py", line 391, in getitem
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'SimConnect_Open' not found"

It says simconnect_open not found, in the attributes.py file, we notice that the:

self.SimConnect = cdll.LoadLibrary(library_path)

SIMCONNECTAPI SimConnect_Open(

HANDLE * phSimConnect,

LPCSTR szName,

HWND hWnd,

DWORD UserEventWin32,

HANDLE hEventHandle,

DWORD ConfigIndex)

SIMCONNECTAPI SimConnect_Open is commented out.

These are two possible methods that I am trying right now. Looking forward to your reply and your guidance.

Can you please please please guide me through this? It will help me so much with my studies in creating an amazing data-driven simulation.

Question: sm.map_to_sim_event(b"") vs ae.find("")

Hi, first of all thanks to odwdinc for his amazing work and all other contributors as well.
I am not really a programmer and rather new to github.com as well so i don't know where to ask or how to contact odwdinc myself so i like to ask my question here. Sorry if it aint the right place or way to do, we can delete this "issue".

Whats the difference between the following two ways to send an event?
Does it make any difference at all in terms of memory usage, speed or other issues i don't know about?
Which one is preferable?

event_hdg_rot_inc = ae.find("HEADING_BUG_INC")
event_hdg_rot_inc(1)

event_hdg_rot_inc = sm.map_to_sim_event(b"HEADING_BUG_INC")
sm.send_event(event_hdg_rot_inc, 1)

No Licence

At present this repo is not licensed

Please could you add a GPL-3.0 License so that code can be reused?

Indexes and Requests

Hello again!

I have run into some strange behaviour for the aq.find() method.

I'm probably doing something stupid, but here is what I am doing and observing:

signals = {
'COM_ACTIVE_FREQUENCY:1': {"getter": None, "val": None},
'COM_ACTIVE_FREQUENCY:2': {"getter": None, "val": None},
'NAV_ACTIVE_FREQUENCY:1': {"getter": None, "val": None},
'NAV_ACTIVE_FREQUENCY:2': {"getter": None, "val": None},
}

while True:

  for signal in signals.keys():

    if signals[signal]["getter"] == None:
      signals[signal]["getter"] = aq.find(signal)

    data = signals[signal]["getter"].value
    if not data == None:
      signals[signal]["val"] = data

    print(signal, signals[signal]["getter"], signals[signal]["val"])
  print()

  sleep(2)

This results in the reading for the first loop being good, but subsequent loops only show the 2nd index reading as follows:

COM_ACTIVE_FREQUENCY:1 <SimConnect.RequestList.Request object at 0x0000028F5FB9E130> 128.7
COM_ACTIVE_FREQUENCY:2 <SimConnect.RequestList.Request object at 0x0000028F5FB9E130> 124.85
NAV_ACTIVE_FREQUENCY:1 <SimConnect.RequestList.Request object at 0x0000028F5FB9E160> 113.8
NAV_ACTIVE_FREQUENCY:2 <SimConnect.RequestList.Request object at 0x0000028F5FB9E160> 112.8

COM_ACTIVE_FREQUENCY:1 <SimConnect.RequestList.Request object at 0x0000028F5FB9E130> 124.85
COM_ACTIVE_FREQUENCY:2 <SimConnect.RequestList.Request object at 0x0000028F5FB9E130> 124.85
NAV_ACTIVE_FREQUENCY:1 <SimConnect.RequestList.Request object at 0x0000028F5FB9E160> 112.8
NAV_ACTIVE_FREQUENCY:2 <SimConnect.RequestList.Request object at 0x0000028F5FB9E160> 112.8

The results also show that the two COM signals use the same request (and hence the same value) as do the NAV radio signals. I can see the index being checked for during the aq.find() method, but can't really follow how the index is considered during the .value read.

Thanks for any assistance!

OS Error when more than one machine is connected.

When I only have one machine connected all is well.

When i attempt to watch on a second machine like my phone. then the server crashes.

`OSError: [WinError -1073741648] Windows Error 0xc00000b0
192.168.1.31 - - [21/Sep/2020 16:42:20] "←[35m←[1mGET /ui HTTP/1.1←[0m" 500 -
Traceback (most recent call last):
File "C:\Python38\Lib\site-packages\flask\app.py", line 2464, in call
return self.wsgi_app(environ, start_response)
File "C:\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python38\Lib\site-packages\flask_compat.py", line 39, in reraise
raise value
File "C:\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python38\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python38\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python38\Lib\site-packages\flask_compat.py", line 39, in reraise
raise value
File "C:\Python38\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python38\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functionsrule.endpoint
File "C:\Tools\MSFS2020_Utilities\fs2020cockpit\glass_server.py", line 306, in output_ui_variables
fuel_percentage = (aq.get("FUEL_TOTAL_QUANTITY") / aq.get("FUEL_TOTAL_CAPACITY")) * 100
File "C:\Users\kenny\AppData\Roaming\Python\Python38\site-packages\SimConnect\RequestList.py", line 179, in get
return request.value
File "C:\Users\kenny\AppData\Roaming\Python\Python38\site-packages\SimConnect\RequestList.py", line 17, in value
self.sm.run()
File "C:\Users\kenny\AppData\Roaming\Python\Python38\site-packages\SimConnect\SimConnect.py", line 171, in run
self.dll.CallDispatch(self.hSimConnect, self.my_dispatch_proc_rd, None)
File "_ctypes/callproc.c", line 948, in GetResult

OSError: [WinError -1073741648] Windows Error 0xc00000b0`

Questions

Hi guys,
don't know an other way to contact the contributors of this than thru an issue, so sorry for that, and please let me know, if I#m totally wrong. But I've some questions about this repo...
First of all, thanks for this wrapper! This is so big for me as I can create my own, desired interface on remote units for the FS2020!

Questions:

  1. Is it due to the wrapper or simconnect itself, that the refresh rate is so bad? For controlling switches, it's absolutely ok, but I see no way to let it produce some glass cockpit elements at all. That would be no fun, as can be seen on saasmath's attitude-indicator. Perhaps its due to my hardware (don't think so), but the refresh rate ist really bad for real time applications, I think.
  2. Is 1. due to the Python wrapper, or ist it simconnect's "fault"?
  3. Is there a way to communicate among the contributors/interrested ones? (E-Mail, Discord, etc.)
  4. As I saw some german-like-named contributors. Is this repo german speaking, or english?

Thanks so much and have a nice day!
Michael

Spaces vs Tabs and other curious questions

Howdy! I'm working on a PR to fix some spelling/grammar issues and noticed that most of the code is indented using tabs instead of spaces, as this is against the guidelines of PEP8, and general Python practice, I just wanted to know if there is a specific reason for this, or if it would be welcome to convert the files to using spaces while I'm at this?

I'm going to be pretty heavily consuming this library for a project I'm working on, so I plan on contributing more than just some grammar cleanups, and if we're going to be stuck on tabs will need to set up an editor script for that, which is the main reason I'm asking.

get_paused function issue

I have been trying the sm.get_paused() function and am receiving the error:

...\site-packages\SimConnect\SimConnect.py", line 414, in get_paused
    hr = self.dll.RequestSystemState(
ctypes.ArgumentError: argument 2: <class 'TypeError'>: Don't know how to convert parameter 2

Is this function current INOP?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.