This example demonstrates the basic mission operations provided by DroneKit-Python, including: downloading missions from the vehicle, clearing missions, creating mission commands and uploading them to the vehicle, monitoring the current active command, and changing the active command.
The guide topic Missions (AUTO Mode) provides more detailed explanation of how the API should be used.
In summary, after cloning the repository:
Navigate to the example folder as shown:
You can run the example against a simulator (DroneKit-SITL) by specifying the Python script without any arguments. The example will download SITL binaries (if needed), start the simulator, and then connect to it:
On the command prompt you should see (something like):
Starting copter simulator (SITL) SITL already Downloaded. Connecting to vehicle on: tcp:127.0.0.1:5760 >>> APM:Copter V3.3 (d6053245) >>> Frame: QUAD >>> Calibrating barometer >>> Initialising APM... >>> barometer calibration complete >>> GROUND START >>> Mission Planner 1.3.35 Create a new mission (for current location) Clear any existing commands Define/add new commands. Upload new commands to vehicle Basic pre-arm checks Waiting for vehicle to initialise... >>> flight plan received Waiting for vehicle to initialise... ... Waiting for vehicle to initialise... Arming motors Waiting for arming... ... Waiting for arming... >>> ARMING MOTORS >>> GROUND START Waiting for arming... >>> Initialising APM... Taking off! Altitude: 0.0 Altitude: 0.11 ... Altitude: 8.9 Altitude: 9.52 Reached target altitude Starting mission Distance to waypoint (0): None Distance to waypoint (1): 78.8000191616 Distance to waypoint (1): 78.3723704927 ... Distance to waypoint (1): 20.7131390269 Distance to waypoint (1): 15.4196151863 >>> Reached Command #1 Distance to waypoint (2): 115.043560356 Distance to waypoint (2): 117.463458185 ... Distance to waypoint (2): 25.7122243168 Distance to waypoint (2): 16.8624794106 >>> Reached Command #2 Distance to waypoint (3): 100.45231832 Skipping to Waypoint 5 when reach waypoint 3 Distance to waypoint (5): 154.645144788 Exit 'standard' mission when start heading to final waypoint (5) Return to launch Close vehicle object
It is more interesting to watch the example run on a map than the console. The topic Connecting an additional Ground Station explains how to set up Mission Planner to view a vehicle running on the simulator (SITL).
You can run the example against a specific connection (simulated or otherwise) by passing the connection string for your vehicle in the
For example, to connect to SITL running on UDP port 14550 on your local computer:
python mission_basic.py --connect 127.0.0.1:14550
In overview, the example calls
adds_square_mission(vehicle.location.global_frame,50) to first
clear the current mission and then define a new mission with a takeoff command and four waypoints arranged
in a square around the central position (two waypoints are added in the last position -
next to determine when we’ve reached the final point).
The clear command and new mission items are then uploaded to the vehicle.
After taking off (in guided mode using the
takeoff() function) the example starts the mission by setting the mode to AUTO:
print "Starting mission" # Set mode to AUTO to start mission vehicle.mode = VehicleMode("AUTO")
The progress of the mission is monitored in a loop. The convenience function
gets the distance to the next waypoint and
Vehicle.commands.next gets the value of
the next command.
We also show how to jump to a specified command using
Vehicle.commands.next (note how we skip the third command below):
while True: nextwaypoint=vehicle.commands.next print 'Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()) if nextwaypoint==3: #Skip to next waypoint print 'Skipping to Waypoint 5 when reach waypoint 3' vehicle.commands.next=5 vehicle.commands.upload() if nextwaypoint==5: #Dummy waypoint - as soon as we reach waypoint 4 this is true and we exit. print "Exit 'standard' mission when start heading to final waypoint (5)" break; time.sleep(1)
When the vehicle starts the 5th command (a dummy waypoint) the loop breaks and the mode is set to RTL (return to launch).
This example has no known issues.
The full source code at documentation build-time is listed below (current version on Github):
#!/usr/bin/env python # -*- coding: utf-8 -*- """ © Copyright 2015-2016, 3D Robotics. mission_basic.py: Example demonstrating basic mission operations including creating, clearing and monitoring missions. Full documentation is provided at http://python.dronekit.io/examples/mission_basic.html """ from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command import time import math from pymavlink import mavutil #Set up option parsing to get connection string import argparse parser = argparse.ArgumentParser(description='Demonstrates basic mission operations.') parser.add_argument('--connect', help="vehicle connection target string. If not specified, SITL automatically started and used.") args = parser.parse_args() connection_string = args.connect sitl = None #Start SITL if no connection string specified if not connection_string: import dronekit_sitl sitl = dronekit_sitl.start_default() connection_string = sitl.connection_string() # Connect to the Vehicle print 'Connecting to vehicle on: %s' % connection_string vehicle = connect(connection_string, wait_ready=True) def get_location_metres(original_location, dNorth, dEast): """ Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the specified `original_location`. The returned Location has the same `alt` value as `original_location`. The function is useful when you want to move the vehicle around specifying locations relative to the current vehicle position. The algorithm is relatively accurate over small distances (10m within 1km) except close to the poles. For more information see: http://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters """ earth_radius=6378137.0 #Radius of "spherical" earth #Coordinate offsets in radians dLat = dNorth/earth_radius dLon = dEast/(earth_radius*math.cos(math.pi*original_location.lat/180)) #New position in decimal degrees newlat = original_location.lat + (dLat * 180/math.pi) newlon = original_location.lon + (dLon * 180/math.pi) return LocationGlobal(newlat, newlon,original_location.alt) def get_distance_metres(aLocation1, aLocation2): """ Returns the ground distance in metres between two LocationGlobal objects. This method is an approximation, and will not be accurate over large distances and close to the earth's poles. It comes from the ArduPilot test code: https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py """ dlat = aLocation2.lat - aLocation1.lat dlong = aLocation2.lon - aLocation1.lon return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5 def distance_to_current_waypoint(): """ Gets distance in metres to the current waypoint. It returns None for the first waypoint (Home location). """ nextwaypoint = vehicle.commands.next if nextwaypoint==0: return None missionitem=vehicle.commands[nextwaypoint-1] #commands are zero indexed lat = missionitem.x lon = missionitem.y alt = missionitem.z targetWaypointLocation = LocationGlobalRelative(lat,lon,alt) distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation) return distancetopoint def download_mission(): """ Download the current mission from the vehicle. """ cmds = vehicle.commands cmds.download() cmds.wait_ready() # wait until download is complete. def adds_square_mission(aLocation, aSize): """ Adds a takeoff command and four waypoint commands to the current mission. The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation). The function assumes vehicle.commands matches the vehicle mission state (you must have called download at least once in the session and after clearing the mission) """ cmds = vehicle.commands print " Clear any existing commands" cmds.clear() print " Define/add new commands." # Add new commands. The meaning/order of the parameters is documented in the Command class. #Add MAV_CMD_NAV_TAKEOFF command. This is ignored if the vehicle is already in the air. cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, 0, 10)) #Define the four MAV_CMD_NAV_WAYPOINT locations and add the commands point1 = get_location_metres(aLocation, aSize, -aSize) point2 = get_location_metres(aLocation, aSize, aSize) point3 = get_location_metres(aLocation, -aSize, aSize) point4 = get_location_metres(aLocation, -aSize, -aSize) cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point1.lat, point1.lon, 11)) cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point2.lat, point2.lon, 12)) cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point3.lat, point3.lon, 13)) cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point4.lat, point4.lon, 14)) #add dummy waypoint "5" at point 4 (lets us know when have reached destination) cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point4.lat, point4.lon, 14)) print " Upload new commands to vehicle" cmds.upload() def arm_and_takeoff(aTargetAltitude): """ Arms vehicle and fly to aTargetAltitude. """ print "Basic pre-arm checks" # Don't let the user try to arm until autopilot is ready while not vehicle.is_armable: print " Waiting for vehicle to initialise..." time.sleep(1) print "Arming motors" # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True while not vehicle.armed: print " Waiting for arming..." time.sleep(1) print "Taking off!" vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command # after Vehicle.simple_takeoff will execute immediately). while True: print " Altitude: ", vehicle.location.global_relative_frame.alt if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. print "Reached target altitude" break time.sleep(1) print 'Create a new mission (for current location)' adds_square_mission(vehicle.location.global_frame,50) # From Copter 3.3 you will be able to take off using a mission item. Plane must take off using a mission item (currently). arm_and_takeoff(10) print "Starting mission" # Reset mission set to first (0) waypoint vehicle.commands.next=0 # Set mode to AUTO to start mission vehicle.mode = VehicleMode("AUTO") # Monitor mission. # Demonstrates getting and setting the command number # Uses distance_to_current_waypoint(), a convenience function for finding the # distance to the next waypoint. while True: nextwaypoint=vehicle.commands.next print 'Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()) if nextwaypoint==3: #Skip to next waypoint print 'Skipping to Waypoint 5 when reach waypoint 3' vehicle.commands.next = 5 if nextwaypoint==5: #Dummy waypoint - as soon as we reach waypoint 4 this is true and we exit. print "Exit 'standard' mission when start heading to final waypoint (5)" break; time.sleep(1) print 'Return to launch' vehicle.mode = VehicleMode("RTL") #Close vehicle object before exiting script print "Close vehicle object" vehicle.close() # Shut down simulator if it was started. if sitl is not None: sitl.stop()