Compatibility of dronekit python with Ardupilot APM mega

Can i run dronekit python codes with ardupilot apm mega?

yes you can. but maybe a couple of features will not work

Will GPS waypoint naigation , set attitude commands work??

yes, it will work. if not post questions here

Can this code works with APM mega and dronekit
"""
© Copyright 2015-2016, 3D Robotics.
mission_import_export.py:

This example demonstrates how to import and export files in the Waypoint file format
(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). The commands are imported
into a list, and can be modified before saving and/or uploading.

Documentation is provided at http://python.dronekit.io/examples/mission_import_export.html
"""
from future import print_function

from dronekit import connect, Command, VehicleMode
from pymavlink import mavutil
import time
import math

#Set up option parsing to get connection string
import argparse
parser = argparse.ArgumentParser(description=‘Demonstrates mission import/export from a file.’)
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 args.connect:
print(“Starting copter simulator (SITL)”)
from dronekit_sitl import SITL
sitl = SITL()
sitl.download(‘copter’, ‘3.3’, verbose=True)
sitl_args = [’-I0’, ‘–model’, ‘quad’, ‘–home=-35.363261,149.165230,584,353’]
sitl.launch(sitl_args, await_ready=True, restart=True)
connection_string=‘tcp:127.0.0.1:5760’

Connect to the Vehicle

print(‘Connecting to vehicle on: %s’ % connection_string)
vehicle = connect(connection_string, wait_ready=True)

Check that vehicle is armable.

This ensures home_location is set (needed when saving WP file)

while not vehicle.is_armable:
print(" Waiting for vehicle to initialise…")
time.sleep(1)

def update_me(name_of_file):
cmds = vehicle.commands
cmds.download()
cmds.wait_ready()
print(" Home Location: %s" % vehicle.home_location)
file=open(name_of_file,“r”)
st=file.readline()
st1=st
while st1 != “”:
st=st1
st1=file.readline()
print(st)
ary=st.split("\t")
ary[8]= vehicle.home_location.lat
ary[9]= vehicle.home_location.lon
ary[10]= vehicle.home_location.alt
print(ary)
l=ary[0]
l=int(l)
ary[0]=str(l+1)
file.close()
file=open(name_of_file,“a”)
ss=(’\t’.join([str(x) for x in ary]))
file.write(ss)
file.close()
def readmission(aFileName):
"""
Load a mission from a file into a list. The mission definition is in the Waypoint file
format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).

This function is used by upload_mission().
"""
print("\nReading mission from file: %s" % aFileName)
cmds = vehicle.commands
missionlist=[]
with open(aFileName) as f:
    for i, line in enumerate(f):
        if i==0:
            if not line.startswith('QGC WPL 110'):
                raise Exception('File is not supported WP version')
        else:
            linearray=line.split('\t')
            ln_index=int(linearray[0])
            ln_currentwp=int(linearray[1])
            ln_frame=int(linearray[2])
            ln_command=int(linearray[3])
            ln_param1=float(linearray[4])
            ln_param2=float(linearray[5])
            ln_param3=float(linearray[6])
            ln_param4=float(linearray[7])
            ln_param5=float(linearray[8])
            ln_param6=float(linearray[9])
            ln_param7=float(linearray[10])
            ln_autocontinue=int(linearray[11].strip())
            cmd = Command( 0, 0, 0, ln_frame, ln_command, ln_currentwp, ln_autocontinue, ln_param1, ln_param2, ln_param3, ln_param4, ln_param5, ln_param6, ln_param7)
            missionlist.append(cmd)
print(len(missionlist))
return missionlist

def upload_mission(aFileName):
""“
Upload a mission from a file.
”""
#Read mission from file
missionlist = readmission(aFileName)

print("\nUpload mission from a file: %s" % aFileName)
#Clear existing mission from vehicle
print(' Clear mission')
cmds = vehicle.commands
cmds.clear()
#Add new mission to vehicle
for command in missionlist:
    cmds.add(command)
