Use Python to Upload Mission to Pixhawk
Getting started with MAVSDK – Python
Following my presentation at the first PX4 DevSummit terminal summer, this post will focus on showing, step past step, how to get up and running with a drone using MAVSDK-Python. No particular knowledge of MAVSDK or MAVLink is expected here, except for ii prerequisites: having a drone (preferably a simulated ane, for a start), and running a version of Python no older than 3.six. Don't worry if yous don't have that, as I will requite you the correct directions on this blog. Currently, the latest version of MAVSDK-Python is 0.3.0. For the impatients who already satisfy the prerequisites, feel costless to bound to "Quick Start" below. Merely before we get started, let'southward effort to understand why we practice this and who this is for.
Annotation that this post is followed by MAVSDK-Python: easy asyncio, which goes deeper into the asyncio mechanisms.
The Goal
Every single use example involving a drone requires a basis station or a connection to the cloud: one needs to program a mission, check that the drone is ready to fly, and control the mission during the flight. Most drone manufacturers provide an SDK to control their products, and the PX4 open source community is no different in this regard. What are the advantages of MAVSDK?
- Designed for speed and efficiency
- Offers multi-linguistic communication support
- Is available in multiple development environments
- Runs on any device using MAVLink
- Allows plugin integration
With MAVSDK we also aim at serving different actors, e.g. service providers and drone manufacturers, to share and interact on a common API without preventing them from diversifying. All drones provide telemetry and basic mission features, merely let'southward say one drone carries a very specific sensor, in that case, a drone manufacturer should exist able to add together unilateral back up for this sensor without even open sourcing it.
What is MAVSDK?
MAVSDK is a set up of libraries providing a high-level API to MAVLink, providing easy to learn programmatic access to vehicle information and telemetry, as well equally control over missions, movement, and other operations.
What does that mean exactly? Well, let's say you accept a drone (or robot). If that drone is MAVLink-enabled (i.due east. information technology "talks MAVLink"), and so MAVSDK will allow you to write programs that command it. If you are non certain whether or not your drone talks MAVLink, the simple rule is this: if QGroundControl tin connect to it, then it talks MAVLink.
MAVSDK is primarily used by developers as a tool for integrating different components on a vehicle – the flight stack, companion figurer, and MAVLink peripherals (due east.grand. cameras). Information technology tin also be used for implementing footing station functionality that is specific to a particular domain (that would not normally be in a generic GCS like QGroundControl).
This article will focus on a simple setup with a simulator running on your computer (we telephone call that "Software in the Loop", or "SITL"), to which MAVSDK volition connect.
Prerequisites
- Python 3.6+: run
python --versionorpython3 --versionin a last to check the installed version. - A running SITL example (jMAVSim, gazebo, …). A quick style to run a headless gazebo SITL example is documented here.
Quick Start
Enough talking, allow'southward get some code running!
Installing through pip
First, let'southward install MAVSDK-Python:
pip install mavsdk Make certain that the output of this command confirms that the installation succeeded! Note that on some systems, you may accept to run pip3 install --user mavsdk (install in user space), sudo pip3 install mavsdk (install on your organization), or you may desire to run in a Python venv.
For a quick start in a REPL (interactive trounce), nosotros will as well install the lightweight parcel called "aioconsole", which provides apython (which is a REPL for running asyncio lawmaking):
pip3 install aioconsole Starting SITL
Now let'southward run SITL (due east.g. make posix jmavsim, or using the headless gazebo docker container that was linked to a higher place). I commonly like to check that it is working past taking off manually from the SITL interactive console:
pxh> commander takeoff pxh> commander country SITL may error with the post-obit message:
Fault [commander] rejecting takeoff, no position lock notwithstanding. Please retry.. Which means that you need to wait for information technology to get ready. I usually wait for the post-obit messages before I try to take off from commander:
INFO [ecl/EKF] EKF GPS checks passed (WGS-84 origin set) INFO [ecl/EKF] EKF commencing GPS fusion Taking off from MAVSDK-Python
When we know that the simulator is ready, we tin can open an apython REPL:
apython In which we can import MAVSDK, as follows:
from mavsdk import Organization We then create a drone object, which will be the entrypoint to MAVSDK everywhere in the scripts:
drone = System() Without going into details at present, let'southward just annotation that we likewise need to "connect" the drone object to the actual vehicle, with:
await drone.connect() And finally, allow's arm and takeoff!
wait drone.action.arm() await drone.action.takeoff() If everything went well, your drone should takeoff. In the pxh console, you should see a log line similar:
INFO [commander] Takeoff detected If running a graphical interface, you should come across the drone taking off. Here is what it looks like in jMAVSim:
Annotation: make certain to transport the takeoff() not likewise long later arm(), considering the drone will automatically disarm later a few seconds if nothing happens.
It could happen that you get an exception, like:
raise ActionError(event, "arm()") mavsdk.generated.action.ActionError: COMMAND_DENIED: 'Control denied'; origin: arm(); params: () This is not a bug! It means that the arm() call was rejected by PX4, with the mistake code COMMAND_DENIED. Information technology happens for instance when you try to arm before the drone gets a GPS set. Near functions in MAVSDK-Python can raise exceptions that your code should manage with endeavor... except.
With the drone now flight, feel free to land whenever yous want:
wait drone.action.land() And that's it for our "Howdy Earth"! Note that nosotros take been using the apython REPL to run all that interactively, but the same tin can be achieved by running the takeoff_and_land.py example (in which case the aioconsole bundle is not needed at all).
Example scripts
Nosotros practise provide a number of examples in the MAVSDK-Python repository. Note that the examples may evolve over time. At the time of this writing, the version of MAVSDK available from pip is "0.3.0", and therefore the corresponding examples can be found in the respective tag. So if an example doesn't work with your installation, brand sure to check that.
To build on the take off example above, let'southward at present take a await at the corresponding script:
#!/usr/bin/env python3 import asyncio from mavsdk import System async def run(): drone = System() wait drone.connect(system_address="udp://:14540") impress("Waiting for drone...") async for land in drone.core.connection_state(): if state.is_connected: print(f"Drone discovered with UUID: {land.uuid}") interruption print("-- Arming") expect drone.activeness.arm() impress("-- Taking off") expect drone.action.takeoff() await asyncio.sleep(5) print("-- Landing") await drone.activity.land() if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(run()) Running this script volition result in the drone taking off and landing v seconds afterward. Let'south outset accept a look at the general syntax. We are using asyncio, which is function of the Python standard library. It may seem a bit intimidating at first, only information technology is actually pretty easy to become started. Plain, nosotros commencement need to import the parcel: import asyncio. Then, nosotros define our main routine, here called run(). In asyncio, information technology is chosen a "coroutine" and its definition starts with the async keyword. You can create other coroutines the aforementioned way. For instance, await drone.action.takeoff() is actually calling another coroutine, that is divers with async def takeoff() somewhere in MAVSDK. And that's the 2nd rule: when calling a coroutine, you need to "await" for it. And information technology results in a normal, blocking function call, just similar we would expect.
One more thing to annotation with the run() coroutine is that we want information technology to be the entry point of our script (I compared it before to a "primary" function). And that'southward precisely what is washed at the cease of the script:
if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(run()) Hither nosotros just tell asyncio to run our main coroutine until it completes.
Ok, and then nosotros take seen how to import asyncio, how to create a main coroutine as the entry point to our script, how to define coroutines (async def my_coroutine()), and how to call a coroutine with await. The next thing we miss in society to understand MAVSDK-Python is the async generators. Nosotros utilize one in the beginning of the script, while we wait for a drone to connect:
impress("Waiting for drone...") async for state in drone.core.connection_state(): if state.is_connected: print(f"Drone discovered with UUID: {state.uuid}") interruption Information technology is nothing fancy, in the finish: information technology simply looks like a for loop. Except that over again, nosotros prepend it with the async keyword. In this case, nosotros receive connection_state() events until one tells us that a drone connected (if state.is_connected), then stop the loop at that point. Another way would be to just run that loop in parallel (like to running it in a thread). That's not in the telescopic of this blog post simply if yous are interested, take a look at the telemetry_takeoff_and_land.py example, which prints some telemetry data while doing the exact same "have off, wait five seconds and land" routine.
The last thing I would like to note is the following:
wait drone.connect(system_address="udp://:14540") Y'all may accept noticed that we call connect() with an argument here (
system_address). In this case, we are explicitly telling MAVSDK to heed for UDP broadcasts on port 14540. That's the default, then you may as well call await drone.connect(), like we did in the REPL in the outset of this article. But that's interesting to know, because you may want to be listening on port 14550 (system_address="udp://:14550")) or on a series port (system_address="serial:///dev/ttyACM0:115200").
Conclusion
That'southward information technology for today! I promise this quick introduction will help getting started with MAVSDK-Python and asyncio. Because asyncio is part of the Python standard library, it is super well documented, so experience gratis to read nearly information technology! When it comes to MAVSDK, you know the 2 constructions nosotros have: coroutines (e.g. calling wait drone.action.arm()), and async generators (e.one thousand. calling async for position in await drone.telemetry.position()).
Lastly, note that you can benefit from the auto-completion of an IDE like PyCharm to go the available functions and their documentation, as tin be seen in the following screenshot:
For more data about MAVSDK-Python and asyncio, take a look at the following mail service: MAVSDK-Python: like shooting fish in a barrel asyncio!
Arrive touch with the states
Make it touch for a demo, quote or whatsoever other question about the Auterion platform
Source: https://auterion.com/getting-started-with-mavsdk-python/
0 Response to "Use Python to Upload Mission to Pixhawk"
Post a Comment