KanoComputing / community-sdk

Scripts, tools and libraries to help you to interact with your Kano Devices in your favourite programming language.
MIT License
31 stars 11 forks source link

Can't call `rpc_request` from event callbacks #3

Open murilopolese opened 5 years ago

murilopolese commented 5 years ago

Can't get event loop from inside a coroutine, apparently. I have no idea how to fix this and it's probably because I should be doing this in a different way.

This code:

from communitysdk import list_connected_devices, MotionSensorKit
msk = None
devices = list_connected_devices()
if len(devices):
    if isinstance(devices[0], MotionSensorKit):
        msk = devices[0]
        def on_proximity(p):
            if p > 200:
                try:
                    msk.set_mode('proximity')
                except Exception as e:
                    print(e)
            else:
                print('proximity', p)
        def on_gesture(g):
            if g == 'up':
                try:
                    msk.set_mode('proximity')
                except Exception as e:
                    print(e)
            else:
                print('gesture', g)
        msk.on_proximity = on_proximity
        msk.on_gesture = on_gesture
else:
    print('there is no device connected')

Prints There is no current event loop in thread 'ThreadPoolExecutor-0_0'. when I swipe up on Motion Sensor.

murilopolese commented 5 years ago

While not a perfect solution because introduce a race condition, removing the creation of a coroutine for waiting the response makes it possible to call rpc_request from a method called from the Executor. The rpc_request was always meant to be blocking so instead of running it on the asyncio thread it's actually running on the main thread.

For requests that require a faster rate, such as stream_frame it doesn't use the blocking rpc_request but sends the data straight to the connection.

https://github.com/KanoComputing/community-sdk/commit/c74dcff47fca03ed26a5b8e18b7cb222abdd606a

murilopolese commented 5 years ago

As the result of the race condition apparently behaves inconsistently on different computers (might be the specs or the OS) this turns out to be a terrible idea. Reopening this issue and going to try a different approach like this or this.