Repository navigation
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
MAVSDK-Python uses
grpc.aio, and the channel is bound to the event loop that was runningwhen
System.connect()was called. Awaiting a MAVSDK call from another loop fails, forexample uvicorn's loop when FastAPI runs in a separate thread (as in #720), or a second
asyncio.run():As the reporter found, merging everything into one loop fixes the error. It also means a
video/OpenCV loop and MAVSDK slow each other down.
What this PR adds
examples/fastapi_mavsdk_thread.pyshows the usual pattern: MAVSDK gets one event loop in abackground thread, and every other part of the app hands coroutines to it.
MavsdkThread.run_async(coro):awaitfrom any other loop (FastAPI handlers) viaasyncio.run_coroutine_threadsafe+asyncio.wrap_future.MavsdkThread.run(coro): blocking call from plain threads (video loop, GUI).connect()and long-running telemetry subscriptions run on the MAVSDK loop. The latestvalues are cached for handlers to read, and the task reference is kept (RUF006).
lifespanstarts and stops the thread. Endpoints:GET /telemetry,POST /arm,/takeoff,/land. Action errors map to HTTP 409.It needs
fastapianduvicorn, as the docstring notes. MAVSDK itself has no newdependencies.
Testing
action.arm()fromasyncio.run()in another thread./telemetryreturnsposition and armed state, and
/arm,/takeoffand/landreturn 200. The blockingrun()from a plain thread works, and shutdown is clean.ruff format --check/ruff check --select=ASYNC,RUF006,E,Fpass.