Python-SimConnect icon indicating copy to clipboard operation
Python-SimConnect copied to clipboard

Asyncio and Multithreading Idea/Proposal

Open mracko opened this issue 5 years ago • 0 comments

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!

mracko avatar Nov 16 '20 14:11 mracko