How to make bleak compatibile with cmd, cmd2, or other terminal apps? #1513
-
I've had some trouble getting bleak to work inside cmd2, but the problem would also be present in other frameworks such as cmd or GUI/TUI applications like tkinter or Textual. All of this is happening on Windows, but I would imagine the same restrictions may appear on other OS's like Linux or MacOS/BSD. Bleak is built from the ground up around asyncio, meaning it expects the main thread to be running async from the top down on the main process thread. There's several cases where this is not feasible:
I wanted background scanning functionality but bleak doesn't support that, so I set my expectations to a time-bounded scanning operation. I tried creating a separate thread (threading module) and run the thread as async with a threading.Queue to process control commands, but I ran into asyncio exceptions like "operation cancelled by user", and the BLE connection would not stay alive when I connected to the peripheral. I'm guessing this is because blocking the second thread for events somehow prevented the host from sending during the connection windows. So I removed the thread and created an async loop through which to funnel all of my async interactions with bleak:
This worked fine until I connected to a GATT server and tried to set up notify callbacks. The notify callback was not received until after I quit the program. I think the answer must rely on getting threading and asyncio to play nicely, so what's the right way to make this possible using an event-driven control thread without a continuous asyncio loop? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There have been several other discussions about using Bleak in a non-asyncio app, e.g #826. TL;DR; there should only be one |
Beta Was this translation helpful? Give feedback.
It's frustrating that there's no built-in functionality to the asyncio library that does this, as it seems this is a too-common problem with a not-so-common solution.
I had searched for cmd and cmd2 in the discussion here with no results so maybe this will at least improve the visibility of this solution. Not sure if there are any libraries out there that provide this functionality, but maybe someone will make one. It might have been nice if bleak did not rely on asyncio in the public interface, but it's too late to change it. Maybe for bleak2! 😄
I got this working by creating a singleton object that encapsulates a thread and the asyncio loop execution. Anyone may feel free to use this or…