diff --git a/docs/automodule.rst b/docs/automodule.rst index 28b53c593..5a43bb22f 100644 --- a/docs/automodule.rst +++ b/docs/automodule.rst @@ -8,7 +8,7 @@ DroneKit-Python API Reference .. automodule:: dronekit.lib :members: :inherited-members: - :exclude-members: Mission, get_mission, ConnectionInfo, web_connect, AuthInfo, delete + :exclude-members: Mission, get_mission, ConnectionInfo, web_connect, AuthInfo, delete, notify_observers, remove_all_observers, local_connect, APIConnection diff --git a/docs/examples/drone_delivery.rst b/docs/examples/drone_delivery.rst index b73904ce8..581021f35 100644 --- a/docs/examples/drone_delivery.rst +++ b/docs/examples/drone_delivery.rst @@ -114,7 +114,7 @@ All attributes in DroneKit can have observers - this is the primary mechanism yo ... def location_callback(self, location): - location = self.vehicle.location + location = self.vehicle.location.global_frame if location.alt is not None: self.altitude = location.alt diff --git a/docs/examples/flight_replay.rst b/docs/examples/flight_replay.rst index e5f1747a1..942dde5a7 100644 --- a/docs/examples/flight_replay.rst +++ b/docs/examples/flight_replay.rst @@ -109,9 +109,9 @@ shown in :ref:`example_mission_basic`): .. code:: python print "Generating %s waypoints from replay..." % len(messages) - cmds = v.commands + cmds = vehicle.commands cmds.clear() - v.flush() + vehicle.flush() for i in xrange(0, len(messages)): pt = messages[i] lat = pt['lat'] @@ -127,7 +127,7 @@ shown in :ref:`example_mission_basic`): 0, 0, 0, 0, 0, 0, lat, lon, altitude) cmds.add(cmd) - v.flush() + vehicle.flush() Known issues diff --git a/docs/examples/follow_me.rst b/docs/examples/follow_me.rst index bbc7155a2..78a886d2d 100644 --- a/docs/examples/follow_me.rst +++ b/docs/examples/follow_me.rst @@ -137,12 +137,11 @@ the mode is changed. # Once we have a valid location (see gpsd documentation) we can start moving our vehicle around if (gpsd.valid & gps.LATLON_SET) != 0: altitude = 30 # in meters - dest = Location(gpsd.fix.latitude, gpsd.fix.longitude, altitude, is_relative=True) + dest = LocationGlobal(gpsd.fix.latitude, gpsd.fix.longitude, altitude, is_relative=True) print "Going to: %s" % dest # A better implementation would only send new waypoints if the position had changed significantly vehicle.commands.goto(dest) - vehicle.flush() # Send a new target every two seconds # For a complete implementation of follow me you'd want adjust this delay diff --git a/docs/examples/guided-set-speed-yaw-demo.rst b/docs/examples/guided-set-speed-yaw-demo.rst index 044cd69cc..f76961d8c 100644 --- a/docs/examples/guided-set-speed-yaw-demo.rst +++ b/docs/examples/guided-set-speed-yaw-demo.rst @@ -201,14 +201,13 @@ This takes a function argument of either :ref:`Vehicle.commands.goto() ` convenience function. @@ -334,7 +331,7 @@ which is used to directly specify the target location in the North, East, Down f 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() + At time of writing, acceleration and yaw bits are ignored. diff --git a/docs/examples/mission_basic.rst b/docs/examples/mission_basic.rst index 81293d69e..874d11c49 100644 --- a/docs/examples/mission_basic.rst +++ b/docs/examples/mission_basic.rst @@ -137,7 +137,7 @@ The :ref:`source code ` is relatively self-do 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 +uploads a new mission using ``adds_square_mission(vehicle.location.global_frame,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: @@ -147,7 +147,6 @@ After taking off (in guided mode using the ``takeoff()`` function) the example s 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() ` @@ -187,9 +186,11 @@ This example fails in DroneKit 2.0.0b6 and earlier releases (see `#355 DKPY2 Can This is blocked by https://github.com/dronekit/dronekit-python/issues/355 (vehicle.commands.clear not working). The code output in "running the example needs to be updated once this runs cleanly. - The above text for the error needs to be replaced with original text - > "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." + The above text for the error needs to be replaced with original text: + + > "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." + Need to check all that clearing is still strictly necessary in DKPY2 which handles race conditions more gracefully. Add image of waypoints /flight for top of page. diff --git a/docs/examples/mission_import_export.rst b/docs/examples/mission_import_export.rst index f8252d4a6..3e2245dd7 100644 --- a/docs/examples/mission_import_export.rst +++ b/docs/examples/mission_import_export.rst @@ -139,7 +139,9 @@ Known issues This is blocked by https://github.com/dronekit/dronekit-python/issues/355 (vehicle.commands.clear not working). The code output in "running the example"" needs to be updated once this runs cleanly. The above text for the error needs to be replaced with original text - > "This example works around known issues in the API:." + + > "This example works around known issues in the API:." + Need to check all that clearing is still strictly necessary in DKPY2 which handles race conditions more gracefully. diff --git a/docs/examples/simple_goto.rst b/docs/examples/simple_goto.rst index c300bd7bf..0440eef39 100644 --- a/docs/examples/simple_goto.rst +++ b/docs/examples/simple_goto.rst @@ -120,14 +120,12 @@ Flying to a point - Goto ------------------------ The vehicle is already in ``GUIDED`` mode, so to send it to a certain point we just need to -call :py:func:`Vehicle.commands.goto() ` with the target location, -and then :py:func:`flush() ` the command: +call :py:func:`Vehicle.commands.goto() ` with the target ``LocationGlobal``: .. code-block:: python - point1 = Location(-35.361354, 149.165218, 20, is_relative=True) + point1 = LocationGlobal(-35.361354, 149.165218, 20, is_relative=True) vehicle.commands.goto(point1) - vehicle.flush() # sleep so we can see the change in map time.sleep(30) @@ -148,7 +146,6 @@ To return to the home position and land, we set the mode to ``RTL``: .. code-block:: python vehicle.mode = VehicleMode("RTL") - vehicle.flush() Source code diff --git a/docs/examples/vehicle_state.rst b/docs/examples/vehicle_state.rst index 2f2497626..6f4c5bacf 100644 --- a/docs/examples/vehicle_state.rst +++ b/docs/examples/vehicle_state.rst @@ -7,15 +7,15 @@ Example: Vehicle State This example shows how to get/set vehicle attribute and parameter information, how to observe vehicle attribute changes, and how to get the home position. -The guide topic :ref:`vehicle-information` provides a more detailed explanation of how the API -should be used. +The guide topic :ref:`vehicle-information` provides a more detailed explanation +of how the API should be used. Running the example =================== -The example can be run as described in :doc:`running_examples` (which in turn assumes that the vehicle -and DroneKit have been set up as described in :ref:`get-started`). +The example can be run as described in :doc:`running_examples` (which in turn assumes that +the vehicle and DroneKit have been 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. You can also @@ -56,7 +56,8 @@ On the command prompt you should see (something like): Accumulating vehicle attribute messages (2s) Get all vehicle attribute values: - Location: Location:lat=-35.3632601,lon=149.1652279,alt=-0.00999999977648,is_relative=False + Global Location: LocationGlobal:lat=-35.363261,lon=149.1652299,alt=0.0,is_relative=False + Local Location: LocationLocal:north=None,east=None,down=None Attitude: Attitude:pitch=0.00486609805375,yaw=0.489637970924,roll=0.00645932834595 Velocity: [-0.12, 0.06, 0.0] GPS: GPSInfo:fix=3,num_sat=10 @@ -117,10 +118,8 @@ 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. -Two cases where you may observe issues are: +You may observe these issues: -* You will see an error ``Timeout setting THR_MIN to 10.000000``. This can be ignored because the value is actually set. - See `#12 Timeout error when setting a parameter `_ for information. * When the observer sets the mode callback, it waits two seconds after changing the mode before removing the observer (to ensure that the callback function is run before the observer is removed). In this time you may see the callback being called twice even though the mode is only changed once. diff --git a/docs/guide/auto_mode.rst b/docs/guide/auto_mode.rst index 1dceb29b1..6cbeb4426 100644 --- a/docs/guide/auto_mode.rst +++ b/docs/guide/auto_mode.rst @@ -217,7 +217,6 @@ To start a mission change the mode to AUTO: # Set the vehicle into auto mode vehicle.mode = VehicleMode("AUTO") - vehicle.flush() .. note:: @@ -344,8 +343,8 @@ The commands are added to a list which is returned by the function. 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()) + 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 @@ -417,8 +416,8 @@ Get distance to waypoint lat=missionitem.x lon=missionitem.y alt=missionitem.z - targetWaypointLocation=Location(lat,lon,alt,is_relative=True) - distancetopoint = get_distance_metres(vehicle.location, targetWaypointLocation) + targetWaypointLocation=LocationGlobal(lat,lon,alt,is_relative=True) + distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation) return distancetopoint The function determines the current target waypoint number with :py:func:`Vehicle.commands.next ` diff --git a/docs/guide/copter/guided_mode.rst b/docs/guide/copter/guided_mode.rst index 4c8d5a480..861d4950b 100644 --- a/docs/guide/copter/guided_mode.rst +++ b/docs/guide/copter/guided_mode.rst @@ -37,7 +37,7 @@ Position control Controlling the vehicle by explicitly setting the target position is useful when the final position is known/fixed. -The recommended method for position control is :py:func:`Vehicle.commands.goto() `. This takes a :py:class:`Location ` argument for the target position in the global `WGS84 coordinate system `_, but with altitude relative to the home location (home altitude = 0). +The recommended method for position control is :py:func:`Vehicle.commands.goto() `. This takes a :py:class:`LocationGlobal ` argument for the target position in the global `WGS84 coordinate system `_, but with altitude relative to the home location (home altitude = 0). The method is used as shown below: @@ -46,10 +46,10 @@ The method is used as shown below: # 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 and then call flush() - a_location = Location(-34.364114, 149.166022, 30, is_relative=True) + # Set the target location in global frame + a_location = LocationGlobal(-34.364114, 149.166022, 30, is_relative=True) vehicle.commands.goto(a_location) - vehicle.flush() + ``Vehicle.commands.goto()`` can be interrupted by a later command, and does not provide any functionality to indicate when the vehicle has reached its destination. Developers can use either a time delay or :ref:`measure proximity to the target ` to give the vehicle an opportunity to reach its destination. The :ref:`example-guided-mode-setting-speed-yaw` shows both approaches. @@ -88,12 +88,12 @@ which is used to directly specify the speed components of the vehicle. 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() - + + The ``type_mask`` parameter is a bitmask that indicates which of the other parameters in the message are used/ignored by the vehicle (0 means that the dimension is enabled, 1 means ignored). In the example the value 0b0000111111000111 is used to enable the velocity components. - + The speed components ``velocity_x`` and ``velocity_y`` are parallel to the North and East directions (not to the front and side of the vehicle). The ``velocity_z`` component is perpendicular to the plane of ``velocity_x`` and ``velocity_y``, with a positive value **towards the ground**, following the right-hand convention. For more information about the ``mavutil.mavlink.MAV_FRAME_BODY_NED`` frame of reference, see this wikipedia article @@ -140,7 +140,7 @@ ArduPilot does not currently support controlling the vehicle by specifying accel -.. _guided_mode_copter_commands: +.. _guided_mode_copter_commands: Guided mode commands ===================== @@ -153,7 +153,7 @@ This section explains how to send MAVLink commands, what commands can be sent, a Sending messages/commands ------------------------- -MAVLink commands are sent by first using :py:func:`message_factory ` to encode the message and then calling :py:func:`send_mavlink ` and ``flush()`` to send them. +MAVLink commands are sent by first using :py:func:`message_factory ` to encode the message and then calling :py:func:`send_mavlink ` to send them. ``message_factory()`` uses a factory method for the encoding. The name of this method will always be the lower case version of the message/command name with ``_encode`` appended. For example, to encode a `SET_POSITION_TARGET_LOCAL_NED `_ message we call ``message_factory.set_position_target_local_ned_encode()`` with values for all the message fields as arguments: @@ -170,8 +170,7 @@ MAVLink commands are sent by first using :py:func:`message_factory `_ command to point camera gimbal at a specified region of interest (:py:class:`Location `). The vehicle may also turn to face the ROI. - +Send the `MAV_CMD_DO_SET_ROI `_ command to point camera gimbal at a specified region of interest (:py:class:`LocationGlobal `). The vehicle may also turn to face the ROI. + .. code-block:: python def set_roi(location): @@ -304,13 +299,12 @@ Send the `MAV_CMD_DO_SET_ROI `_ - command with zero in all parameters. The front of the vehicle will then follow the direction of travel. - + command with zero in all parameters. The front of the vehicle will then follow the direction of travel. + The ROI (and yaw) is also reset when the mode, or the command used to control movement, is changed. @@ -329,29 +323,28 @@ Send the `MAV_CMD_DO_SET_HOME =aTargetAltitude*0.95: #Just below target, in case of undershoot. + print " Altitude: ", vehicle.location.global_frame.alt + if vehicle.location.global_frame.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. print "Reached target altitude" break time.sleep(1) @@ -86,9 +83,8 @@ vehicle has booted and has a GPS lock: print "Waiting for GPS...:", vehicle.gps_0.fix_type time.sleep(1) -Once the vehicle is ready we set the mode to ``GUIDED`` and arm it. We then call :py:func:`flush() ` -to guarantee that the commands have been sent, and then wait until arming is confirmed before sending the -:py:func:`takeoff ` command. +Once the vehicle is ready we set the mode to ``GUIDED`` and arm it. We then wait until arming is confirmed +before sending the :py:func:`takeoff ` command. .. code-block:: python @@ -96,7 +92,6 @@ to guarantee that the commands have been sent, and then wait until arming is con # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True - vehicle.flush() while not vehicle.armed: print " Waiting for arming..." @@ -104,7 +99,6 @@ to guarantee that the commands have been sent, and then wait until arming is con print "Taking off!" vehicle.commands.takeoff(aTargetAltitude) # Take off to target altitude - vehicle.flush() The ``takeoff`` command is asynchronous and can be interrupted if another command arrives before it reaches the target altitude. This could have potentially serious consequences if the vehicle is commanded to move @@ -117,8 +111,8 @@ concerned about reaching a particular height, a simpler implementation might jus .. code-block:: python while True: - print " Altitude: ", vehicle.location.alt - if vehicle.location.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. + print " Altitude: ", vehicle.location.global_frame.alt + if vehicle.location.global_frame.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. print "Reached target altitude" break time.sleep(1) diff --git a/docs/guide/vehicle_state_and_parameters.rst b/docs/guide/vehicle_state_and_parameters.rst index d7c133fb1..d5e08606e 100644 --- a/docs/guide/vehicle_state_and_parameters.rst +++ b/docs/guide/vehicle_state_and_parameters.rst @@ -50,7 +50,8 @@ The code fragment below shows how to read and print all the attributes. The valu .. code:: python # vehicle is an instance of the Vehicle class - print "Location: %s" % vehicle.location + print "Global Location: %s" % vehicle.location.global_frame + print "Local Location: %s" % vehicle.location.local_frame #NED print "Attitude: %s" % vehicle.attitude print "Velocity: %s" % vehicle.velocity print "GPS: %s" % vehicle.gps_0 @@ -91,22 +92,21 @@ Setting attributes Only the :py:attr:`Vehicle.mode ` and :py:attr:`Vehicle.armed ` attributes can be written. -The attributes are set by assigning a value. Calling :py:func:`Vehicle.flush() ` -then forces DroneKit to send outstanding messages. +The attributes are set by assigning a value: .. code:: python #disarm the vehicle vehicle.armed = False - vehicle.flush() # Flush to ensure changes are sent to autopilot .. warning:: - After ``flush()`` returns the message is guaranteed to have been sent to the autopilot, but it is **not guaranteed to succeed**. + Changing a value is **not guaranteed to succeed**. For example, vehicle arming can fail if the vehicle doesn't pass pre-arming checks. - While the autopilot does send information about the success (or failure) of the request, this is `not currently handled by DroneKit `_. + While the autopilot does send information about the success (or failure) of the request, + this is `not currently handled by DroneKit `_. Code should not assume that an attempt to set an attribute will succeed. The example code snippet below polls the attribute values @@ -116,7 +116,6 @@ to confirm they have changed before proceeding. vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True - vehicle.flush() # Flush to ensure changes are sent to autopilot while not vehicle.mode.name=='GUIDED' and not vehicle.armed and not api.exit: print " Getting ready to take off ..." time.sleep(1) @@ -142,8 +141,9 @@ attribute changes. The two second ``sleep()`` is required because otherwise the # Callback function. The parameter is the name of the observed attribute (a string) def location_callback(attribute): - print " CALLBACK: Location changed to: ", vehicle.location - + print " CALLBACK: Global Location changed to: ", vehicle.location.global_frame + print " CALLBACK: Location changed to: ", vehicle.location.local_frame + # Add a callback. The first parameter the name of the observed attribute (a string). vehicle.add_attribute_observer('location', location_callback) @@ -156,7 +156,8 @@ attribute changes. The two second ``sleep()`` is required because otherwise the The callback is triggered every time a message is received from the vehicle (whether or not the observed attribute changes). Callback code may therefore choose to cache the result and only report changes. -For example, the following code can be used in the callback to only print output when the value of :py:attr:`Vehicle.rangefinder ` changes. +For example, the following code can be used in the callback to only print output when the value of +:py:attr:`Vehicle.rangefinder ` changes. .. code:: python @@ -213,15 +214,12 @@ throttle at which the motors will keep spinning. Setting parameters ------------------ -Vehicle parameters are set as shown in the code fragment below, using the parameter name as a "key". As with attributes, the values are not guaranteed to have been sent to the vehicle until after -:py:func:`flush() ` returns. +Vehicle parameters are set as shown in the code fragment below, using the parameter name as a "key": .. code:: python # Change the parameter value (Copter, Rover) vehicle.parameters['THR_MIN']=100 - vehicle.flush() - Observing parameter changes diff --git a/dronekit/lib/__init__.py b/dronekit/lib/__init__.py index 951668fc7..4cc9ddac4 100644 --- a/dronekit/lib/__init__.py +++ b/dronekit/lib/__init__.py @@ -4,34 +4,55 @@ This is the API Reference for the DroneKit-Python API. The main API is the :py:class:`Vehicle ` class. -The code snippet below shows how to obtain an instance of the (first) connected vehicle: +The code snippet below shows how to use :py:func:`connect` to obtain an instance a connected vehicle: .. code:: python - # Get a local APIConnection to the autopilot (from companion computer or GCS). - api_connection = local_connect() - # Get the first connected vehicle from the APIConnection - vehicle = api.get_vehicles()[0] + from dronekit import connect + + # Connect to the Vehicle using "connection string" (in this case an address on network) + vehicle = connect('127.0.0.1:14550', await_params=True) + :py:class:`Vehicle ` provides access to vehicle *state* through python attributes -(e.g. :py:attr:`Vehicle.location `) +(e.g. :py:attr:`Vehicle.mode `) and to settings/parameters though the :py:attr:`Vehicle.parameters ` attribute. Asynchronous notification on vehicle attribute changes is available by registering observers. :py:class:`Vehicle ` provides two main ways to control vehicle movement and other operations: -* Missions are downloaded and uploaded through the :py:attr:`Vehicle.commands ` attribute - (see :py:class:`CommandSequence ` for more information). * Direct control of movement outside of missions is also supported. To set a target position you can use :py:func:`CommandSequence.goto `. Control over speed, direction, altitude, camera trigger and any other aspect of the vehicle is supported using custom MAVLink messages (:py:func:`Vehicle.send_mavlink `, :py:func:`Vehicle.message_factory `). - +* Missions are downloaded and uploaded through the :py:attr:`Vehicle.commands ` attribute + (see :py:class:`CommandSequence ` for more information). + A number of other useful classes and methods are listed below. ---- .. todo:: Update this when have confirmed how to register for parameter notifications. + + + +.. py:function:: connect(ip, await_params=False, status_printer=errprinter, vehicle_class=Vehicle, rate=4) + + Returns a :py:class:`Vehicle` object connected to the address specified by string parameter ``ip``. + Connection string parameters for different targets are listed in the :ref:`getting started guide `. + + :param String ip: Connection string for target address - e.g. 127.0.0.1:14550. + :param Bool await_params: Wait until all :py:func:`Vehicle.parameters` have downloaded before the method returns (default is false) + :param status_printer: NA + :param Vehicle vehicle_class: NA + :param int rate: NA + + :returns: A connected :py:class:`Vehicle` object. + +---- + + .. todo:: Confirm what status_printer, vehicle_class and rate "mean". Can we hide in API. Can we get method defined in this file. + """ import threading @@ -124,11 +145,11 @@ class LocationGlobal(object): The latitude and longitude are relative to the `WGS84 coordinate system `_. The altitude is relative to either the *home position* or "mean sea-level", depending on the value of the ``is_relative``. - For example, a location object might be defined as: + For example, a global location object might be defined as: .. code:: python - Location(-34.364114, 149.166022, 30, is_relative=True) + LocationGlobal(-34.364114, 149.166022, 30, is_relative=True) .. todo:: FIXME: Location class - possibly add a vector3 representation. @@ -266,10 +287,6 @@ def mode_callback(self, mode): .. 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") @@ -355,19 +372,22 @@ def add_attribute_observer(self, attr_name, observer): """ Add an attribute observer. - The observer is called with the ``attr_name`` argument. This can be used to access - the vehicle parameter, as shown below: + The observer callback function is called with the ``attr_name`` argument. + This can be used to infer the related attribute if the same callback is used + for watching several attributes. + + The example below shows how to get callbacks for location changes: .. code:: python - #Add observer for the vehicle's current location - vehicle.add_attribute_observer('location', location_callback) - - #Callback to print the location + #Callback to print the location in global and local frames def location_callback(location): - print "Location: ", vehicle.location - + print "Location (Global): ", vehicle.location.global_frame + print "Location (Local): ", vehicle.location.local_frame + #Add observer for the vehicle's current location + vehicle.add_attribute_observer('location', location_callback) + .. note:: Attribute changes will only be published for changes due to some other entity. They will not be published for changes made by the local API client @@ -376,7 +396,7 @@ def location_callback(location): :param attr_name: The attribute to watch. :param observer: The callback to invoke when a change in the attribute is detected. - .. todo:: Check that the defect for endless repetition after thread closes is fixed: https://github.com/dronekit/dronekit-python/issues/74 + """ l = self.__observers.get(attr_name) if l is None: @@ -389,11 +409,11 @@ def remove_attribute_observer(self, attr_name, observer): """ Remove an observer. - For example, the following line would remove a previously added vehicle 'location' observer called location_callback: + For example, the following line would remove a previously added vehicle 'global_frame' observer called location_callback: .. code:: python - vehicle.remove_attribute_observer('location', location_callback) + vehicle.remove_attribute_observer('global_frame', location_callback) :param attr_name: The attribute name that is to have an observer removed. @@ -565,11 +585,9 @@ class Vehicle(HasObservers): # Override channels 1 and 4 (only). vehicle.channel_override = { "1" : 900, "4" : 1000 } - vehicle.flush() # Cancel override on channel 1 and 4 by sending 0 vehicle.channel_override = { "1" : 0, "4" : 0 } - vehicle.flush() .. versionchanged:: 1.0 @@ -779,10 +797,9 @@ def unset_mavlink_callback(self): def flush(self): """ - It is important to understand that setting attributes/changing vehicle state may occur over a slow link. + Call ``flush()`` after :py:func:`adding ` or :py:func:`clearing ` mission commands. - It is **not** guaranteed that the effects of previous commands will be visible from reading vehicle attributes unless - ``flush()`` is called first. After the return from flush any writes are guaranteed to have completed (or thrown an + After the return from ``flush()`` any writes are guaranteed to have completed (or thrown an exception) and future reads will see their effects. """ pass @@ -816,9 +833,11 @@ class Mission(object): """ Access to historical missions. - .. warning:: This function is a *placeholder*. It has no implementation in DroneKit-Python release 1. + .. warning:: + + This function is a *placeholder*. It has no implementation in DroneKit-Python release 1. - Mission objects are only accessible from the REST API in release 1 (most use-cases requiring missions prefer a REST interface). + Mission objects are only accessible from the REST API in release 1 (most use-cases requiring missions prefer a REST interface). .. todo:: FIXME: Mission class needs to be updated when it is implemented (after DroneKit Python release 1). """ @@ -831,7 +850,6 @@ class Parameters(HasObservers): `Plane `_, `Rover `_. Attribute names are generated automatically based on parameter names. The example below shows how to get and set the value of a parameter. - Note that 'set' operations are not guaranteed to be complete until :py:func:`flush() ` is called on the parent :py:class:`Vehicle` object. .. code:: python @@ -840,7 +858,7 @@ class Parameters(HasObservers): # Change the parameter value to something different. vehicle.parameters['THR_MIN']=100 - vehicle.flush() + .. note:: @@ -910,9 +928,8 @@ class CommandSequence(object): .. code-block:: python :emphasize-lines: 5-10 - # Connect to API provider and get vehicle - api = local_connect() - vehicle = api.get_vehicles()[0] + #Connect to a vehicle object (for example, on com14) + vehicle = connect('com14', await_params=True) # Download the vehicle waypoints (commands). Wait until download is complete. cmds = vehicle.commands @@ -976,19 +993,20 @@ def wait_valid(self): def goto(self, location): ''' - Go to a specified location (changing :py:class:`VehicleMode` to ``GUIDED`` if necessary). + Go to a specified global location (:py:class:`LocationGlobal`). + + The method will change the :py:class:`VehicleMode` to ``GUIDED`` if necessary. .. code:: python # Set mode to guided - this is optional as the goto method will change the mode if needed. vehicle.mode = VehicleMode("GUIDED") - # Set the location to goto() and flush() - a_location = Location(-34.364114, 149.166022, 30, is_relative=True) + # Set the LocationGlobal to head towards + a_location = LocationGlobal(-34.364114, 149.166022, 30, is_relative=True) vehicle.commands.goto(a_location) - vehicle.flush() - :param Location location: The target location. + :param LocationGlobal location: The target location. ''' pass @@ -1008,6 +1026,8 @@ def clear(self): def add(self, cmd): ''' Add a new command (waypoint) at the end of the command list. + + .. note:: Commands are sent to the vehicle only after you call :py:func:`Vehicle.flush`. :param Command cmd: The command to be added. ''' diff --git a/examples/channel_overrides/channel_overrides.py b/examples/channel_overrides/channel_overrides.py index 0ff0ed2d7..89066ce0b 100644 --- a/examples/channel_overrides/channel_overrides.py +++ b/examples/channel_overrides/channel_overrides.py @@ -33,7 +33,6 @@ #Override channels print "\nOverriding RC channels for roll and yaw" vehicle.channel_override = { "1" : 900, "4" : 1000 } -vehicle.flush() print " Current overrides are:", vehicle.channel_override # Get all original channel values (before override) @@ -42,7 +41,6 @@ # Cancel override by setting channels to 0 print " Cancelling override" vehicle.channel_override = { "1" : 0, "4" : 0 } -vehicle.flush() # Short wait before exiting time.sleep(5) diff --git a/examples/drone_delivery/drone_delivery.py b/examples/drone_delivery/drone_delivery.py index 496f0a00f..85a1d21bd 100644 --- a/examples/drone_delivery/drone_delivery.py +++ b/examples/drone_delivery/drone_delivery.py @@ -11,7 +11,7 @@ from pymavlink import mavutil import dronekit.lib from dronekit import connect -from dronekit.lib import VehicleMode, Location +from dronekit.lib import VehicleMode, LocationGlobal import cherrypy from cherrypy.process import wspbus, plugins @@ -68,12 +68,10 @@ def __init__(self, home_coords, server_enabled=True): def takeoff(self): self._log("Taking off") self.commands.takeoff(30.0) - self.vehicle.flush() def arm(self): self._log("Arming") self.vehicle.armed = True - self.vehicle.flush() def run(self): self._log('Running initial boot sequence') @@ -98,9 +96,8 @@ def _run_server(self): def change_mode(self, mode): self._log("Mode: {0}".format(mode)) - self.vehicle.mode = VehicleMode(mode) - self.vehicle.flush() + def goto(self, location, relative=None): self._log("Goto: {0}, {1}".format(location, self.altitude)) @@ -112,13 +109,12 @@ def goto(self, location, relative=None): is_relative=relative ) ) - self.vehicle.flush() def get_location(self): return [self.current_location.lat, self.current_location.lon] def location_callback(self, location): - location = self.vehicle.location + location = self.vehicle.location.global_frame if location.alt is not None: self.altitude = location.alt diff --git a/examples/follow_me/follow_me.py b/examples/follow_me/follow_me.py index 253f9ca44..2db35cdd7 100644 --- a/examples/follow_me/follow_me.py +++ b/examples/follow_me/follow_me.py @@ -14,7 +14,8 @@ import gps import socket import time -from dronekit.lib import VehicleMode, Location +import sys +from dronekit.lib import VehicleMode, LocationGlobal #Set up option parsing to get connection string import argparse @@ -47,7 +48,6 @@ def arm_and_takeoff(aTargetAltitude): # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True - vehicle.flush() while not vehicle.armed: print " Waiting for arming..." @@ -55,13 +55,12 @@ def arm_and_takeoff(aTargetAltitude): 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 True: - print " Altitude: ", vehicle.location.alt - if vehicle.location.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. + print " Altitude: ", vehicle.location.global_frame.alt + if vehicle.location.global_frame.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. print "Reached target altitude" break; time.sleep(1) @@ -87,12 +86,11 @@ def arm_and_takeoff(aTargetAltitude): # Once we have a valid location (see gpsd documentation) we can start moving our vehicle around if (gpsd.valid & gps.LATLON_SET) != 0: altitude = 30 # in meters - dest = Location(gpsd.fix.latitude, gpsd.fix.longitude, altitude, is_relative=True) + dest = LocationGlobal(gpsd.fix.latitude, gpsd.fix.longitude, altitude, is_relative=True) print "Going to: %s" % dest # A better implementation would only send new waypoints if the position had changed significantly vehicle.commands.goto(dest) - vehicle.flush() # Send a new target every two seconds # For a complete implementation of follow me you'd want adjust this delay diff --git a/examples/gcs/microgcs.py b/examples/gcs/microgcs.py index 6b1ed878d..720589416 100644 --- a/examples/gcs/microgcs.py +++ b/examples/gcs/microgcs.py @@ -1,10 +1,8 @@ # # This is a small example of the python drone API - an ultra minimal GCS -# Usage: -# * mavproxy.py --master=/dev/ttyACM0,115200 -# * module load api -# * api start microgcs.py # + +from dronekit import connect from dronekit.lib import VehicleMode from pymavlink import mavutil from Tkinter import * @@ -12,17 +10,22 @@ # The tkinter root object global root -# First get an instance of the API endpoint -api = local_connect() -# get our vehicle - when running with mavproxy it only knows about one vehicle (for now) -v = api.get_vehicles()[0] +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Tracks GPS position of your computer (Linux only). Connects to SITL on local PC by default.') +parser.add_argument('--connect', default='127.0.0.1:14550', + help="vehicle connection target. Default '127.0.0.1:14550'") +args = parser.parse_args() + + +# Connect to the Vehicle +print 'Connecting to vehicle on: %s' % args.connect +vehicle = connect(args.connect, await_params=True) def setMode(mode): # Now change the vehicle into auto mode - v.mode = VehicleMode(mode) + vehicle.mode = VehicleMode(mode) - # Always call flush to guarantee that previous writes to the vehicle have taken place - v.flush() def updateGUI(label, value): label['text'] = value @@ -30,7 +33,7 @@ def updateGUI(label, value): def addObserverAndInit(name, cb): """We go ahead and call our observer once at startup to get an initial value""" cb(name) - v.add_attribute_observer(name, cb) + vehicle.add_attribute_observer(name, cb) root = Tk() root.wm_title("microGCS - the worlds crummiest GCS") @@ -44,9 +47,9 @@ def addObserverAndInit(name, cb): modeLabel = Label(frame, text = "mode") modeLabel.pack() -addObserverAndInit('attitude', lambda attr: updateGUI(attitudeLabel, v.attitude)) -addObserverAndInit('location', lambda attr: updateGUI(locationLabel, v.location)) -addObserverAndInit('mode', lambda attr: updateGUI(modeLabel, v.mode)) +addObserverAndInit('attitude', lambda attr: updateGUI(attitudeLabel, vehicle.attitude)) +addObserverAndInit('location', lambda attr: updateGUI(locationLabel, vehicle.location)) +addObserverAndInit('mode', lambda attr: updateGUI(modeLabel, vehicle.mode)) Button(frame, text = "Auto", command = lambda : setMode("AUTO")).pack() Button(frame, text = "RTL", command = lambda : setMode("RTL")).pack() diff --git a/examples/guided_set_speed_yaw/guided_set_speed_yaw.py b/examples/guided_set_speed_yaw/guided_set_speed_yaw.py index 818e11fbc..f658dd275 100644 --- a/examples/guided_set_speed_yaw/guided_set_speed_yaw.py +++ b/examples/guided_set_speed_yaw/guided_set_speed_yaw.py @@ -7,7 +7,7 @@ """ from dronekit import connect -from dronekit.lib import VehicleMode, Location +from dronekit.lib import VehicleMode, LocationGlobal from pymavlink import mavutil import time import math @@ -43,21 +43,20 @@ def arm_and_takeoff(aTargetAltitude): # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True - vehicle.flush() while not vehicle.armed: print " Waiting for arming..." + vehicle.armed = True 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 True: - print " Altitude: ", vehicle.location.alt - if vehicle.location.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. + print " Altitude: ", vehicle.location.global_frame.alt + if vehicle.location.global_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. print "Reached target altitude" break; time.sleep(1) @@ -112,12 +111,12 @@ def condition_yaw(heading, relative=False): 0, 0, 0) # param 5 ~ 7 not used # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() def set_roi(location): """ - Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a specified region of interest (Location). + Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a + specified region of interest (LocationGlobal). The vehicle may also turn to face the ROI. For more information see: @@ -135,7 +134,6 @@ def set_roi(location): ) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() def set_speed(speed): @@ -163,12 +161,11 @@ def set_speed(speed): # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() def set_home(aLocation, aCurrent=1): """ - Send MAV_CMD_DO_SET_HOME command to set the Home location to either the current location + Send MAV_CMD_DO_SET_HOME command to set the Home location to either the current LocationGlobal or a specified location. For more information see: @@ -188,7 +185,6 @@ def set_home(aLocation, aCurrent=1): ) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() @@ -201,15 +197,15 @@ def set_home(aLocation, aCurrent=1): to the Earth's poles. Specifically, it provides: -* get_location_metres - Get Location (decimal degrees) at distance (m) North & East of a given Location. -* get_distance_metres - Get the distance between two Location objects in metres -* get_bearing - Get the bearing in degrees to a Location +* get_location_metres - Get LocationGlobal (decimal degrees) at distance (m) North & East of a given LocationGlobal. +* get_distance_metres - Get the distance between two LocationGlobal objects in metres +* get_bearing - Get the bearing in degrees to a LocationGlobal """ 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 + Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the + specified `original_location`. The returned LocationGlobal 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 @@ -228,12 +224,12 @@ def get_location_metres(original_location, dNorth, dEast): #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) + return LocationGlobal(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. + Returns the ground distance in metres between two LocationGlobal objects. This method is an approximation, and will not be accurate over large distances and close to the earth's poles. It comes from the ArduPilot test code: @@ -246,7 +242,7 @@ def get_distance_metres(aLocation1, aLocation2): def get_bearing(aLocation1, aLocation2): """ - Returns the bearing between the two Location objects passed as parameters. + Returns the bearing between the two LocationGlobal objects passed as parameters. This method is an approximation, and may not be accurate over large distances and close to the earth's poles. It comes from the ArduPilot test code: @@ -277,7 +273,7 @@ def get_bearing(aLocation1, aLocation2): def goto_position_target_global_int(aLocation): """ - Send SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified location. + Send SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified LocationGlobal. For more information see: https://pixhawk.ethz.ch/mavlink/#SET_POSITION_TARGET_GLOBAL_INT @@ -300,7 +296,6 @@ def goto_position_target_global_int(aLocation): 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() @@ -334,7 +329,6 @@ def goto_position_target_local_ned(north, east, down): 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() @@ -342,21 +336,20 @@ def goto(dNorth, dEast, gotoFunction=vehicle.commands.goto): """ Moves the vehicle to a position dNorth metres North and dEast metres East of the current position. - The method takes a function pointer argument with a single `dronekit.lib.Location` parameter for + The method takes a function pointer argument with a single `dronekit.lib.LocationGlobal` parameter for the target position. This allows it to be called with different position-setting commands. By default it uses the standard method: dronekit.lib.Vehicle.commands.goto(). The method reports the distance to target every two seconds. """ - currentLocation=vehicle.location + currentLocation=vehicle.location.global_frame targetLocation=get_location_metres(currentLocation, dNorth, dEast) targetDistance=get_distance_metres(currentLocation, targetLocation) gotoFunction(targetLocation) - vehicle.flush() while vehicle.mode.name=="GUIDED": #Stop action if we are no longer in guided mode. - remainingDistance=get_distance_metres(vehicle.location, targetLocation) + remainingDistance=get_distance_metres(vehicle.location.global_frame, targetLocation) print "Distance to target: ", remainingDistance if remainingDistance<=targetDistance*0.01: #Just below target, in case of undershoot. print "Reached target" @@ -395,7 +388,6 @@ def send_ned_velocity(velocity_x, velocity_y, velocity_z): 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() @@ -412,7 +404,7 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z): msg = vehicle.message_factory.set_position_target_global_int_encode( 0, # time_boot_ms (not used) 0, 0, # target system, target component - mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, # frame + mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, # frame 0b0000111111000111, # type_mask (only speeds enabled) 0, # lat_int - X Position in WGS84 frame in 1e7 * meters 0, # lon_int - Y Position in WGS84 frame in 1e7 * meters @@ -425,7 +417,6 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z): 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle vehicle.send_mavlink(msg) - vehicle.flush() @@ -448,6 +439,8 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z): + + """ Fly a triangular path using the SET_POSITION_TARGET_GLOBAL_INT command and specifying a target position (rather than controlling movement using velocity vectors). The command is @@ -505,7 +498,7 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z): print("Point ROI at current location (home position)") # NOTE that this has to be called after the goto command as first "move" command of a particular type # "resets" ROI/YAW commands -set_roi(vehicle.location) +set_roi(vehicle.location.global_frame) time.sleep(DURATION) print("North 50m, East 50m, 10m altitude") @@ -513,7 +506,7 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z): time.sleep(DURATION) print("Point ROI at current location") -set_roi(vehicle.location) +set_roi(vehicle.location.global_frame) print("North 0m, East 50m, 10m altitude") goto_position_target_local_ned(0,50,-10) @@ -614,7 +607,7 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z): send_global_velocity(0,0,0) print("Set new Home location to current location") -set_home(vehicle.location) +set_home(vehicle.location.global_frame) print "Get new home location" #This reloads the home location in GCSs cmds = vehicle.commands cmds.download() @@ -642,7 +635,6 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z): print("Setting LAND mode...") vehicle.mode = VehicleMode("LAND") -vehicle.flush() #Close vehicle object before exiting script diff --git a/examples/mission_basic/mission_basic.py b/examples/mission_basic/mission_basic.py index c644ef555..56a4ad2f3 100644 --- a/examples/mission_basic/mission_basic.py +++ b/examples/mission_basic/mission_basic.py @@ -7,7 +7,7 @@ from dronekit import connect import time import math -from dronekit.lib import VehicleMode, Location, Command +from dronekit.lib import VehicleMode, LocationGlobal, Command from pymavlink import mavutil @@ -26,7 +26,7 @@ def get_location_metres(original_location, dNorth, dEast): """ - Returns a Location object containing the latitude/longitude `dNorth` and `dEast` metres from the + Returns a LocationGlobal 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`. @@ -44,12 +44,12 @@ def get_location_metres(original_location, dNorth, dEast): #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) + return LocationGlobal(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. + Returns the ground distance in metres between two LocationGlobal objects. This method is an approximation, and will not be accurate over large distances and close to the earth's poles. It comes from the ArduPilot test code: @@ -73,8 +73,8 @@ def distance_to_current_waypoint(): lat=missionitem.x lon=missionitem.y alt=missionitem.z - targetWaypointLocation=Location(lat,lon,alt,is_relative=True) - distancetopoint = get_distance_metres(vehicle.location, targetWaypointLocation) + targetWaypointLocation=LocationGlobal(lat,lon,alt,is_relative=True) + distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation) return distancetopoint @@ -107,7 +107,7 @@ def download_mission(): 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 waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation). The function assumes vehicle.commands matches the vehicle mission state (you must have called download at least once in the session and after clearing the mission) @@ -151,7 +151,6 @@ def arm_and_takeoff(aTargetAltitude): # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True - vehicle.flush() while not vehicle.armed: print " Waiting for arming..." @@ -159,13 +158,12 @@ def arm_and_takeoff(aTargetAltitude): 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 True: - print " Altitude: ", vehicle.location.alt - if vehicle.location.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. + print " Altitude: ", vehicle.location.global_frame.alt + if vehicle.location.global_frame.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. print "Reached target altitude" break; time.sleep(1) @@ -176,7 +174,7 @@ def arm_and_takeoff(aTargetAltitude): clear_mission() print 'Create a new mission' -adds_square_mission(vehicle.location,50) +adds_square_mission(vehicle.location.global_frame,50) time.sleep(2) # This is here so that mission being sent is displayed on console @@ -186,7 +184,7 @@ def arm_and_takeoff(aTargetAltitude): 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 @@ -207,7 +205,7 @@ def arm_and_takeoff(aTargetAltitude): print 'Return to launch' vehicle.mode = VehicleMode("RTL") -vehicle.flush() # Flush to ensure changes are sent to autopilot + #Close vehicle object before exiting script print "Close vehicle object" diff --git a/examples/perf/perf_test.py b/examples/perf/perf_test.py index 03a334e53..e43d590d3 100644 --- a/examples/perf/perf_test.py +++ b/examples/perf/perf_test.py @@ -1,10 +1,7 @@ # # This is a small example of the python drone API -# Usage: -# * mavproxy.py -# * module load api -# * api start small-demo.py # +from dronekit import connect from dronekit.lib import VehicleMode from pymavlink import mavutil import time @@ -103,7 +100,19 @@ mavproxy.py --master=/dev/ttyMFD1,115200 --cmd="api start perf_test.py" """ -global v +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Example that demonstrates mission import/export from a file. Connects to SITL on local PC by default.') +parser.add_argument('--connect', default='127.0.0.1:14550', + help="vehicle connection target. Default '127.0.0.1:14550'") +args = parser.parse_args() + + +# Connect to the Vehicle +print 'Connecting to vehicle on: %s' % args.connect +vehicle = connect(args.connect, await_params=True) + +#global vehicle def scatterplot(x,y): @@ -168,7 +177,7 @@ def send_testpackets(): #print "send ROI cmds" # create the SET_POSITION_TARGET_GLOBAL_INT command - msg = v.message_factory.set_position_target_global_int_encode( + msg = vehicle.message_factory.set_position_target_global_int_encode( 0, # time_boot_ms (not used) 1, 1, # target system, target component mavutil.mavlink.MAV_FRAME_GLOBAL, # frame @@ -179,10 +188,10 @@ def send_testpackets(): 0, 0) # yaw, yaw_rate (not used) # send command to vehicle - v.send_mavlink(msg) + vehicle.send_mavlink(msg) # set ROI - msg = v.message_factory.command_long_encode( + msg = vehicle.message_factory.command_long_encode( 1, 1, # target system, target component #mavutil.mavlink.MAV_CMD_DO_SET_RELAY, #command mavutil.mavlink.MAV_CMD_DO_SET_ROI, #command @@ -193,67 +202,37 @@ def send_testpackets(): 0 ) - v.send_mavlink(msg) + vehicle.send_mavlink(msg) - # Always call flush to guarantee that previous writes to the vehicle have taken place - v.flush() -# First get an instance of the API endpoint -api = local_connect() -# get our vehicle - when running with mavproxy it only knows about one vehicle (for now) -v = api.get_vehicles()[0] # Print out some interesting stats about the vehicle -print "Mode: %s" % v.mode -print "Location: %s" % v.location -print "Attitude: %s" % v.attitude -print "Velocity: %s" % v.velocity -print "GPS: %s" % v.gps_0 -print "Armed: %s" % v.armed -print "groundspeed: %s" % v.groundspeed -print "airspeed: %s" % v.airspeed +print "Mode: %s" % vehicle.mode +print "Location: %s" % vehicle.location +print "Attitude: %s" % vehicle.attitude +print "Velocity: %s" % vehicle.velocity +print "GPS: %s" % vehicle.gps_0 +print "Armed: %s" % vehicle.armed +print "groundspeed: %s" % vehicle.groundspeed +print "airspeed: %s" % vehicle.airspeed import time time.sleep(30) # Use of the following method is not recommended (it is better to add observer callbacks to attributes) but if you need it # it is available... -v.set_mavlink_callback(mavrx_debug_handler) +vehicle.set_mavlink_callback(mavrx_debug_handler) # You can read and write parameters -#print "Param: %s" % v.parameters['THR_MAX'] +#print "Param: %s" % vehicle.parameters['THR_MAX'] # Now download the vehicle waypoints -cmds = v.commands +cmds = vehicle.commands cmds.download() cmds.wait_valid() print "Home WP: %s" % cmds[0] print "Current dest: %s" % cmds.next -# Test custom commands -# Note: For mavlink messages that include a target_system & target_component, those values -# can just be filled with zero. The API will take care of using the correct values -# For instance, from the xml for command_long: -# Send a command with up to seven parameters to the MAV -# -# target_system : System which should execute the command (uint8_t) -# target_component : Component which should execute the command, 0 for all components (uint8_t) -# command : Command ID, as defined by MAV_CMD enum. (uint16_t) -# confirmation : 0: First transmission of this command. 1-255: Confirmation transmissions (e.g. for kill command) (uint8_t) -# param1 : Parameter 1, as defined by MAV_CMD enum. (float) -# param2 : Parameter 2, as defined by MAV_CMD enum. (float) -# param3 : Parameter 3, as defined by MAV_CMD enum. (float) -# param4 : Parameter 4, as defined by MAV_CMD enum. (float) -# param5 : Parameter 5, as defined by MAV_CMD enum. (float) -# param6 : Parameter 6, as defined by MAV_CMD enum. (float) -# param7 : Parameter 7, as defined by MAV_CMD enum. (float) -#msg = v.message_factory.command_long_encode(0, 0, -# mavutil.mavlink.MAV_CMD_CONDITION_YAW, 0, -# 0, 0, 0, 0, 1, 0, 0) -#print "Created msg: %s" % msg -#v.send_mavlink(msg) print "Disarming..." -v.armed = False -v.flush() +vehicle.armed = False -# send_testpackets() diff --git a/examples/simple_goto/simple_goto.py b/examples/simple_goto/simple_goto.py index 53f9d0d0e..10caa358c 100644 --- a/examples/simple_goto/simple_goto.py +++ b/examples/simple_goto/simple_goto.py @@ -8,7 +8,7 @@ import time from dronekit import connect -from dronekit.lib import VehicleMode, Location +from dronekit.lib import VehicleMode, LocationGlobal from pymavlink import mavutil import time @@ -40,25 +40,24 @@ def arm_and_takeoff(aTargetAltitude): 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() + vehicle.armed = True - while not vehicle.armed: + while not vehicle.armed: 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 True: - print " Altitude: ", vehicle.location.alt - if vehicle.location.alt>=aTargetAltitude*0.95: #Just below target, in case of undershoot. + print " Altitude: ", vehicle.location.global_frame.alt + if vehicle.location.global_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. print "Reached target altitude" break time.sleep(1) @@ -67,24 +66,21 @@ def arm_and_takeoff(aTargetAltitude): print "Going to first point..." -point1 = Location(-35.361354, 149.165218, 20, is_relative=True) +point1 = LocationGlobal(-35.361354, 149.165218, 20, is_relative=True) vehicle.commands.goto(point1) -vehicle.flush() # sleep so we can see the change in map time.sleep(30) print "Going to second point..." -point2 = Location(-35.363244, 149.168801, 20, is_relative=True) +point2 = LocationGlobal(-35.363244, 149.168801, 20, is_relative=True) vehicle.commands.goto(point2) -vehicle.flush() # sleep so we can see the change in map time.sleep(30) print "Returning to Launch" vehicle.mode = VehicleMode("RTL") -vehicle.flush() #Close vehicle object before exiting script print "Close vehicle object" diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index 46fa0d4a6..f0cba15ae 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -34,8 +34,8 @@ # Get all vehicle attributes (state) print "\nGet all vehicle attribute values:" -print " Global Location: %s" % v.location.global_frame -print " Local Location: %s" % v.location.local_frame +print " Global Location: %s" % vehicle.location.global_frame +print " Local Location: %s" % vehicle.location.local_frame print " Attitude: %s" % vehicle.attitude print " Velocity: %s" % vehicle.velocity print " GPS: %s" % vehicle.gps_0 @@ -53,7 +53,6 @@ # Set vehicle mode and armed attributes (the only settable attributes) print "\nSet Vehicle.mode=GUIDED (currently: %s)" % vehicle.mode.name vehicle.mode = VehicleMode("GUIDED") -vehicle.flush() # Flush to guarantee that previous writes to the vehicle have taken place while not vehicle.mode.name=='GUIDED': #Wait until mode has changed print " Waiting for mode change ..." time.sleep(1) @@ -67,7 +66,6 @@ print "\nSet Vehicle.armed=True (currently: %s)" % vehicle.armed vehicle.armed = True -vehicle.flush() while not vehicle.armed: print " Waiting for arming..." time.sleep(1) @@ -82,13 +80,12 @@ def mode_callback(attribute): print " Set mode=STABILIZE (currently: %s)" % vehicle.mode.name vehicle.mode = VehicleMode("STABILIZE") -vehicle.flush() print " Wait 2s so callback invoked before observer removed" time.sleep(2) # Remove observer - specifying the attribute and previously registered callback function -vehicle.remove_attribute_observer('mode', mode_callback) +vehicle.remove_attribute_observer('mode', mode_callback) # Get Vehicle Home location ((0 index in Vehicle.commands) @@ -103,7 +100,6 @@ def mode_callback(attribute): print "\nRead vehicle param 'THR_MIN': %s" % vehicle.parameters['THR_MIN'] print "Write vehicle param 'THR_MIN' : 10" vehicle.parameters['THR_MIN']=10 -vehicle.flush() print "Read new value of param 'THR_MIN': %s" % vehicle.parameters['THR_MIN'] @@ -112,11 +108,10 @@ def mode_callback(attribute): vehicle.mode = VehicleMode("STABILIZE") vehicle.armed = False vehicle.parameters['THR_MIN']=130 -vehicle.flush() #Close vehicle object before exiting script print "\nClose vehicle object" vehicle.close() -print("Completed") \ No newline at end of file +print("Completed") diff --git a/tests/sitl/test_110.py b/tests/sitl/test_110.py index da8203b22..c7afed19e 100644 --- a/tests/sitl/test_110.py +++ b/tests/sitl/test_110.py @@ -40,7 +40,6 @@ def armed_callback(attribute): # Disarm and see update. v.armed = False - v.flush() # Wait for ACK. time.sleep(3) @@ -58,7 +57,6 @@ def armed_callback(attribute): # Re-arm and see update. v.armed = True - v.flush() # Wait for ack time.sleep(3) diff --git a/tests/sitl/test_115.py b/tests/sitl/test_115.py index 93d4c0d86..834357f45 100644 --- a/tests/sitl/test_115.py +++ b/tests/sitl/test_115.py @@ -33,7 +33,6 @@ def mavlink_callback(*args): # Disarm. A callback of None should not throw errors v.armed = False - v.flush() # NOTE wait crudely for ACK on mode update time.sleep(3) @@ -42,6 +41,5 @@ def mavlink_callback(*args): # Re-arm should not throw errors. v.armed = True - v.flush() # NOTE wait crudely for ACK on mode update time.sleep(3) diff --git a/tests/sitl/test_goto.py b/tests/sitl/test_goto.py index 3327ab7f8..ee7f9a649 100644 --- a/tests/sitl/test_goto.py +++ b/tests/sitl/test_goto.py @@ -43,7 +43,6 @@ def arm_and_takeoff(aTargetAltitude): # print "Arming motors" # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") - vehicle.flush() i = 60 while vehicle.mode.name != 'GUIDED' and i > 0: @@ -52,7 +51,6 @@ def arm_and_takeoff(aTargetAltitude): i = i - 1 vehicle.armed = True - vehicle.flush() i = 60 while not vehicle.armed and vehicle.mode.name == 'GUIDED' and i > 0: @@ -66,7 +64,6 @@ def arm_and_takeoff(aTargetAltitude): # 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 @@ -86,7 +83,6 @@ def arm_and_takeoff(aTargetAltitude): # print "Going to first point..." point1 = LocationGlobal(-35.361354, 149.165218, 20, is_relative=True) vehicle.commands.goto(point1) - vehicle.flush() # sleep so we can see the change in map time.sleep(3) @@ -94,11 +90,9 @@ def arm_and_takeoff(aTargetAltitude): # print "Going to second point..." point2 = LocationGlobal(-35.363244, 149.168801, 20, is_relative=True) vehicle.commands.goto(point2) - vehicle.flush() # sleep so we can see the change in map time.sleep(3) # print "Returning to Launch" vehicle.mode = VehicleMode("RTL") - vehicle.flush()