Skip to content

examples: run MAVSDK on a dedicated loop thread (FastAPI example) - #834

Open
vishwagw wants to merge 1 commit into
mavlink:mainfrom
vishwagw:examples-fastapi-mavsdk-thread
Open

vishwagw wants to merge 1 commit into
mavlink:mainfrom
vishwagw:examples-fastapi-mavsdk-thread

Conversation

@vishwagw

Copy link
Copy Markdown
Contributor

Problem

MAVSDK-Python uses grpc.aio, and the channel is bound to the event loop that was running
when System.connect() was called. Awaiting a MAVSDK call from another loop fails, for
example uvicorn's loop when FastAPI runs in a separate thread (as in #720), or a second
asyncio.run():

RuntimeError: Task <...> got Future <Task pending ... UnaryUnaryCall._invoke() ...>
attached to a different loop

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.py shows the usual pattern: MAVSDK gets one event loop in a
background thread, and every other part of the app hands coroutines to it.

  • MavsdkThread.run_async(coro): await from any other loop (FastAPI handlers) via
    asyncio.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 latest
    values are cached for handlers to read, and the task reference is kept (RUF006).
  • FastAPI lifespan starts and stops the thread. Endpoints: GET /telemetry, POST /arm,
    /takeoff, /land. Action errors map to HTTP 409.

It needs fastapi and uvicorn, as the docstring notes. MAVSDK itself has no new
dependencies.

Testing


> Optional before opening: run it once against PX4 SITL (`make px4_sitl gz_x500`), which is the
> setup in #720, and add a line to Testing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant