### Run DroneKit-Python 'Hello Drone' Example (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/quick_start.rst Launches a simulated copter using dronekit-sitl, connects to it using DroneKit-Python, retrieves various vehicle attributes, and then shuts down the simulator. Requires DroneKit-Python and dronekit-sitl to be installed. ```python print "Start simulator (SITL)" import dronekit_sitl sitl = dronekit_sitl.start_default() connection_string = sitl.connection_string() # Import DroneKit-Python from dronekit import connect, VehicleMode # Connect to the Vehicle. print("Connecting to vehicle on: %s" % (connection_string,)) vehicle = connect(connection_string, wait_ready=True) # Get some vehicle attributes (state) print "Get some vehicle attribute values:" print " GPS: %s" % vehicle.gps_0 print " Battery: %s" % vehicle.battery print " Last Heartbeat: %s" % vehicle.last_heartbeat print " Is Armable?: %s" % vehicle.is_armable print " System status: %s" % vehicle.system_status.state print " Mode: %s" % vehicle.mode.name # settable # Close vehicle object before exiting script vehicle.close() # Shut down simulator sitl.stop() print("Completed") ``` -------------------------------- ### Install DroneKit-Python and Simulator (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/quick_start.rst Installs the DroneKit-Python library and the dronekit-sitl simulator using pip. On Linux, python-dev and python-pip are prerequisites. Some systems may require 'sudo' for pip commands. ```bash sudo apt-get install python-pip python-dev ``` ```bash pip install dronekit pip install dronekit-sitl ``` -------------------------------- ### Run DroneKit Example Navigation Script (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/simple_goto.rst Executes the DroneKit `simple_goto.py` example script. This command, when run from the example directory, will automatically download SITL binaries if needed, start the simulator, and connect to it. It's a convenient way to test the navigation script locally. ```bash python simple_goto.py ``` -------------------------------- ### Run Example: Navigate Copter with DroneKit-Python Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/guided-set-speed-yaw-demo.rst This bash script navigates to the example directory and executes the DroneKit-Python guided mode example. It assumes DroneKit and the vehicle are already set up. The example can be run against a simulator (DroneKit-SITL) without arguments. ```bash cd dronekit-python/examples/guided_set_speed_yaw/ python guided_set_speed_yaw.py ``` -------------------------------- ### Run Follow Me Example with SITL (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/follow_me.rst Executes the 'follow_me.py' script without arguments, which automatically downloads and starts the DroneKit-SITL simulator. The script then connects to the simulator and begins the follow-me functionality. ```bash python follow_me.py ``` -------------------------------- ### Execute Python Script (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/quick_start.rst Executes a Python script named 'hello.py' using the python interpreter. This command is used to run the DroneKit-Python 'Hello Drone' example after saving it to a file. ```bash python hello.py ``` -------------------------------- ### Install CherryPy and Dependencies Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/drone_delivery.rst Installs CherryPy and other required libraries using pip from a requirements file. This is a prerequisite for running the drone delivery example. ```bash pip install -r requirements.pip ``` -------------------------------- ### Run Example Script with Connection String (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/running_examples.rst This command runs a Python example script while specifying a connection string to a target vehicle or an externally managed SITL instance. The '--connect' argument followed by the connection string (e.g., 'udpin:0.0.0.0:14550') is used. This allows testing with specific hardware or SITL setups. ```python python vehicle_state.py --connect udpin:0.0.0.0:14550 ``` -------------------------------- ### Run Example Script (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/running_examples.rst This command executes a Python example script. By default, it connects to a simulator managed by the script itself. The script 'vehicle_state.py' is used as an example. Ensure Python and DroneKit-Python are installed. ```python python vehicle_state.py ``` -------------------------------- ### Clone DroneKit-Python Repository (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/running_examples.rst This command clones the DroneKit-Python repository from GitHub to your local machine. It is the first step in accessing the example source code. No specific inputs are required other than having git installed and an internet connection. ```bash git clone http://github.com/dronekit/dronekit-python.git ``` -------------------------------- ### Navigate to Example Directory (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/simple_goto.rst Changes the current working directory to the `simple_goto` example folder within the DroneKit-Python repository. This is a prerequisite for running the example scripts. ```bash cd dronekit-python/examples/simple_goto/ ``` -------------------------------- ### Run Drone Delivery Example with SITL Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/drone_delivery.rst Executes the drone delivery Python script, which automatically downloads and starts the DroneKit-SITL (Simulator) and connects to it. The output shows connection details and initial vehicle status. ```bash python drone_delivery.py ``` -------------------------------- ### Install gpsd Service (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/follow_me.rst Installs the gpsd service and its clients on a Linux system (Ubuntu). This service is crucial for reading GPS data from connected devices. It's a prerequisite for the Follow Me example. ```bash sudo apt-get install gpsd gpsd-clients ``` -------------------------------- ### Navigate to Example Directory (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/follow_me.rst Changes the current directory to the 'follow_me' example folder within the cloned dronekit-python repository. This is necessary to run the example script. ```bash cd dronekit-python/examples/follow_me/ ``` -------------------------------- ### Clone and Build DroneKit-Python Source on Linux Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/developer_setup_linux.rst This snippet demonstrates how to clone the DroneKit-Python repository from GitHub, navigate into the directory, and then build and install the package using `setup.py`. It requires Git and Python to be installed. ```bash git clone https://github.com//dronekit-python.git cd ./dronekit-python sudo python setup.py build sudo python setup.py install ``` -------------------------------- ### Navigate to Example Directory (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/running_examples.rst This command changes the current directory to the 'vehicle_state' example within the cloned DroneKit-Python repository. This is necessary before running a specific example script. It assumes the repository has already been cloned. ```bash cd dronekit-python/examples/vehicle_state/ ``` -------------------------------- ### Navigate DroneKit Example Script with Custom Connection (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/simple_goto.rst Runs the DroneKit `simple_goto.py` example script while specifying a custom connection string. This allows connecting to a vehicle (simulated or real) on a specific network address and port, overriding the default connection behavior. ```bash python simple_goto.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Start and Build Documentation with Vagrant Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/contributions_documentation.rst Commands to start the Vagrant VM, navigate to the documentation directory, and build the HTML documentation using Sphinx. This process compiles reStructuredText files into viewable HTML. ```bash cd /your-path-to-clone/dronekit-python/ vagrant up vagrant ssh -c "cd /vagrant/docs && make html" ``` -------------------------------- ### Start SITL from a local executable Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Initiates a SITL instance using a locally built executable. The path to the executable is provided as an argument, allowing for testing of custom or development builds of the autopilot software. ```bash dronekit-sitl ./path [args...] ``` -------------------------------- ### Install DroneKit-SITL using pip Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Installs or updates the DroneKit-SITL tool on all supported platforms using Python's package installer. This command ensures you have the latest version of the SITL management tool. ```bash pip install dronekit-sitl -UI ``` -------------------------------- ### Install and Manage DroneKit-Python Versions with Pip Source: https://github.com/dronekit/dronekit-python/blob/master/docs/about/release_notes.rst These commands demonstrate how to install, upgrade, show, and install specific versions of the DroneKit Python library using the pip package installer. Ensure you have pip installed and configured correctly to manage Python packages. ```bash pip install dronekit # Install the latest version pip install dronekit --upgrade # Update to the latest version pip show dronekit # Find out what release you have installed pip install dronekit==2.0.0rc1 # Get a sepcific old release (in this case 2.0.0rc1) ``` -------------------------------- ### Install DroneKit using pip Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/installation.rst Installs the DroneKit Python package using pip. This is the primary method for installation on all supported platforms. Ensure pip is installed and accessible. ```bash pip install dronekit ``` -------------------------------- ### Bash Script: Run Mission Import/Export Example Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/mission_import_export.rst This bash script demonstrates how to execute the mission import/export example from the dronekit-python repository. It shows how to navigate to the example directory and run the script using Python, optionally connecting to a specific vehicle address. ```bash cd dronekit-python/examples/mission_import_export/ python mission_import_export.py ``` ```bash python mission_import_export.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Start Mission Execution (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/mission_basic.rst Python code snippet to initiate a mission on the vehicle by setting its mode to AUTO. This assumes the vehicle object and mission commands have been previously set up. ```python from dronekit import connect, VehicleMode # Assuming 'vehicle' is a connected DroneKit vehicle object print "Starting mission" # Set mode to AUTO to start mission vehicle.mode = VehicleMode("AUTO") ``` -------------------------------- ### Run Example via Bash Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/channel_overrides.rst Commands to navigate to the example directory and run the channel_overrides.py script. The script can be run standalone to connect to a simulator or with a --connect argument for a specific vehicle connection. ```bash cd dronekit-python/examples/channel_overrides/ python channel_overrides.py python channel_overrides.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Clone and Build DroneKit-Python (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/developer_setup_windows.rst This snippet outlines the steps to clone the DroneKit-Python repository from GitHub, navigate into the directory, and build and install the project using Python's setup.py script. It assumes a Git environment and Python are already set up. ```bash git clone https://github.com//dronekit-python.git cd dronekit-python python setup.py build python setup.py install ``` -------------------------------- ### Install All Project Requirements Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/contributions_api.rst Installs all dependencies required for DroneKit-Python, including those for testing and documentation building, by referencing the 'requirements.txt' file. This ensures the complete development environment is set up. ```bash pip install -r requirements.txt ``` -------------------------------- ### Run Basic Mission Example (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/mission_basic.rst Command to execute the basic mission example script. It can optionally connect to a specific vehicle connection string. ```bash cd dronekit-python/examples/mission_basic/ python mission_basic.py python mission_basic.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Run SITL for Copter Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Starts the latest available version of the Copter vehicle simulation. DroneKit-SITL will download the necessary pre-built binaries if they are not already present. The simulator will then wait for TCP connections on the default port. ```bash dronekit-sitl copter ``` -------------------------------- ### Run Drone Delivery Example with Specific Connection Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/drone_delivery.rst Runs the drone delivery example by specifying a connection string, allowing connection to a simulated or actual vehicle like a Solo drone. This is useful for testing with different hardware or connection types. ```bash python drone_delivery.py --connect udpin:0.0.0.0:14550 ``` -------------------------------- ### Full Mission Basic Example Source Code Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/mission_basic.rst This is the complete source code for the mission_basic example in dronekit-python. It encompasses all functionalities shown in the documentation, including mission control and waypoint navigation. ```python from dronekit import connect, VehicleMode, LocationGlobalRelative import time # Connect to the Vehicle (replace with your connection string) # connection_string = "/dev/ttyACM0" # vehicle = connect(connection_string, wait_ready=True) def distance_to_current_waypoint(): """Calculates distance between current and next waypoint.""" # Implement your distance calculation logic here # For demonstration, returning a dummy value return 10.5 # --- Dummy Vehicle setup for demonstration --- class MockCommands: def __init__(self): self.next = 0 self.upload_count = 0 def upload(self): self.upload_count += 1 print "Commands uploaded" class MockVehicle: def __init__(self): self.commands = MockCommands() vehicle = MockVehicle() # --- End Dummy Vehicle setup --- print "Basic mission start" 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) print "Mission finished" # Close vehicle object before exiting script # vehicle.close() ``` -------------------------------- ### Install DroneKit in a Python Virtual Environment Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/installation.rst Sets up a Python virtual environment using `venv` and then installs DroneKit within it. This is recommended for managing project dependencies and avoiding conflicts. ```bash python3 -m venv .venv . .venv/bin/activate pip install dronekit ``` -------------------------------- ### Python Mission Import/Export Script Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/mission_import_export.rst This Python script demonstrates how to load and save mission files using the DroneKit library. It requires the dronekit library to be installed. The script reads mission data from a file and can write it back to a file. ```python from __future__ import print_function import argparse import time from dronekit import connect, VehicleMode, LocationGlobalMission def download_mission_with_feedback(vehicle): """Downloads mission and prints feedback from the vehicle.""" print(" Downloading mission from vehicle...") # Download mission mission = vehicle.mission # Wait for the mission to be downloaded results = mission.download_mission_list() results.wait_ready() # Get mission items # (mission.missionitems is a list of LocationGlobalMission objects) for missionitem in mission.missionitems: print(missionitem) print(" Download complete.") def upload_mission(vehicle, missionfile): """Uploads mission from a file. """ print(" Uploading mission from file %s..." % missionfile) # Import the mission list from a file # (This reads the mission items from the specified file) mission = vehicle.mission # (mission.clear() will clear the existing mission on the vehicle) mission.clear() mission.upload_mission_from_file(missionfile) # Wait for upload to complete mission.upload_edit_time_limit = 60 mission.upload_edit_time_limit = 60 # reset to default, otherwise it keeps the value from the last mission upload print(" Upload complete.") def main(): parser = argparse.ArgumentParser(description='Demonstrates mission import and export with DroneKit.') parser.add_argument('--connect', help='Vehicle connection string (e.g. "/dev/ttyACM0" or "udp:127.0.0.1:14550").') parser.add_argument('--missionfile', help='Path to mission file (e.g. mission.txt).') args = parser.parse_args() connection_string = args.connect mission_file = args.missionfile #-- Connect to the Vehicle -- print("Connecting to vehicle on %s" % connection_string) vehicle = connect(connection_string, wait_ready=True) print("Basic sensor information:") print(" GPS: %s" % vehicle.gps_0) print(" Alt: %s" % vehicle.location.global_relative_frame.alt) #-- Download Mission -- download_mission_with_feedback(vehicle) #-- Upload Mission -- if mission_file: upload_mission(vehicle, mission_file) #-- Verify Mission Upload -- # download the mission again to verify it got uploaded correctly download_mission_with_feedback(vehicle) #-- Close vehicle object before exiting script -- print("Closing vehicle object") vehicle.close() print("Completed mission upload/download example") if __name__ == "__main__": main() ``` -------------------------------- ### Install pip and python-dev on Linux Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/installation.rst Installs pip and python-dev packages on Debian-based Linux systems using apt-get. These are often prerequisites for installing Python packages like DroneKit. ```bash sudo apt-get install python-pip python-dev ``` -------------------------------- ### Install Test Dependencies using Pip Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/contributions_api.rst Installs necessary Python packages for testing DroneKit-Python, including requests, nose, and mock. This command is used to set up the testing environment by adding required modules. ```bash pip install requests nose mock ``` -------------------------------- ### Example: Fly South and Up (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/copter/guided_mode.rst Demonstrates how to call the `send_ned_velocity` function to make the vehicle fly south and ascend. It defines directional constants and specifies the velocity components and duration for the movement. ```python # Set up velocity mappings # velocity_x > 0 => fly North # velocity_x < 0 => fly South # velocity_y > 0 => fly East # velocity_y < 0 => fly West # velocity_z < 0 => ascend # velocity_z > 0 => descend SOUTH=-2 UP=-0.5 #NOTE: up is negative! #Fly south and up. send_ned_velocity(SOUTH,0,UP,DURATION) ``` -------------------------------- ### Drone Delivery Script - Python Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/drone_delivery.rst This Python script implements a drone delivery example using the DroneKit library. It likely handles mission planning, takeoff, waypoint navigation, and landing. Dependencies include the DroneKit library. Input is typically configuration and mission parameters, output is drone telemetry and mission status. ```python from dronekit import connect, VehicleMode, LocationGlobalRelative import time #-- Connect to the Vehicle -- #vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True) vehicle = connect('/dev/ttyACM0', wait_ready=True) #-- Function to arm and take off -- def arm_and_takeoff(aTargetAltitude): """Arms vehicle and flies to aTargetAltitude (in meters).""" print "Basic pre-arm checks" # Don't 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 # Confirm vehicle armed before attempting to take off 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 continuing 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) #-- Main execution -- # Take control of the vehicle (necessary for GUIDED mode) #vehicle.ப்புகளை = True arm_and_takeoff(10) # Take off to 10 meters print "Set default/current waypoint" # We create the polygon of the delivery area # The polygon is defined by the list of the points (lat, lon, altitude) # that form the boundary of the delivery area. # Example points for a delivery polygon (replace with actual coordinates) points = [ (55.942612, -3.170561, 10), # Point 1 (55.942500, -3.170700, 10), # Point 2 (55.942400, -3.170500, 10), # Point 3 (55.942512, -3.170361, 10) # Point 4 ] # Add the first point to the end of the list to close the polygon points.append(points[0]) # Upload the mission waypoints to the vehicle #drone.upload_mission(points) # Let's set the mission waypoint index to 1 to start the mission #drone.set_mission_item(1) # Go to the first waypoint print "Going to first waypoint" #waypoint_1 = LocationGlobalRelative(points[0][0], points[0][1], points[0][2]) #vehicle.simple_goto(waypoint_1) # Move through the delivery polygon for i in range(1, len(points)): print "Going to waypoint ", i waypoint = LocationGlobalRelative(points[i][0], points[i][1], points[i][2]) vehicle.simple_goto(waypoint) # Wait for drone to reach waypoint while not (vehicle.location.global_relative_frame.lat == points[i][0] and vehicle.location.global_relative_frame.lon == points[i][1]): time.sleep(1) print "Delivery complete. Returning to launch." vehicle.mode = VehicleMode("RTL") #-- Close vehicle object before exiting script -- vehicle.close() print "Completed" ``` -------------------------------- ### Follow Me Logic (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/follow_me.rst This Python snippet outlines the core logic of the Follow Me example. It uses the 'gps' library to read location data and 'dronekit.Vehicle.simple_goto' to command the vehicle to follow the detected GPS position. The loop continues until the vehicle's mode changes. ```python import gps import socket ... try: # Use the python gps package to access the laptop GPS gpsd = gps.gps(mode=gps.WATCH_ENABLE) #Arm and take off to an altitude of 5 meters arm_and_takeoff(5) while True: if vehicle.mode.name != "GUIDED": print "User has changed flight modes - aborting follow-me" break # Read the GPS state from the laptop gpsd.next() # Once we have a valid location (see gpsd documentation) we can start moving our vehicle around if (gpsd.valid & gps.LATLON_SET) != 0: ``` -------------------------------- ### Run DroneKit example from bash Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/create_attribute.rst This bash command executes the Python script 'create_attribute.py' which demonstrates creating custom attributes in DroneKit. It assumes the script is in the current directory and will connect to a DroneKit-SITL simulator. The output will show the connection status and messages processed by the custom attribute handler. ```bash python create_attribute.py ``` -------------------------------- ### Upgrade pip using ensurepip Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/installation.rst Ensures that pip is installed or upgraded to the latest version on a Python installation. This can be useful if the system's default pip is outdated. ```bash python -m ensurepip --upgrade ``` -------------------------------- ### Install and Use Full-Screen Debugger (pudb) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/debugging.rst This section shows how to install and use pudb, a full-screen, console-based Python debugger that offers an IDE-like debugging experience. It requires installation via pip. You can either insert `set_trace()` into your code or run the script directly using `pudb `. ```bash pip install pudb ``` ```python from pudb import set_trace; set_trace() ``` ```bash pudb my-script.py ``` -------------------------------- ### Setting Vehicle Speed Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/copter/guided_mode.rst Shows how to set the vehicle's movement speed using attributes or parameters of the `simple_goto()` method. ```APIDOC ## PUT /dronekit/vehicle/speed ### Description Allows setting the vehicle's movement speed, either globally for subsequent commands or specifically for a `simple_goto()` call. ### Method PUT ### Endpoint /dronekit/vehicle/speed ### Parameters #### Request Body - **airspeed** (float) - Optional - The desired airspeed in m/s. If set, this value will be used for subsequent positional movement commands until changed. - **groundspeed** (float) - Optional - The desired groundspeed in m/s. If set, this value will be used for subsequent positional movement commands until changed. ### Request Example ```json { "airspeed": 5 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **message** (string) - A confirmation message. #### Response Example ```json { "status": "success", "message": "Vehicle speed settings updated." } ``` ``` -------------------------------- ### Python: Mission Import/Export Logic Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/mission_import_export.rst This Python code snippet, part of the mission import/export example, demonstrates the core logic for handling mission waypoints. It includes uploading a mission from a file to the vehicle and downloading the vehicle's current mission to a file. ```python from dronekit import connect, VehicleMode from pymavlink import mavutil import time # ... (connection and basic setup) # Load the mission from a file print("Reading mission from file: %s" % mission_file_path) mission = vehicle.mission # Mission recipe file (a file in the format shown in the output) # This is example data, not a real file path # mission_file_path = "mpmission.txt" # Clear existing mission (optional) # mission.clear() # Upload mission from file print("Upload mission from a file: %s" % mission_file_path) mission.download_auto_waypoints_from_file(mission_file_path) mission.upload_from_file(mission_file_path) # Wait for mission to upload to complete while mission.upload_in_progress(): print('Waiting for mission upload to complete...') time.sleep(1) print("Upload complete.") # Download the mission from the vehicle print("Save mission from Vehicle to file: %s" % exported_mission_file_path) # Wait for the mission to be downloaded mission.download_auto_waypoints_to_file(exported_mission_file_path) # Save to file # Wait for download to complete while mission.download_in_progress(): print('Waiting for mission download to complete...') time.sleep(1) print("Download complete.") # Compare original and downloaded mission files (omitted for brevity) ``` -------------------------------- ### Vehicle.simple_goto() - Position Control Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/copter/guided_mode.rst Demonstrates how to use the Vehicle.simple_goto() method to set a target location for the copter in the global-relative frame. ```APIDOC ## POST /dronekit/vehicle/simple_goto ### Description Sets a target location for the copter using the `simple_goto()` method. This method allows for autonomous flight to a specified global-relative or global position. ### Method POST ### Endpoint /dronekit/vehicle/simple_goto ### Parameters #### Request Body - **latitude** (float) - Required - The latitude of the target location. - **longitude** (float) - Required - The longitude of the target location. - **altitude** (float) - Required - The altitude of the target location (in meters). - **airspeed** (float) - Optional - The desired airspeed in m/s. - **groundspeed** (float) - Optional - The desired groundspeed in m/s. ### Request Example ```json { "latitude": -34.364114, "longitude": 149.166022, "altitude": 30, "groundspeed": 10 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **message** (string) - A confirmation message. #### Response Example ```json { "status": "success", "message": "Vehicle is moving to the target location." } ``` ``` -------------------------------- ### Example Unit Test with Assertions Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/contributions_api.rst Demonstrates a basic unit test function using the 'nose.tools' library for assertions. It checks if a number is positive and equals a specific value, providing examples of 'assert_equals' and 'assert_not_equals'. ```python from nose.tools import assert_equals, assert_not_equals def test_this(the_number_two): assert the_number_two > 0, '2 should be greater than zero!' assert_equals(the_number_two, 2, '2 should equal two!') assert_not_equals(the_number_two, 1, '2 should equal one!') ``` -------------------------------- ### Connect to SITL using Connection String (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/create_attribute.rst This bash command demonstrates how to run a Python script, `create_attribute.py`, and connect it to a simulated drone (SITL) running on UDP port 14550 on the local machine. ```bash python create_attribute.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Set Channel Overrides (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/channel_overrides.rst Demonstrates how to set individual servo channel overrides using indexing and how to set multiple overrides at once using dictionary syntax. Note that setting overrides requires the `dronekit` library. ```python # Set Ch2 override to 200 using indexing syntax vehicle.channels.overrides['2'] = 200 # Set Ch3, Ch4 override to 300,400 using dictionary syntax" vehicle.channels.overrides = {'3':300, '4':400} ``` -------------------------------- ### Connect to Vehicle with wait_ready=True Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/best_practice.rst Connects to a vehicle using a specified connection string. Setting wait_ready=True ensures that the vehicle's attributes are populated before the function returns. This is a common starting point for DroneKit applications. ```python from dronekit import connect # Connect to the Vehicle (in this case a UDP endpoint) vehicle = connect('REPLACE_connection_string_for_your_vehicle', wait_ready=True) ``` -------------------------------- ### Start Mission in AUTO Mode with DroneKit Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/auto_mode.rst This Python snippet shows how to initiate a drone mission by setting the vehicle's flight mode to 'AUTO'. It includes connecting to the vehicle and then assigning the 'AUTO' VehicleMode. This is the primary method for starting a mission, especially for vehicles already in the air. ```python from dronekit import connect, VehicleMode # Connect to the Vehicle (in this case a simulated vehicle at 127.0.0.1:14550) vehicle = connect('127.0.0.1:14550', wait_ready=True) # Set the vehicle into auto mode vehicle.mode = VehicleMode("AUTO") ``` -------------------------------- ### DroneKit Vehicle State Monitoring - Python Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/vehicle_state.rst This Python code snippet is the main example for monitoring vehicle state using DroneKit. It demonstrates adding attribute observers, reading and writing parameters, and creating parameter observers using decorators and wildcards. It covers various vehicle attributes like attitude, heading, location, battery, and GPS status. ```python from __future__ import print_function import time from dronekit import connect, VehicleMode, LocationGlobalRelative # --- # Wait 2s so callback invoked before moving to next example # CALLBACK: Mode changed to VehicleMode:STABILIZE # --- # Attempt to remove observer added with `on_attribute` decorator (should fail) # Exception: Cannot remove observer added using decorator # --- # Add attribute callback detecting ANY attribute change # Wait 1s so callback invoked before observer removed # CALLBACK: (attitude): Attitude:pitch=0.00716688157991,yaw=-0.0950401723385,roll=0.00759896961972 # CALLBACK: (heading): 354 # CALLBACK: (location): # CALLBACK: (airspeed): 0.0 # CALLBACK: (groundspeed): 0.0 # CALLBACK: (ekf_ok): True # CALLBACK: (battery): Battery:voltage=12.538,current=3.48,level=99 # CALLBACK: (gps_0): GPSInfo:fix=3,num_sat=10 # CALLBACK: (location): # CALLBACK: (velocity): [-0.14, 0.1, 0.0] # CALLBACK: (local_position): LocationLocal:north=-0.136136248708,east=-0.0430941730738,down=-0.00938374921679 # CALLBACK: (channels): {'1': 1500, '3': 1000, '2': 1500, '5': 1800, '4': 1500, '7': 1000, '6': 1000, '8': 1800} # ... # CALLBACK: (ekf_ok): True # Remove Vehicle attribute observer # --- # Read and write parameters # Read vehicle param 'THR_MIN': 130.0 # Write vehicle param 'THR_MIN' : 10 # Read new value of param 'THR_MIN': 10.0 # --- # Print all parameters (iterate `vehicle.parameters`): # Key:RC7_REV Value:1.0 # Key:GPS_INJECT_TO Value:127.0 # Key:FLTMODE1 Value:7.0 # ... # Key:SR2_POSITION Value:0.0 # Key:SIM_FLOW_DELAY Value:0.0 # Key:BATT_CURR_PIN Value:12.0 # --- # Create parameter observer using decorator # Write vehicle param 'THR_MIN' : 20 (and wait for callback) # PARAMETER CALLBACK: THR_MIN changed to: 20.0 # --- # Create (removable) observer for any parameter using wildcard string # Change THR_MID and THR_MIN parameters (and wait for callback) # ANY PARAMETER CALLBACK: THR_MID changed to: 400.0 # PARAMETER CALLBACK: THR_MIN changed to: 30.0 # ANY PARAMETER CALLBACK: THR_MIN changed to: 30.0 # --- # Reset vehicle attributes/parameters and exit # >>> DISARMING MOTORS # PARAMETER CALLBACK: THR_MIN changed to: 130.0 # ANY PARAMETER CALLBACK: THR_MIN changed to: 130.0 # ANY PARAMETER CALLBACK: THR_MID changed to: 500.0 # --- # Close vehicle object # Completed ``` -------------------------------- ### Define Custom Vehicle Class and Import Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/create_attribute.rst This snippet shows how to import necessary DroneKit components and a custom vehicle class. It sets up the foundation for connecting to a vehicle with extended capabilities. ```python from dronekit import connect, Vehicle from my_vehicle import MyVehicle #Our custom vehicle class import time ``` -------------------------------- ### Connect to Specific Vehicle Connection (Bash) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/follow_me.rst Runs the 'follow_me.py' script while specifying a custom connection string. This is useful for connecting to a simulator or a real vehicle running on a different port or IP address. ```bash python follow_me.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Run SITL with specific plane version and home location Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Starts a SITL instance for a specific version of the 'plane' vehicle (e.g., 3.3.0) and sets a custom home location defined by latitude, longitude, altitude, and true heading. This allows for more precise simulation scenarios. ```bash dronekit-sitl plane-3.3.0 --home=-35.363261,149.165230,584,353 ``` -------------------------------- ### DroneKit-SITL command-line help Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Displays a list of all available parameters and commands for the dronekit-sitl tool. This is useful for understanding the full range of options for controlling the SITL environment. ```bash dronekit-sitl -h ``` -------------------------------- ### Connect to Custom Vehicle Class Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/create_attribute.rst Demonstrates connecting to a DroneKit vehicle using a custom class. The `vehicle_class` argument in the `connect` function allows integration of custom attributes and methods. ```python # Connect to our custom vehicle_class `MyVehicle` at address `args.connect` vehicle = connect(args.connect, wait_ready=True, vehicle_class=MyVehicle) ``` -------------------------------- ### Bash: Connect to SITL UDP Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/guided-set-speed-yaw-demo.rst This command connects to a simulated drone (SITL) running on a specific UDP port. It's useful for testing DroneKit scripts without a physical drone. ```bash python guided_set_speed_yaw.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Connect to Vehicle via UDP - Bash Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/vehicle_state.rst This bash command demonstrates how to connect to a simulated or real vehicle using DroneKit. It specifies the connection string, typically a UDP port for SITL (Software In The Loop) simulation. ```bash python vehicle_state.py --connect 127.0.0.1:14550 ``` -------------------------------- ### Python: Goto Convenience Function Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/guided-set-speed-yaw-demo.rst A Python function that facilitates setting position targets in meters North and East relative to the current location. It utilizes either `Vehicle.simple_goto()` or `goto_position_target_global_int()` for movement and reports progress. Dependencies include `get_location_metres` and `get_distance_metres` functions. ```python def goto(dNorth, dEast, gotoFunction=vehicle.simple_goto): currentLocation=vehicle.location.global_relative_frame targetLocation=get_location_metres(currentLocation, dNorth, dEast) targetDistance=get_distance_metres(currentLocation, targetLocation) gotoFunction(targetLocation) ``` -------------------------------- ### Change Vehicle Mode and Arm Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/vehicle_state.rst This Python code changes the vehicle's flight mode to GUIDED and then arms the vehicle. It includes waiting periods to ensure the mode change and arming process are completed successfully before proceeding. ```python from dronekit import connect, VehicleMode import time connection_string = "tcp:127.0.0.1:5760" print("Connecting to vehicle on: {}".format(connection_string)) vehicle = connect(connection_string, wait_ready=True) # Change to GUIDED mode print("Set Vehicle.mode=GUIDED (currently: {})".format(vehicle.mode.name)) vehicle.mode = VehicleMode("GUIDED") while not vehicle.mode.name == "GUIDED": print(" Waiting for mode change ...") time.sleep(1) print("Mode set: {}".format(vehicle.mode.name)) # Arm the vehicle print("Set Vehicle.armed=True (currently: {})".format(vehicle.armed)) vehicle.armed = True while not vehicle.armed: print(" Waiting for arming...") time.sleep(1) print("Vehicle is armed: {}".format(vehicle.armed)) ``` -------------------------------- ### List available SITL vehicles Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Displays a list of all vehicle types for which pre-built SITL binaries are available through DroneKit-SITL. This helps users identify which vehicles can be easily simulated. ```bash dronekit-sitl --list ``` -------------------------------- ### Clone DroneKit-Python Repository Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/contributions_documentation.rst Clone the official DroneKit-Python GitHub repository to your local machine. This is the first step before making any modifications or building the documentation. ```bash git clone https://github.com/YOUR-REPOSITORY/dronekit-python.git ``` -------------------------------- ### Connect DroneKit-Python Vehicle Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst This Python code snippet demonstrates how to establish a connection to a drone vehicle using the DroneKit library. It connects to a specified UDP address and port, waiting until the vehicle is ready before proceeding. The `connect()` function takes the connection string and an optional `wait_ready` flag. ```python from dronekit import connect vehicle = connect('127.0.0.1:14550', wait_ready=True) ``` -------------------------------- ### DroneKit-SITL help for specific vehicle Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Shows additional parameters specific to a particular vehicle type, in this case, 'copter'. This allows for fine-tuning simulation settings relevant to the chosen autopilot. ```bash dronekit-sitl copter -h ``` -------------------------------- ### Iterative Documentation Building with Vagrant SSH Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/contributions_documentation.rst This snippet shows how to maintain an open SSH session with the Vagrant VM for faster, iterative building of documentation. After opening the session, navigate to the docs directory and run 'make html' as needed. ```bash vagrant ssh cd /vagrant/docs make html exit ``` -------------------------------- ### Launch Python Script from Command Line Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/best_practice.rst Demonstrates how to launch a Python script from the command line, passing arguments that are accessible via sys.argv. This is a standard method for running DroneKit applications. ```bash python some_python_script.py [arguments] ``` -------------------------------- ### Getting Current Script Directory Path (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/about/migrating.rst DroneKit-Python v1.x provided a global `load_path` property. Version 2.0 removes this, requiring the use of standard Python methods like `os.path.dirname` and `os.path.abspath(__file__)` to get the current script's directory. ```python import os.path full_directory_path_of_current_script = os.path.dirname(os.path.abspath(__file__)) ``` -------------------------------- ### Set Target Location with simple_goto (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/guide/copter/guided_mode.rst This snippet demonstrates how to set the Copter to a specific global-relative target location using the `simple_goto` function. It first ensures the vehicle is in GUIDED mode and then defines the target `LocationGlobalRelative`. This method is suitable when the final destination is known. ```python from dronekit import Vehicle, VehicleMode, LocationGlobalRelative # Assuming 'vehicle' is an established DroneKit connection # vehicle = connect('your_connection_string', wait_ready=True) # Set mode to guided - this is optional as the goto method will change the mode if needed. vehicle.mode = VehicleMode("GUIDED") # Set the target location in global-relative frame a_location = LocationGlobalRelative(-34.364114, 149.166022, 30) vehicle.simple_goto(a_location) ``` -------------------------------- ### Reset downloaded SITL vehicle binaries Source: https://github.com/dronekit/dronekit-python/blob/master/docs/develop/sitl_setup.rst Removes all previously downloaded SITL vehicle binaries managed by DroneKit-SITL. This is useful for freeing up disk space or troubleshooting issues with corrupted downloads. ```bash dronekit-sitl --reset ``` -------------------------------- ### Performing Takeoff and Movement Commands (Python) Source: https://github.com/dronekit/dronekit-python/blob/master/docs/about/migrating.rst DKPY 2.0 replaces `Vehicle.commands.takeoff()` and `Vehicle.commands.goto()` with `Vehicle.simple_takeoff()` and `Vehicle.simple_goto()`. The `simple_goto` method now optionally accepts default target groundspeed and airspeed. ```python # Example for simple_takeoff (no direct code provided in text, but mentioned) # vehicle.simple_takeoff(altitude) # Example for simple_goto (no direct code provided in text, but mentioned) # vehicle.simple_goto(location, groundspeed=10, airspeed=5) ``` -------------------------------- ### Basic Integration Test Structure with DroneKit Source: https://github.com/dronekit/dronekit-python/blob/master/docs/contributing/contributions_api.rst This snippet demonstrates the fundamental structure of an integration test for DroneKit. It shows how to import necessary modules, use the `@with_sitl` decorator to set up the SITL environment, connect to the simulated vehicle, perform tests using assertions, and properly close the vehicle connection. ```python from dronekit import connect from dronekit.test import with_sitl from nose.tools import assert_equals, assert_not_equals @with_sitl def test_something(connpath): vehicle = connect(connpath) # Test using assert, assert_equals and assert_not_equals ... vehicle.close() ``` -------------------------------- ### goto_position_target_global_int() Source: https://github.com/dronekit/dronekit-python/blob/master/docs/examples/guided-set-speed-yaw-demo.rst Generates a SET_POSITION_TARGET_GLOBAL_INT MAVLink message to set the target location of the vehicle. When used with MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, it functions similarly to Vehicle.simple_goto. ```APIDOC ## POST /goto_position_target_global_int ### Description Generates a `SET_POSITION_TARGET_GLOBAL_INT` MAVLink message to directly specify the target location of the vehicle. This function is equivalent to `Vehicle.simple_goto` when using `MAV_FRAME_GLOBAL_RELATIVE_ALT_INT`. ### Method POST ### Endpoint /goto_position_target_global_int ### Parameters #### Request Body - **aLocation** (object) - Required - An object representing the target location. - **lat** (float) - Required - Latitude in decimal degrees. - **lon** (float) - Required - Longitude in decimal degrees. - **alt** (float) - Required - Altitude in meters. ### Request Example ```json { "aLocation": { "lat": 34.123456, "lon": -118.765432, "alt": 50.0 } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "Command sent successfully" } ``` ``` -------------------------------- ### Run Python Script from Command Line Source: https://github.com/dronekit/dronekit-python/blob/master/docs/about/migrating.rst In DroneKit-Python 2.0, applications are executed directly from a standard Python command prompt. This replaces the older method of launching scripts within MAVProxy. ```bash some_python_script.py # or `python some_python_script.py` ```