print(' Upload mission')
vehicle.commands.upload()

def download_mission():
""“
Downloads the current mission and returns it in a list.
It is used in save_mission() to get the file information to save.
”"“
print(” Download mission from vehicle")
missionlist=[]
cmds = vehicle.commands
cmds.download()
cmds.wait_ready()
for cmd in cmds:
missionlist.append(cmd)
return missionlist

def save_mission(aFileName):
""“
Save a mission in the Waypoint file format
(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
”"“
print(”\nSave mission from Vehicle to file: %s" % export_mission_filename)
#Download mission from vehicle
missionlist = download_mission()
#Add file-format information
output=‘QGC WPL 110\n’
#Add home location as 0th waypoint
home = vehicle.home_location
output+="%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (0,1,0,16,0,0,0,0,home.lat,home.lon,home.alt,1)
#Add commands
for cmd in missionlist:
commandline="%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (cmd.seq,cmd.current,cmd.frame,cmd.command,cmd.param1,cmd.param2,cmd.param3,cmd.param4,cmd.x,cmd.y,cmd.z,cmd.autocontinue)
output+=commandline
with open(aFileName, ‘w’) as file_:
print(" Write mission to file")
file_.write(output)

def printfile(aFileName):
""“
Print a mission file to demonstrate “round trip”
”"“
print(”\nMission file: %s" % aFileName)
with open(aFileName) as f:
for line in f:
print(’ %s’ % line.strip())
def set_velocity_body(vehicle, vx, vy, vz):
""" Remember: vz is positive downward!!!
http://ardupilot.org/dev/docs/copter-commands-in-guided-mode.html

Bitmask to indicate which dimensions should be ignored by the vehicle 
(a value of 0b0000000000000000 or 0b0000001000000000 indicates that 
none of the setpoint dimensions should be ignored). Mapping: 
bit 1: x,  bit 2: y,  bit 3: z, 
bit 4: vx, bit 5: vy, bit 6: vz, 
bit 7: ax, bit 8: ay, bit 9:


"""
msg = vehicle.message_factory.set_position_target_local_ned_encode(
        0,
        0, 0,
        mavutil.mavlink.MAV_FRAME_BODY_NED,
        0b0000111111000111, #-- BITMASK -> Consider only the velocities
        0, 0, 0,        #-- POSITION
        vx, vy, vz,     #-- VELOCITY
        0, 0, 0,        #-- ACCELERATIONS
        0, 0)
vehicle.send_mavlink(msg)
vehicle.flush()

def drone_response_req():

cmds = vehicle.commands
import_mission_filename = 'mpmission.txt'
    
#Upload mission from file
upload_mission(import_mission_filename)

#Close vehicle object before exiting script
vehicle.mode    = VehicleMode("GUIDED")
vehicle.armed   = True
vehicle.flush()

while not vehicle.armed:
    print(" Waiting for arming...")
    time.sleep(1)

print("Taking off!")
aTargetAltitude=10
vehicle.simple_takeoff(aTargetAltitude)  # Take off to target altitude
gnd_speed=20

# 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)
    # Break and return from function just below target altitude.
    if vehicle.location.global_relative_frame.alt >= aTargetAltitude * 0.95:
        print("Reached target altitude")
        break
    time.sleep(1) # Take off to target altitude
vehicle.flush()
print("Starting mission")
# Set mode to AUTO to start mission
vehicle.mode = VehicleMode("AUTO")
while True:
	me=raw_input("y/n")
	if me == "y":
		vehicle.mode=VehicleMode("GUIDED")
		set_velocity_body(vehicle, 0, -gnd_speed, 0)    		
	time.sleep(1)
else:
	vehicle.mode=VehicleMode("AUTO")

		
vehicle.flush()
print("Close vehicle object")
vehicle.close()

# Shut down simulator if it was started.
if sitl is not None:
    sitl.stop()

#update_me(“mpmission.txt”)
drone_response_req()

Yes, it should work… What does not work for you ?