diff --git a/docs/examples/index.rst b/docs/examples/index.rst index a3ea7461c..65b983659 100644 --- a/docs/examples/index.rst +++ b/docs/examples/index.rst @@ -16,6 +16,8 @@ during missions and outside missions using custom commands. Vehicle State Simple Goto Guided Movement and Commands + Basic Mission + Mission Import/Export Follow Me (Linux only) Drone Delivery Flight Replay diff --git a/docs/examples/mission_basic.rst b/docs/examples/mission_basic.rst new file mode 100644 index 000000000..00d9d3610 --- /dev/null +++ b/docs/examples/mission_basic.rst @@ -0,0 +1,168 @@ +.. _example_mission_basic: + +====================== +Example: Basic Mission +====================== + +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 :ref:`auto_mode_vehicle_control` provides more detailed explanation of how the API +should be used. + + +Running the example +=================== + +The vehicle and DroneKit should be set up as described in :ref:`get-started`. + +If you're using a simulated vehicle remember to :ref:`disable arming checks ` so +that the example can run. + +Once MAVProxy is running and the API is loaded, you can start the example by typing: ``api start mission_basic.py``. + +.. note:: + + The command above assumes you started the *MAVProxy* prompt in a directory containing the example script. If not, + you will have to specify the full path to the script (something like): + ``api start /home/user/git/dronekit-python/examples/mission_basic/mission_basic.py``. + + +On the *MAVProxy* console you should see (something like): + +.. code:: bash + + MAV> api start mission_basic.py + STABILIZE> Clear the current mission + Got MAVLink msg: MISSION_ACK {target_system : 255, target_component : 0, type : 0} + Requesting 0 waypoints t=Wed Jul 29 21:27:58 2015 now=Wed Jul 29 21:27:58 2015 + Create a new mission + Got MAVLink msg: MISSION_ACK {target_system : 255, target_component : 0, type : 0} + Sent waypoint 0 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 0, frame : 0, command : 16, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.3632621765, y : 149.165237427, z : 584.0} + Sent waypoint 1 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 1, frame : 3, command : 22, current : 0, autocontinue : 0, param1 : 0, param2 : 0, param3 : 0, param4 : 0, x : 0, y : 0, z : 10} + Sent waypoint 2 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 2, frame : 3, command : 16, current : 0, autocontinue : 0, param1 : 0, param2 : 0, param3 : 0, param4 : 0, x : -35.3628118424, y : 149.164679124, z : 11} + Sent waypoint 3 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 3, frame : 3, command : 16, current : 0, autocontinue : 0, param1 : 0, param2 : 0, param3 : 0, param4 : 0, x : -35.3628118424, y : 149.165780676, z : 12} + Sent waypoint 4 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 4, frame : 3, command : 16, current : 0, autocontinue : 0, param1 : 0, param2 : 0, param3 : 0, param4 : 0, x : -35.3637101576, y : 149.165780676, z : 13} + Sent waypoint 5 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 5, frame : 3, command : 16, current : 0, autocontinue : 0, param1 : 0, param2 : 0, param3 : 0, param4 : 0, x : -35.3637101576, y : 149.164679124, z : 14} + Sent all 6 waypoints + Got MAVLink msg: MISSION_ACK {target_system : 255, target_component : 0, type : 0} + APM: flight plan received + Basic pre-arm checks + Arming motors + Waiting for arming... + Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} + Waiting for arming... + APM: ARMING MOTORS + APM: GROUND START + Waiting for arming... + GUIDED> Mode GUIDED + APM: Initialising APM... + Got MAVLink msg: COMMAND_ACK {command : 400, result : 0} + Waiting for arming... + ARMED + Taking off! + Altitude: 0.0 + Got MAVLink msg: COMMAND_ACK {command : 22, result : 0} + GPS lock at 0 meters + Altitude: 0.10000000149 + ... + Altitude: 8.84000015259 + Altitude: 9.60999965668 + Reached target altitude + Starting mission + Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} + waypoint 1 + waypoint 2 + AUTO> Mode AUTO + Distance to waypoint (2): 79.3138466142 + Distance to waypoint (2): 79.1869592549 + Distance to waypoint (2): 77.8436803794 + ... + Distance to waypoint (2): 20.7677087176 + Distance to waypoint (2): 15.4592692026 + APM: Reached Command #2 + waypoint 3 + Distance to waypoint (3): 115.328425048 + Skipping to Waypoint 4 when reach waypoint 3 + waypoint 4 + Distance to waypoint (4): 152.376018911 + Distance to waypoint (4): 154.882233097 + ... + Distance to waypoint (4): 20.4052797291 + Distance to waypoint (4): 15.0592597507 + APM: Reached Command #4 + waypoint 5 + Distance to waypoint (5): 114.450267446 + Exit 'standard' mission when start heading to final waypoint (5) + Return to launch + APIThread-0 exiting... + + + +How does it work? +================= + +The :ref:`source code ` is relatively self-documenting, and most of its main +operations are explained in the guide topic :ref:`auto_mode_vehicle_control` . + +In overview, the example first calls ``clear_mission()`` to clear the current mission and then creates and +uploads a new mission using ``adds_square_mission(vehicle.location,50)``. This function defines a mission with a takeoff +command and four waypoints arranged in a square around the central position. + +After taking off (in guided mode using the ``takeoff()`` function) the example starts the mission by setting the mode to AUTO: + +.. code:: python + + print "Starting mission" + # Set mode to AUTO to start mission + vehicle.mode = VehicleMode("AUTO") + vehicle.flush() + +The progress of the mission is monitored in a loop. The convenience function +:ref:`distance_to_current_waypoint() ` +gets the distance to the next waypoint and +:py:func:`Vehicle.commands.next ` gets the value of +the next command. + +We also show how to move to a specified command using +:py:func:`Vehicle.commands.next ` (note how we skip the third command below): + +.. code:: python + + while True: + nextwaypoint =vehicle.commands.next + if nextwaypoint > 1: + print 'Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()) + if nextwaypoint ==3: #Skip to next waypoint + print 'Skipping to Waypoint 4 when reach waypoint 3' + vehicle.commands.next=4 + if nextwaypoint ==5: #Skip to next waypoint + print "Exit 'standard' mission when start heading to final waypoint (5)" + break; + time.sleep(1) + +When the vehicle starts the 5th command the loop breaks and the mode is set to RTL (return to launch). + + +.. _example_mission_basic_known_issues: + +Known issues +============ + +This example works around the :ref:`known issues in the API `. +Provided that the vehicle is connected and able to arm, it should run through to completion. + + + +.. _example_mission_basic_source_code: + +Source code +=========== + +The full source code at documentation build-time is listed below (`current version on github `_): + +.. literalinclude:: ../../examples/mission_basic/mission_basic.py + :language: python + diff --git a/docs/examples/mission_import_export.rst b/docs/examples/mission_import_export.rst new file mode 100644 index 000000000..ce7371ec9 --- /dev/null +++ b/docs/examples/mission_import_export.rst @@ -0,0 +1,116 @@ +.. _example_mission_import_export: + +============================== +Example: Mission Import/Export +============================== + +This example shows how to import and export files in the +`Waypoint file format `_. + +The commands are first imported from a file into a list and then uploaded to the vehicle. +Then the current mission is downloaded from the vehicle and put into a list, and finally +saved into (another file). + +The example does not show how missions can be modified, but once the mission is in a list, +changing the order and content of commands is straightforward. + +The guide topic :ref:`auto_mode_vehicle_control` provides information about +missions and AUTO mode. + + +Running the example +=================== + +The vehicle and DroneKit should be set up as described in :ref:`get-started`. + +Once MAVProxy is running and the API is loaded, you can start the example by typing: ``api start mission_import_export.py``. + +.. note:: + + The command above assumes you started the *MAVProxy* prompt in a directory containing the example script. If not, + you will have to specify the absolute path to the script. For example: + ``api start /home/user/git/dronekit-python/examples/mission_import_export/mission_import_export.py``. + + +On the *MAVProxy* console you should see (something like): + +.. code:: bash + + STABILIZE> api start mission_import_export.py + STABILIZE> + Upload mission from a file: mpmission.txt + Reading mission from file: mpmission.txt + + STABILIZE> Import line: 0 1 0 16 0 0 0 0 -35.360500 149.172363 747.000000 1 + + Import line: 1 0 3 22 0.000000 0.000000 0.000000 0.000000 -35.359831 149.166334 100.000000 1 + + + Import line: 2 0 3 16 0.000000 0.000000 0.000000 0.000000 -35.363489 149.167213 100.000000 1 + + Import line: 3 0 3 16 0.000000 0.000000 0.000000 0.000000 -35.355491 149.169595 100.000000 1 + + Import line: 4 0 3 16 0.000000 0.000000 0.000000 0.000000 -35.355071 149.175839 100.000000 1 + + Import line: 5 0 3 113 0.000000 0.000000 0.000000 0.000000 -35.362666 149.178715 22222.000000 1 + Import line: 6 0 3 115 2.000000 22.000000 1.000000 3.000000 0.000000 0.000000 0.000000 1 + + Import line: 7 0 3 16 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1 + + Clear mission + Requesting 9 waypoints t=Wed Jul 29 20:12:17 2015 now=Wed Jul 29 20:12:17 2015 + ClearCount: 0 + Got MAVLink msg: MISSION_ACK {target_system : 255, target_component : 0, type : 0} + Requesting 0 waypoints t=Wed Jul 29 20:12:17 2015 now=Wed Jul 29 20:12:17 2015 + Got MAVLink msg: MISSION_ACK {target_system : 255, target_component : 0, type : 0} + Sent waypoint 0 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 0, frame : 0, command : 16, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.3632621765, y : 149.165237427, z : 584.0} + Sent waypoint 1 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 1, frame : 0, command : 16, current : 1, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.3605, y : 149.172363, z : 747.0} + Sent waypoint 2 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 2, frame : 3, command : 22, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.359831, y : 149.166334, z : 100.0} + Sent waypoint 3 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 3, frame : 3, command : 16, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.363489, y : 149.167213, z : 100.0} + Sent waypoint 4 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 4, frame : 3, command : 16, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.355491, y : 149.169595, z : 100.0} + Sent waypoint 5 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 5, frame : 3, command : 16, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.355071, y : 149.175839, z : 100.0} + Sent waypoint 6 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 6, frame : 3, command : 113, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : -35.362666, y : 149.178715, z : 22222.0} + Sent waypoint 7 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 7, frame : 3, command : 115, current : 0, autocontinue : 1, param1 : 2.0, param2 : 22.0, param3 : 1.0, param4 : 3.0, x : 0.0, y : 0.0, z : 0.0} + Sent waypoint 8 : MISSION_ITEM {target_system : 1, target_component : 0, seq : 8, frame : 3, command : 16, current : 0, autocontinue : 1, param1 : 0.0, param2 : 0.0, param3 : 0.0, param4 : 0.0, x : 0.0,y : 0.0, z : 0.0} + Sent all 9 waypoints + Got MAVLink msg: MISSION_ACK {target_system : 255, target_component : 0, type : 0} + APM: flight plan received + + Save mission from Vehicle to file: exportedmission.txt + Requesting 9 waypoints t=Wed Jul 29 20:12:18 2015 now=Wed Jul 29 20:12:18 2015 + APIThread-1 exiting... + + + +How does it work? +================= + +The :ref:`source code ` is largely self-documenting. + +More information about the functions can be found in the guide at +:ref:`auto_mode_load_mission_file` and :ref:`auto_mode_save_mission_file`. + + + +Known issues +============ + +This example works around known issues in the API: + +* A ``time.sleep(1)`` has been placed between uploading the mission to the vehicle (from the file) and downloading the mission. + This is to avoid the race condition where the mission being downloaded has not yet successfully uploaded to the vehicle. + This race condition (probably) shouldn't exist because the mission is flushed to the Vehicle - + see `Race condition when updating and fetching commands `_ + + + +.. _example_mission_import_export_source_code: + +Source code +=========== + +The full source code at documentation build-time is listed below (`current version on github `_): + +.. literalinclude:: ../../examples/mission_import_export/mission_import_export.py + :language: python + diff --git a/docs/guide/auto_mode.rst b/docs/guide/auto_mode.rst new file mode 100644 index 000000000..deb709c0f --- /dev/null +++ b/docs/guide/auto_mode.rst @@ -0,0 +1,464 @@ +.. _auto_mode_vehicle_control: + +============================== +Missions (AUTO Mode) +============================== + +AUTO mode is used run pre-defined waypoint missions on Copter, Plane and Rover. + +DroneKit-Python provides basic methods to download and clear the current mission commands +from the vehicle, to add and upload new mission commands, to count the number of waypoints, +and to read and set the currently executed mission command. +You can build upon these basic primitives to create high-level mission planning functionality. + +This section shows how to use the basic methods and provides a few useful helper functions. +Most of the code can be observed running in :ref:`example_mission_basic` and :ref:`example_mission_import_export`. + +.. note:: + + We recommend that you :ref:`use GUIDED mode ` instead of AUTO mode where possible, because it offers finer + and more responsive control over movement, and can emulate most mission planning activities. + + AUTO mode can be helpful if a command you need is not supported in GUIDED mode on a particular vehicle type. + + +.. _auto_mode_supported_commands: + +Mission Command Overview +========================== + +The mission commands (e.g. ``MAV_CMD_NAV_TAKEOFF``, ``MAV_CMD_NAV_WAYPOINT`` ) supported for each vehicle type are listed here: +`Copter `_, +`Plane `_, +`Rover `_. + +There are three types of commands: + +* *NAVigation commands* (``MAV_CMD_NAV_*``) are used to control vehicle movement, + including takeoff, moving to and around waypoints, changing altitude, and landing. +* *DO commands* (``MAV_CMD_DO_*``) are for auxiliary functions that do not affect the vehicle’s position + (for example, setting the camera trigger distance, or setting a servo value). +* *CONDITION commands* (``MAV_CMD_NAV_*``) are used to delay *DO commands* until some condition is met. + For example ``MAV_CMD_CONDITION_DISTANCE`` will prevent DO commands executing until the vehicle + reaches the specified distance from the waypoint. + +During a mission at most one *NAV* command and one *DO* or *CONDITION* command can be running **at the same time**. +*CONDITION* and *DO* commands are associated with the last *NAV* command that was sent: if the UAV reaches the waypoint before these +commands are executed, the next *NAV* command is loaded and they will be skipped. + +The `MAVLink Mission Command Messages (MAV_CMD) `_ +wiki topic provides a more detailed overview of commands. + +.. note:: + + * If the autopilot receives a command that it cannot handle, then the command will be (silently) dropped. + * You cannot yet determine dynamically what commands are supported. We hope to deliver this functionality in + the forthcoming `capability API `_. + + +.. _auto_mode_download_mission: + +Download current mission +======================== + +The mission commands for a vehicle are accessed using the :py:attr:`Vehicle.commands ` +attribute. The attribute is of type :py:class:`CommandSequence `, a class that provides ‘array style’ indexed access to the +waypoints which make up the mission. + +Waypoints are not downloaded from vehicle until :py:func:`download() ` is called. The download is asynchronous; +use :py:func:`wait_valid() ` to block your thread until the download is complete: + +.. code:: python + + # Connect to API provider and get vehicle + api = local_connect() + vehicle = api.get_vehicles()[0] + + # Download the vehicle waypoints (commands). Wait until download is complete. + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + +.. note:: + + The commands downloaded from the vehicle will include a waypoint for the :ref:`home location ` in the first position (0 index). + This waypoint is not editable - it cannot be removed or modified. + +.. todo:: + + The information about home location will change with + `#207 WIP:Adds separate .home_location from .commands array `_. + + +.. _auto_mode_clear_mission: + +Clearing current mission +======================== + +To clear a mission you call :py:func:`clear() ` and then +:py:func:`flush() ` (to upload the changes to the vehicle): + +.. code:: python + + # Connect to API provider and get vehicle + api = local_connect() + vehicle = api.get_vehicles()[0] + cmds = vehicle.commands + + # Clear Vehicle.commands and flush. + cmds.clear() + vehicle.flush() + + # Reset the Vehicle.commands from the vehicle. + cmds.download() + cmds.wait_valid() + +.. warning:: + + You must re-download the mission from the vehicle after clearing (as shown above) or the first command you add + will be lost when you upload the new mission. + + This happens because :py:attr:`Vehicle.commands ` removes the :ref:`home location ` + (see `#132 `_). Downloading adds it back again. + +If the current command completes before you add a new mission, then the vehicle mode will change to RTL (return to launch). + + +.. _auto_mode_adding_command: + +Creating/adding mission commands +================================ + +After :ref:`downloading ` or :ref:`clearing ` a mission new commands +can be added and uploaded to the vehicle. Commands are added to the mission using :py:func:`add() ` +and are sent to the vehicle (either individually or in batches) using :py:func:`flush() `. + +Each command is packaged in a :py:class:`Command ` object (see that class for the order/meaning of the parameters). +The supported commands for each vehicle are :ref:`linked above `. + + +.. code:: python + + from droneapi.lib import Command + from pymavlink import mavutil + + # Connect to API provider and get vehicle + api = local_connect() + vehicle = api.get_vehicles()[0] + + # Get the set of commands from the vehicle + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + + # Create and add commands + cmd1=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) + cmd2=Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, 10, 10, 10) + cmds.add(cmd1) + cmds.add(cmd2) + vehicle.flush() # Send commands + + + + +.. _auto_mode_modify_mission: + +Modifying missions +================== + +While you can :ref:`add new commands ` after :ref:`downloading a mission ` +it is not possible to directly modify and upload existing commands in ``Vehicle.commands`` (you can modify the commands but +changes do not propagate to the vehicle). + +Instead you copy all the commands into another container (e.g. a list), +modify them as needed, then clear ``Vehicle.commands`` and upload the list as a new mission: + +.. code:: python + + api = local_connect() + vehicle = api.get_vehicles()[0] + + # Download the current vehicle commands + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + + # Save the vehicle commands to a list + missionlist=[] + for cmd in cmds[1:]: #skip first item as it is home waypoint. + missionlist.append(cmd) + + # Modify the mission as needed. For example, here we change the + # first waypoint into a MAV_CMD_NAV_TAKEOFF command. + missionlist[0].command=mavutil.mavlink.MAV_CMD_NAV_TAKEOFF + + # Clear the current mission + cmds.clear() + vehicle.flush() + cmds.download() + cmds.wait_valid() + + #Write the modified mission and flush to the vehicle + for cmd in missionlist: + cmds.add(cmd) + vehicle.flush() + + +The changes are not guaranteed to be complete until +:py:func:`flush() ` is called on the parent ``Vehicle`` object. + + +.. _auto_mode_monitoring_controlling: + +Running and monitoring missions +=============================== + +To start a mission change the mode to AUTO: + +.. code:: python + + # Get an instance of the API endpoint and a vehicle + api = local_connect() + vehicle = api.get_vehicles()[0] + + # Set the vehicle into auto mode + vehicle.mode = VehicleMode("AUTO") + vehicle.flush() + +.. note:: + + If the vehicle is in the air, then changing the mode to AUTO is all that is required to start the + mission. + + **Copter 3.3 release and later:** If the vehicle is on the ground (only), you will additionally need to send the + `MAV_CMD_MISSION_START `_ + command. + +You can stop/pause the current mission by switching out of AUTO mode (e.g. into GUIDED mode). If you switch back to +AUTO mode the mission will either restart at the beginning or resume at the current waypoint - the behaviour depends on the value of the +`MIS_RESTART `_ +parameter (available on all vehicle types). + +You can monitor the progress of the mission by polling the :py:func:`Vehicle.commands.next ` attribute +to get the current command number. You can also change the current command by setting the attribute to the desired command number. + +.. code:: python + + vehicle.commands.next=2 + print "Current Waypoint: %s" % vehicle.commands.next + vehicle.commands.next=4 + print "Current Waypoint: %s" % vehicle.commands.next + +There is no need to ``flush()`` changes to ``next`` to the vehicle (and as with other attributes, if you fetch a value, it is updated +from the vehicle). + + +.. _auto_mode_handle_mission_end: + +Handling the end of a mission +=============================== + +At the end of the mission the vehicle will enter LOITER mode (hover in place for Copter, +circle for Plane, stop for Rover). You can add new commands to the mission, but you will need to toggle from/back to +AUTO mode to start it running again. + +Currently there is no notification in DroneKit when a mission completes. If you need to detect mission end (in order +to perform some other operation) then you can either: + +* Add a dummy mission command and poll :py:func:`Vehicle.commands.next ` for the + transition to the final command, or +* Compare the current position to the position in the last command. + + + + +.. _auto_mode_useful_functions: + +Useful Mission functions +======================== + +This example code contains a number of functions that might be useful for managing and monitoring missions: + +.. _auto_mode_load_mission_file: + +Load a mission from a file +----------------------------- + +``upload_mission()`` uploads a mission from a file. + +The implementation calls ``readmission()`` (below) to import the mission from a file into a list. The method then +clears the existing mission and uploads the new version. + +Adding mission commands is discussed :ref:`here in the guide `. + +.. code:: python + + def upload_mission(aFileName): + """ + Upload a mission from a file. + """ + missionlist = readmission(aFileName) + #clear existing mission + print 'Clear mission' + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + cmds.clear() + vehicle.flush() + print 'ClearCount: %s' % cmds.count + #add new mission + cmds.download() + cmds.wait_valid() + for command in missionlist: + cmds.add(command) + vehicle.flush() + + +``readmission()`` reads a mission from the specified file and returns a list of :py:class:`Command ` objects. + +Each line is split up. The first line is used to test whether the file has the correct (stated) format. +For subsequent lines the values are stored in a :py:class:`Command ` object +(the values are first cast to the correct ``float`` and ``int`` types for their associated parameters). +The commands are added to a list which is returned by the function. + +.. code:: python + + def readmission(aFileName): + """ + Load a mission from a file into a list. + + This function is used by upload_mission(). + """ + print "Reading mission from file: %s\n" % 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: + print ' Import line: %s' % line + 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) + return missionlist + + + +.. _auto_mode_save_mission_file: + +Save a mission to a file +------------------------ + +``save_mission()`` saves the current mission to a file (in the `Waypoint file format `_). +It uses ``download_mission()`` (below) to get them mission, and then writes the list line-by-line to the file. + +.. code:: python + + def save_mission(aFileName): + """ + Save a mission in the Waypoint file format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). + """ + missionlist = download_mission() + output='QGC WPL 110\n' + 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_: + file_.write(output) + +``download_mission()`` downloads the :py:attr:`Vehicle.commands ` from the vehicle and +adds them to a list. Downloading mission is discussed :ref:`in the guide `. + +.. code:: python + + 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. + """ + missionlist=[] + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + for cmd in cmds[1:]: #skip first item as it is home waypoint. + missionlist.append(cmd) + return missionlist + + + + + +.. _auto_mode_mission_distance_to_waypoint: + +Get distance to waypoint +------------------------ + +``distance_to_current_waypoint()`` returns the distance (in metres) to the next waypoint: + +.. code:: python + + 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==1: + return None + missionitem=vehicle.commands[nextwaypoint] + lat=missionitem.x + lon=missionitem.y + alt=missionitem.z + targetWaypointLocation=Location(lat,lon,alt,is_relative=True) + distancetopoint = get_distance_metres(vehicle.location, targetWaypointLocation) + return distancetopoint + +The function determines the current target waypoint number with :py:func:`Vehicle.commands.next ` +and uses it to index the commands to get the latitude, longitude and altitude of the target waypoint. The ``get_distance_metres()`` function +(see :ref:`guided_mode_copter_useful_conversion_functions`) is then used to calculate and return the (horizontal) distance +from the current vehicle location. + +The implementation ignores the first waypoint (which will be the "home location"). + +.. tip:: + + This implementation is very basic. It assumes that the next command number is for a valid NAV command (it might not be) + and that the lat/lon/alt values are non-zero. It is however a useful indicator for test code. + + + +.. _auto_mode_mission_useful_links: + +Useful Links +================= + +* `MAVLink mission command messages `_ (all vehicle types - wiki). + + +.. _auto_mode_mission_known_issues: + +Known Issues +============ + +AUTO Mode/mission control has the following known issues (at time of writing): + +* `#230 vehicle.commands must be reset after clearing `_ +* `#132 Vehicle.commands is throwing away the first command sent `_ +* `#252 Expose home location as separate from .commands array `_ +* `#207 WIP:Adds separate .home_location from .commands array `_ +* `#105 Implement Vehicle.waypoint_home `_ +* `#227 Race condition when updating and fetching commands `_ \ No newline at end of file diff --git a/docs/guide/index.rst b/docs/guide/index.rst index 37bd91e86..cc0c8914c 100644 --- a/docs/guide/index.rst +++ b/docs/guide/index.rst @@ -14,4 +14,5 @@ The guide contains how-to documentation for using the DroneKit-Python API. These vehicle_state_and_parameters taking_off copter/guided_mode + Missions debugging diff --git a/examples/mission_basic/mission_basic.py b/examples/mission_basic/mission_basic.py new file mode 100644 index 000000000..7c8486dbf --- /dev/null +++ b/examples/mission_basic/mission_basic.py @@ -0,0 +1,198 @@ +""" +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 +""" + +import time +import math +from droneapi.lib import VehicleMode, Location, Command +from pymavlink import mavutil + +# Connect to API provider and get vehicle +api = local_connect() +vehicle = api.get_vehicles()[0] + + +def get_location_metres(original_location, dNorth, dEast): + """ + Returns a Location object containing the latitude/longitude `dNorth` and `dEast` metres from the + specified `original_location`. The returned Location has the same `alt and `is_relative` values + 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 Location(newlat, newlon,original_location.alt,original_location.is_relative) + + +def get_distance_metres(aLocation1, aLocation2): + """ + Returns the ground distance in metres between two Location 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 ==1: + return None + missionitem=vehicle.commands[nextwaypoint] + lat=missionitem.x + lon=missionitem.y + alt=missionitem.z + targetWaypointLocation=Location(lat,lon,alt,is_relative=True) + distancetopoint = get_distance_metres(vehicle.location, targetWaypointLocation) + return distancetopoint + + +def clear_mission(): + """ + Clear the current mission. + """ + cmds = vehicle.commands + vehicle.commands.clear() + vehicle.flush() + + # After clearing the mission you MUST re-download the mission from the vehicle + # before vehicle.commands can be used again + # (see https://github.com/dronekit/dronekit-python/issues/230) + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + + +def download_mission(): + """ + Download the current mission from the vehicle. + """ + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() # 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 location (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) + """ + # Add the commands. The meaning/order of the parameters is documented in the Command class. + cmds = vehicle.commands + #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)) + + # Send commands to vehicle. + vehicle.flush() + + +def arm_and_takeoff(aTargetAltitude): + """ + Arms vehicle and fly to aTargetAltitude. + """ + print "Basic pre-arm checks" + # Don't let the user try to fly autopilot is booting + if vehicle.mode.name == "INITIALISING": + print "Waiting for vehicle to initialise" + time.sleep(1) + while vehicle.gps_0.fix_type < 2: + print "Waiting for GPS...:", vehicle.gps_0.fix_type + time.sleep(1) + + print "Arming motors" + # Copter should arm in GUIDED mode + vehicle.mode = VehicleMode("GUIDED") + vehicle.armed = True + vehicle.flush() + + while not vehicle.armed and not api.exit: + print " Waiting for arming..." + time.sleep(1) + + print "Taking off!" + vehicle.commands.takeoff(aTargetAltitude) # Take off to target altitude + vehicle.flush() + + # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command + # after Vehicle.commands.takeoff will execute immediately). + while not api.exit: + print " Altitude: ", vehicle.location.alt + if vehicle.location.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. + print "Reached target altitude" + break; + time.sleep(1) + + +print 'Clear the current mission' +clear_mission() + +print 'Create a new mission' +adds_square_mission(vehicle.location,50) +time.sleep(2) # This is here so that mission being sent is displayed on console + + +# 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" +# Set mode to AUTO to start mission +vehicle.mode = VehicleMode("AUTO") +vehicle.flush() + +# 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 + if nextwaypoint > 1: + print 'Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()) + if nextwaypoint==3: #Skip to next waypoint + print 'Skipping to Waypoint 4 when reach waypoint 3' + vehicle.commands.next=4 + if nextwaypoint==5: #Skip to next waypoint + print "Exit 'standard' mission when start heading to final waypoint (5)" + break; + time.sleep(1) + +print 'Return to launch' +vehicle.mode = VehicleMode("RTL") +vehicle.flush() # Flush to ensure changes are sent to autopilot + + diff --git a/examples/mission_import_export/mission_import_export.py b/examples/mission_import_export/mission_import_export.py new file mode 100644 index 000000000..cdf681a2f --- /dev/null +++ b/examples/mission_import_export/mission_import_export.py @@ -0,0 +1,113 @@ +""" +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 +""" + +import time +import math +from droneapi.lib import Command +from pymavlink import mavutil + +# Connect to API provider and get vehicle +api = local_connect() +vehicle = api.get_vehicles()[0] + + +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 "Reading mission from file: %s\n" % 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: + print ' Import line: %s' % line + 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) + return missionlist + + +def upload_mission(aFileName): + """ + Upload a mission from a file. + """ + missionlist = readmission(aFileName) + #clear existing mission + print 'Clear mission' + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + cmds.clear() + vehicle.flush() + print 'ClearCount: %s' % cmds.count + #add new mission + cmds.download() + cmds.wait_valid() + for command in missionlist: + cmds.add(command) + vehicle.flush() + + +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. + """ + missionlist=[] + cmds = vehicle.commands + cmds.download() + cmds.wait_valid() + for cmd in cmds[1:]: #skip first item as it is home waypoint. + 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). + """ + missionlist = download_mission() + output='QGC WPL 110\n' + 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_: + file_.write(output) + + +import_mission_filename = 'mpmission.txt' +export_mission_filename = 'exportedmission.txt' + +print "\nUpload mission from a file: %s" % import_mission_filename +upload_mission(import_mission_filename) + +time.sleep(1) + +print "\nSave mission from Vehicle to file: %s" % export_mission_filename +save_mission(export_mission_filename) +