From a2436b450a5b85914327825549043b13c2197bfc Mon Sep 17 00:00:00 2001 From: Liam Staskawicz Date: Wed, 3 Jun 2015 17:54:10 -0700 Subject: [PATCH 1/7] MPVehicle: add system_status property, which exposes the system_status field from the most recently received heartbeat msg handy for checking whether they vehicle is on the ground, flying, in failsafe, etc --- droneapi/module/api.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/droneapi/module/api.py b/droneapi/module/api.py index 0992a1e7a..26d5d8aad 100644 --- a/droneapi/module/api.py +++ b/droneapi/module/api.py @@ -209,6 +209,10 @@ def armed(self, value): else: self.__master.arducopter_disarm() + @property + def system_status(self): + return self.__module.system_status + @property def groundspeed(self): return self.__module.groundspeed @@ -355,6 +359,7 @@ def __init__(self, mpstate): " (USERNAME) (PASSWORD) (VEHICLEID)", "" ]) self.api = MPAPIConnection(self) self.vehicle = self.api.get_vehicles()[0] + self.system_status = None self.lat = None self.lon = None self.alt = None @@ -461,6 +466,7 @@ def mavlink_packet(self, m): self.level = m.battery_remaining self.__on_change('battery') elif typ == "HEARTBEAT": + self.system_status = m.system_status self.__on_change('mode', 'armed') elif typ in ["WAYPOINT_CURRENT", "MISSION_CURRENT"]: self.last_waypoint = m.seq From eafda08a76890cd7dbc9821f30e3ead85b2ba0c0 Mon Sep 17 00:00:00 2001 From: hamishwillee Date: Thu, 11 Jun 2015 11:52:47 +1000 Subject: [PATCH 2/7] Add documentation for new system_status attribute --- docs/examples/vehicle_state.rst | 4 +- docs/guide/vehicle_state_and_parameters.rst | 19 +++++--- droneapi/lib/__init__.py | 52 +++++++++++++++++++++ examples/vehicle_state/vehicle_state.py | 29 +++++++++++- 4 files changed, 95 insertions(+), 9 deletions(-) diff --git a/docs/examples/vehicle_state.rst b/docs/examples/vehicle_state.rst index 8c693c4fa..d432df327 100644 --- a/docs/examples/vehicle_state.rst +++ b/docs/examples/vehicle_state.rst @@ -41,9 +41,11 @@ On the *MAVProxy* console you should see (something like): Groundspeed: 0.0 Airspeed: 0.0 Mount status: [None, None, None] - Battery: Battery voltage: 12590, current: 0, level: 99 + Battery: Battery:voltage=12.587,current=0.0,level=98 + System status: 3 Mode: STABILIZE Armed: False + Current Status: MAV_STATE_STANDBY: System is grounded and on standby. It can be launched any time. Set Vehicle.mode=GUIDED (currently: STABILIZE) Waiting for mode change ... Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} diff --git a/docs/guide/vehicle_state_and_parameters.rst b/docs/guide/vehicle_state_and_parameters.rst index f4a4ace79..a77636b5b 100644 --- a/docs/guide/vehicle_state_and_parameters.rst +++ b/docs/guide/vehicle_state_and_parameters.rst @@ -31,7 +31,9 @@ Vehicle state information is exposed through vehicle *attributes*. DroneKit-Pyth :py:attr:`Vehicle.gps_0 `, :py:attr:`Vehicle.armed `, :py:attr:`Vehicle.location `, -:py:attr:`Vehicle.mount_status `. +:py:attr:`Vehicle.mount_status `, +:py:attr:`Vehicle.battery `, +:py:attr:`Vehicle.system_status `. All of the attributes can be :ref:`read ` and :ref:`observed `, but only the :py:attr:`Vehicle.mode ` and :py:attr:`Vehicle.armed ` @@ -53,16 +55,21 @@ The code fragment below shows how to read and print all the attributes. The valu print "Attitude: %s" % v.attitude print "Velocity: %s" % v.velocity print "GPS: %s" % v.gps_0 - print "groundspeed: %s" % v.groundspeed - print "airspeed: %s" % v.airspeed - print "mount_status: %s" % v.mount_status + print "Groundspeed: %s" % v.groundspeed + print "Airspeed: %s" % v.airspeed + print "Mount status: %s" % v.mount_status + print "Battery: %s" % v.battery + print "System status: %s" % v.system_status print "Mode: %s" % v.mode.name # settable print "Armed: %s" % v.armed # settable -If one of these attributes cannot be retrieved or is invalid then the returned object will contain + +If these attributes cannot be retrieved or are invalid then the returned object will usually contain ``None`` values for its members (for example, if there was no GPS lock then :py:attr:`Vehicle.gps_0 ` would return a :py:class:`GPSInfo ` -with ``None`` values for ``eph``, ``satellites_visible`` etc.) +with ``None`` values for ``eph``, ``satellites_visible`` etc.) One exception is the +:py:attr:`Vehicle.system_status `, which will return the +last value retrieved if the heartbeat fails. .. todo:: we need to be able to verify mount_status works/setup. diff --git a/droneapi/lib/__init__.py b/droneapi/lib/__init__.py index 26bd20853..61579643a 100644 --- a/droneapi/lib/__init__.py +++ b/droneapi/lib/__init__.py @@ -476,6 +476,58 @@ class Vehicle(HasObservers): The values in the list are set to ``None`` if no mount is configured. + .. py:attribute:: system_status + + Gets the ``system_status`` value from the most recently received `heartbeat `_ message. + + This attribute provides high-level information about whether the vehicle is on the ground, flying, in failsafe, etc. For example, + you can check if the vehicle is in a critical state as shown: + + .. code:: python + + from pymavlink import mavutil + ... + + if v.system_status == mavutil.mavlink.MAV_STATE_CRITICAL: + print "DON'T PANIC!" + + The possible values of the status are defined in the `MAV_STATE `_ enum (reproduced below). + + .. list-table:: MAV_STATE enum. + :widths: 5 25 75 + :header-rows: 1 + + * - Value + - Field name + - Description + * - 0 + - ``MAV_STATE_UNINIT`` + - Uninitialized system - state is unknown. + * - 1 + - ``MAV_STATE_BOOT`` + - System is booting up. + * - 2 + - ``MAV_STATE_CALIBRATING`` + - System is calibrating and not flight-ready. + * - 3 + - ``MAV_STATE_STANDBY`` + - System is grounded and on standby. It can be launched any time. + * - 4 + - ``MAV_STATE_ACTIVE`` + - System is active and might be already airborne. Motors are engaged. + * - 5 + - ``MAV_STATE_CRITICAL`` + - System is in a non-normal flight mode. It can however still navigate. + * - 6 + - ``MAV_STATE_EMERGENCY`` + - System is in a non-normal flight mode. It has lost control over all + or parts of the airframe. It is in mayday and going down. + * - 7 + - ``MAV_STATE_POWEROFF`` + - System just initialized its power-down sequence and will shut down now. + + + .. py:attribute:: battery Current system :py:class:`Battery` status. diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index e48487ee0..8238e2216 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -26,10 +26,36 @@ print " Airspeed: %s" % v.airspeed print " Mount status: %s" % v.mount_status print " Battery: %s" % v.battery +print " System status: %s" % v.system_status print " Mode: %s" % v.mode.name # settable print " Armed: %s" % v.armed # settable +def system_status_string(status): + """ + Convenience function to get a string for the system_status. + """ + status_string="Unknown status" + if v.system_status == mavutil.mavlink.MAV_STATE_UNINIT: + status_string = "MAV_STATE_UNINIT: Uninitialized system - state is unknown." + if v.system_status == mavutil.mavlink.MAV_STATE_BOOT: + status_string = "MAV_STATE_BOOT: System is booting up." + if v.system_status == mavutil.mavlink.MAV_STATE_CALIBRATING: + status_string = "MAV_STATE_CALIBRATING: System is calibrating and not flight-ready." + if v.system_status == mavutil.mavlink.MAV_STATE_STANDBY: + status_string = "MAV_STATE_STANDBY: System is grounded and on standby. Ready to launch." + if v.system_status == mavutil.mavlink.MAV_STATE_ACTIVE: + status_string = "MAV_STATE_ACTIVE: System is active and may be airborne. Motors are engaged." + if v.system_status == mavutil.mavlink.MAV_STATE_CRITICAL: + status_string = "MAV_STATE_CRITICAL: System is in a non-normal flight mode but can still navigate." + if v.system_status == mavutil.mavlink.MAV_STATE_EMERGENCY: + status_string = "MAV_STATE_EMERGENCY: System is in a non-normal flight mode. We're going down." + if v.system_status == mavutil.mavlink.MAV_STATE_POWEROFF: + status_string = "MAV_STATE_POWEROFF: System has started its power-down sequence." + return status_string + +print "Current Status:", system_status_string(v.system_status) + # Set vehicle mode and armed attributes (the only settable attributes) print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name v.mode = VehicleMode("GUIDED") @@ -45,7 +71,6 @@ print " Waiting for arming..." time.sleep(1) - # Show how to add and remove and attribute observer callbacks (using mode as example) def mode_callback(attribute): print " CALLBACK: Mode changed to: ", v.mode.name @@ -96,7 +121,7 @@ def mode_callback(attribute): ## Reset variables to sensible values. -print "\nReset vehicle atributes/parameters and exit" +print "\nReset vehicle attributes/parameters and exit" v.mode = VehicleMode("STABILIZE") v.armed = False v.parameters['THR_MIN']=130 From a2908cb384dfb8ac42fb2e159eccfdd95b7783ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ram=C3=B3n=20Roche?= Date: Thu, 11 Jun 2015 12:17:00 -0700 Subject: [PATCH 3/7] strip whitespace --- examples/vehicle_state/vehicle_state.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index 8238e2216..bbe942e05 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -1,7 +1,7 @@ # -# This example shows how to use DroneKit-Python to get and set vehicle state, parameter and channel-override information. -# It also demonstrates how to observe vehicle attribute (state) changes. -# +# This example shows how to use DroneKit-Python to get and set vehicle state, parameter and channel-override information. +# It also demonstrates how to observe vehicle attribute (state) changes. +# # Usage: # * mavproxy.py # * module load api @@ -57,28 +57,28 @@ def system_status_string(status): print "Current Status:", system_status_string(v.system_status) # Set vehicle mode and armed attributes (the only settable attributes) -print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name +print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name v.mode = VehicleMode("GUIDED") v.flush() # Flush to guarantee that previous writes to the vehicle have taken place while not v.mode.name=='GUIDED' and not api.exit: #Wait until mode has changed print " Waiting for mode change ..." time.sleep(1) -print "Set Vehicle.armed=True (currently: %s)" % v.armed +print "Set Vehicle.armed=True (currently: %s)" % v.armed v.armed = True v.flush() while not v.armed and not api.exit: print " Waiting for arming..." time.sleep(1) -# Show how to add and remove and attribute observer callbacks (using mode as example) +# Show how to add and remove and attribute observer callbacks (using mode as example) def mode_callback(attribute): print " CALLBACK: Mode changed to: ", v.mode.name -print "\nAdd mode attribute observer for Vehicle.mode" -v.add_attribute_observer('mode', mode_callback) +print "\nAdd mode attribute observer for Vehicle.mode" +v.add_attribute_observer('mode', mode_callback) -print " Set mode=STABILIZE (currently: %s)" % v.mode.name +print " Set mode=STABILIZE (currently: %s)" % v.mode.name v.mode = VehicleMode("STABILIZE") v.flush() @@ -86,11 +86,11 @@ def mode_callback(attribute): time.sleep(2) # Remove observer - specifying the attribute and previously registered callback function -v.remove_attribute_observer('mode', mode_callback) +v.remove_attribute_observer('mode', mode_callback) # Get Vehicle Home location ((0 index in Vehicle.commands) -print "\nGet home location" +print "\nGet home location" cmds = v.commands cmds.download() cmds.wait_valid() @@ -106,7 +106,7 @@ def mode_callback(attribute): # Overriding an RC channel -# NOTE: CHANNEL OVERRIDES may be useful for simulating user input and when implementing certain types of joystick control. +# NOTE: CHANNEL OVERRIDES may be useful for simulating user input and when implementing certain types of joystick control. #DO NOT use unless there is no other choice (there almost always is!) print "\nOverriding RC channels for roll and yaw" v.channel_override = { "1" : 900, "4" : 1000 } From 51fa75e93e160ec506a584d35dffd8ba38b4171c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ram=C3=B3n=20Roche?= Date: Thu, 11 Jun 2015 13:15:14 -0700 Subject: [PATCH 4/7] more whitespace --- examples/vehicle_state/vehicle_state.py | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index bbe942e05..5a032caeb 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -31,30 +31,7 @@ print " Armed: %s" % v.armed # settable -def system_status_string(status): - """ - Convenience function to get a string for the system_status. - """ - status_string="Unknown status" - if v.system_status == mavutil.mavlink.MAV_STATE_UNINIT: - status_string = "MAV_STATE_UNINIT: Uninitialized system - state is unknown." - if v.system_status == mavutil.mavlink.MAV_STATE_BOOT: - status_string = "MAV_STATE_BOOT: System is booting up." - if v.system_status == mavutil.mavlink.MAV_STATE_CALIBRATING: - status_string = "MAV_STATE_CALIBRATING: System is calibrating and not flight-ready." - if v.system_status == mavutil.mavlink.MAV_STATE_STANDBY: - status_string = "MAV_STATE_STANDBY: System is grounded and on standby. Ready to launch." - if v.system_status == mavutil.mavlink.MAV_STATE_ACTIVE: - status_string = "MAV_STATE_ACTIVE: System is active and may be airborne. Motors are engaged." - if v.system_status == mavutil.mavlink.MAV_STATE_CRITICAL: - status_string = "MAV_STATE_CRITICAL: System is in a non-normal flight mode but can still navigate." - if v.system_status == mavutil.mavlink.MAV_STATE_EMERGENCY: - status_string = "MAV_STATE_EMERGENCY: System is in a non-normal flight mode. We're going down." - if v.system_status == mavutil.mavlink.MAV_STATE_POWEROFF: - status_string = "MAV_STATE_POWEROFF: System has started its power-down sequence." - return status_string - -print "Current Status:", system_status_string(v.system_status) +print "Current Status: ", v.system_status # Set vehicle mode and armed attributes (the only settable attributes) print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name From 190586819c10f1a4b4cd8d0a5c17b710954cb364 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ram=C3=B3n=20Roche?= Date: Thu, 11 Jun 2015 13:32:54 -0700 Subject: [PATCH 5/7] SystemStatus class yields string compares to int updated vehicle_state.py example to reflect this change --- droneapi/lib/__init__.py | 33 +++++++++++++++++++++++++ droneapi/module/api.py | 4 +-- examples/vehicle_state/vehicle_state.py | 5 +++- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/droneapi/lib/__init__.py b/droneapi/lib/__init__.py index 61579643a..d7cce8840 100644 --- a/droneapi/lib/__init__.py +++ b/droneapi/lib/__init__.py @@ -1018,3 +1018,36 @@ def next(self, value): .. INTERNAL NOTE: (implementation provided by subclass) """ pass + +class SystemStatus(object): + """ + A simple way to work with MAV_STATE messages + + Supported properties: + + ============= ====================================== + Name Description + ============= ====================================== + mav_state int + ============= ====================================== + + """ + STATES = { + mavutil.mavlink.MAV_STATE_UNINIT: '[MAV_STATE_UNINIT]: Uninitialized system, state is unknown.', + mavutil.mavlink.MAV_STATE_BOOT: '[MAV_STATE_BOOT]: System is booting up.', + mavutil.mavlink.MAV_STATE_CALIBRATING: '[MAV_STATE_CALIBRATING]: System is calibrating and not flight-ready.', + mavutil.mavlink.MAV_STATE_STANDBY: '[MAV_STATE_STANDBY]: System is grounded and on standby. It can be launched any time.', + mavutil.mavlink.MAV_STATE_ACTIVE: '[MAV_STATE_ACTIVE]: System is active and might be already airborne. Motors are engaged.', + mavutil.mavlink.MAV_STATE_CRITICAL: '[MAV_STATE_CRITICAL]: System is in a non-normal flight mode. It can however still navigate.', + mavutil.mavlink.MAV_STATE_EMERGENCY: '[MAV_STATE_EMERGENCY]: System is in a non-normal flight mode. It lost control over parts or over the whole airframe. It is in mayday and going down.', + mavutil.mavlink.MAV_STATE_POWEROFF: '[MAV_STATE_POWEROFF]: System just initialized its power-down sequence, will shut down now.', + } + + def __init__(self, mav_state): + self.status = mav_state + + def __eq__(self, other): + return self.status == other + + def __str__(self): + return self.STATES[self.status] diff --git a/droneapi/module/api.py b/droneapi/module/api.py index 26d5d8aad..9bec7e24a 100644 --- a/droneapi/module/api.py +++ b/droneapi/module/api.py @@ -9,7 +9,7 @@ from droneapi.lib.WebClient import * from droneapi.lib import APIConnection, Vehicle, VehicleMode, Location, \ Attitude, GPSInfo, Parameters, CommandSequence, APIException, Battery, \ - Rangefinder + Rangefinder, SystemStatus # Enable logging here (until this code can be moved into mavproxy) logging.basicConfig(level=logging.DEBUG) @@ -466,7 +466,7 @@ def mavlink_packet(self, m): self.level = m.battery_remaining self.__on_change('battery') elif typ == "HEARTBEAT": - self.system_status = m.system_status + self.system_status = SystemStatus(m.system_status) self.__on_change('mode', 'armed') elif typ in ["WAYPOINT_CURRENT", "MISSION_CURRENT"]: self.last_waypoint = m.seq diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index 5a032caeb..94619059a 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -31,7 +31,10 @@ print " Armed: %s" % v.armed # settable -print "Current Status: ", v.system_status +# when trying to compare v.system_status with enum from mavlink +# it will always yeild the enum instead of string value +if v.system_status == mavutil.mavlink.MAV_STATE_STANDBY: + print 'Standing by waiting instructions' # Set vehicle mode and armed attributes (the only settable attributes) print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name From a881d1bd8ef066bc1d2e4c7a908cbaed54a422a6 Mon Sep 17 00:00:00 2001 From: hamishwillee Date: Fri, 12 Jun 2015 11:09:03 +1000 Subject: [PATCH 6/7] Documentation fixes for changed system_state implementation --- docs/examples/vehicle_state.rst | 127 ++++ docs/guide/vehicle_state_and_parameters.rst | 688 ++++++++++---------- droneapi/lib/__init__.py | 47 +- examples/vehicle_state/vehicle_state.py | 218 +++---- 4 files changed, 598 insertions(+), 482 deletions(-) diff --git a/docs/examples/vehicle_state.rst b/docs/examples/vehicle_state.rst index d432df327..87fe4f42b 100644 --- a/docs/examples/vehicle_state.rst +++ b/docs/examples/vehicle_state.rst @@ -125,3 +125,130 @@ The full source code at documentation build-time is listed below (`current versi .. literalinclude:: ../../examples/vehicle_state/vehicle_state.py :language: python +======= +.. _example-vehicle-state: + +====================== +Example: Vehicle State +====================== + +This example shows how to get/set vehicle attribute, parameter and channel-override 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. + + +Running the example +=================== + +The vehicle and DroneKit should be set up as described in the :ref:`quick-start` or :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 vehicle_state.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/vehicle_state/vehicle_state.py``. + + +On the *MAVProxy* console you should see (something like): + +.. code:: bash + + MAV> api start vehicle_state.py + STABILIZE> + + Get all vehicle attribute values: + Location: Attitude: Attitude:pitch=-0.00405988190323,yaw=-0.0973932668567,roll=-0.00393210304901 + Velocity: [0.06, -0.07, 0.0] + GPS: GPSInfo:fix=3,num_sat=10 + Groundspeed: 0.0 + Airspeed: 0.0 + Mount status: [None, None, None] + Battery: Battery:voltage=12.587,current=0.0,level=98 + System status: [MAV_STATE_STANDBY]: System is grounded and on standby. It can be launched any time. + Mode: STABILIZE + Armed: False + Standing by - waiting for instructions + Set Vehicle.mode=GUIDED (currently: STABILIZE) + Waiting for mode change ... + Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} + GUIDED> Mode GUIDED + Set Vehicle.armed=True (currently: False) + Waiting for arming... + APM: ARMING MOTORS + APM: Initialising APM... + Got MAVLink msg: COMMAND_ACK {command : 400, result : 0} + ARMED + + Add mode attribute observer for Vehicle.mode + Set mode=STABILIZE (currently: GUIDED) + Wait 2s so callback invoked before observer removed + Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} + STABILIZE> Mode STABILIZE + CALLBACK: Mode changed to: STABILIZE + + Get home location + Requesting 0 waypoints t=Fri May 15 11:35:58 2015 now=Fri May 15 11:35:58 2015 + Home WP: MISSION_ITEM {target_system : 255, 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 : 583.729980469} + + Read vehicle param 'THR_MIN': 130.0 + Write vehicle param 'THR_MIN' : 10 + timeout setting THR_MIN to 10.000000 + Read new value of param 'THR_MIN': 10.0 + + Overriding RC channels for roll and yaw + Current overrides are: {'1': 900, '4': 1000} + Channel default values: {'1': 1500, '3': 1000, '2': 1500, '5': 1800, '4': 1500, '7': 1000, '6': 1000, '8': 1800} + Cancelling override + + Reset vehicle atributes/parameters and exit + Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} + APM: DISARMING MOTORS + Got MAVLink msg: COMMAND_ACK {command : 400, result : 0} + DISARMED + timeout setting THR_MIN to 130.000000 + APIThread-0 exiting... + + + +How does it work? +================= + +The guide topic :ref:`vehicle-information` provides an explanation of how this code works. + +.. INTERNAL COMMENT: + + Normally we'd highlight code here but all of it is worth of highlight, and we do that in the + linked guide + + +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 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. + See `#60 Attribute observer callbacks are called with heartbeat until disabled - after first called `_ + for more information. + + + +Source code +=========== + +The full source code at documentation build-time is listed below (`current version on github `_): + +.. literalinclude:: ../../examples/vehicle_state/vehicle_state.py + :language: python diff --git a/docs/guide/vehicle_state_and_parameters.rst b/docs/guide/vehicle_state_and_parameters.rst index a77636b5b..13efd4551 100644 --- a/docs/guide/vehicle_state_and_parameters.rst +++ b/docs/guide/vehicle_state_and_parameters.rst @@ -1,343 +1,347 @@ -.. _vehicle-information: - -=========================== -Vehicle State and Settings -=========================== - -The :py:class:`Vehicle ` class exposes *most* state information (position, speed, etc.) through python -:ref:`attributes `, while vehicle :ref:`parameters ` (settings) -are accessed though named elements of :py:attr:`Vehicle.parameters `. - -This topic explains how to get, set and observe vehicle state and parameter information (including getting the -:ref:`Home location `). It also describes a few APIs that -:ref:`should be used with caution `. - -.. tip:: You can test most of the code in this topic by running the :ref:`Vehicle State ` example. - - -.. _vehicle_state_attributes: - -Attributes -========== - -Vehicle state information is exposed through vehicle *attributes*. DroneKit-Python currently supports the following -"standard" attributes: -:py:attr:`Vehicle.location `, -:py:attr:`Vehicle.attitude `, -:py:attr:`Vehicle.velocity `, -:py:attr:`Vehicle.mode `, -:py:attr:`Vehicle.airspeed `, -:py:attr:`Vehicle.groundspeed `, -:py:attr:`Vehicle.gps_0 `, -:py:attr:`Vehicle.armed `, -:py:attr:`Vehicle.location `, -:py:attr:`Vehicle.mount_status `, -:py:attr:`Vehicle.battery `, -:py:attr:`Vehicle.system_status `. - -All of the attributes can be :ref:`read ` and :ref:`observed `, -but only the :py:attr:`Vehicle.mode ` and :py:attr:`Vehicle.armed ` -status can be :ref:`written `. - - -.. _vehicle_state_read_attributes: - -Getting attributes ------------------- - -The code fragment below shows how to read and print all the attributes. The values are retrieved from the remote device -(not cached). - -.. code:: python - - # v is an instance of the Vehicle class - print "Location: %s" % v.location - print "Attitude: %s" % v.attitude - print "Velocity: %s" % v.velocity - print "GPS: %s" % v.gps_0 - print "Groundspeed: %s" % v.groundspeed - print "Airspeed: %s" % v.airspeed - print "Mount status: %s" % v.mount_status - print "Battery: %s" % v.battery - print "System status: %s" % v.system_status - print "Mode: %s" % v.mode.name # settable - print "Armed: %s" % v.armed # settable - - -If these attributes cannot be retrieved or are invalid then the returned object will usually contain -``None`` values for its members (for example, if there was no GPS lock then -:py:attr:`Vehicle.gps_0 ` would return a :py:class:`GPSInfo ` -with ``None`` values for ``eph``, ``satellites_visible`` etc.) One exception is the -:py:attr:`Vehicle.system_status `, which will return the -last value retrieved if the heartbeat fails. - -.. todo:: we need to be able to verify mount_status works/setup. - - - -.. _vehicle_state_set_attributes: - -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. - -.. code:: python - - #disarm the vehicle - v.armed = False - v.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**. - 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 `_. - - -Code should not assume that an attempt to set an attribute will succeed. The example code snippet below polls the attribute values -to confirm they have changed before proceeding. - -.. code:: python - - v.mode = VehicleMode("GUIDED") - v.armed = True - v.flush() # Flush to ensure changes are sent to autopilot - while not v.mode.name=='GUIDED' and not v.armed and not api.exit: - print " Getting ready to take off ..." - time.sleep(1) - - - -.. _vehicle_state_observe_attributes: - -Observing attribute changes ---------------------------- - -You can observe any of the attributes and will receive notification if their values change. This allows you to -monitor changes to velocity and other vehicle state without the need for polling. - -.. warning:: - - There is currently `a defect (#60) `_ that means that after an - observer is triggered, the callback function is run on every heartbeat (whether or not the observed attribute changes). - -Observers are added using :py:func:`Vehicle.add_attribute_observer() `, -specifying the name of the attribute to observe and a callback function. The same string is passed to the callback -when it is notified. Observers are removed using :py:func:`remove_attribute_observer() `. - -The code snippet below shows how to add (and remove) a callback function to observe :py:attr:`location ` attribute changes. The two second ``sleep()`` is required because otherwise the observer might be removed before the the callback is first run. - -.. code:: python - - # Callback function. The parameter is the name of the observed attribute (a string) - def location_callback(attribute): - print " CALLBACK: Location changed to: ", v.location - - # Add a callback. The first parameter the name of the observed attribute (a string). - v.add_attribute_observer('location', location_callback) - - # Wait 2s so callback can be notified before the observer is removed - time.sleep(2) - - # Remove observer - specifying the attribute and previously registered callback function - v.remove_attribute_observer('location', location_callback) - - - - - -.. _vehicle_state_parameters: - -Parameters -========== - -Vehicle parameters provide the information used to configure the autopilot for the vehicle-specific hardware/capabilities. -These can be read and set using the :py:attr:`Vehicle.parameters ` -attribute (a :py:class:`Parameters ` object). - -.. tip:: - - `Copter Parameters `_, - `Plane Parameters `_, - and `Rover Parameters `_ list all the supported parameters for each platform. - The lists are automatically generated from the latest ArduPilot source code, and may contain parameters - that are not yet in the stable released versions of the code. - - - -Getting parameters ------------------- - -The parameters are read using the parameter name as a key. Reads will generally succeed unless you attempt to read an unsupported parameter -(which results in a Key error exception). - -The code example below shows how to set Minimum Throttle (THR_MIN) setting. On Copter and Rover (not Plane), this is the minimum PWM setting for the -throttle at which the motors will keep spinning. - -.. code:: python - - # Print the value of the THR_MIN parameter. - print "Param: %s" % vehicle.parameters['THR_MIN'] - - - - -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. - -.. code:: python - - # Change the parameter value (Copter, Rover) - vehicle.parameters['THR_MIN']=100 - vehicle.flush() - - - -Observing parameter changes ---------------------------- - -At time of writing :py:class:`Parameters ` does `not support `_ observing parameter changes. - -.. todo:: - - Check to see if observers have been implemented and if so, update the information here, in about, and in Vehicle class: - https://github.com/diydrones/dronekit-python/issues/107 - - - - -.. _vehicle_state_home_location: - -Home location -============= - -The *Home location* is set when a vehicle is armed and first gets a good location fix from the GPS. The location is used -as the target when the vehicle does a "return to launch". In Copter missions (and most Plane) missions, the altitude of -waypoints is set relative to this position. - -Unlike other vehicle state information, the home location is accessed as the 0 index value of -:py:attr:`Vehicle.commands `: - -.. code:: python - - cmds = v.commands - cmds.download() - cmds.wait_valid() - print " Home WP: %s" % cmds[0] - -The returned value is a :py:class:`Command ` object. - - - -.. _vehicle_state_disrecommended: - -Discommended APIs -================= - -This section describes methods that we recommend you do not use! In general they are provided to handle the (hopefully rare) -cases where the "proper" API is missing some needed functionality. - -If you have to use these methods please `provide feedback explaining why `_. - - -.. _vehicle_state_set_mavlink_callback: - -MAVLink Message Observer ------------------------- - -The :py:func:`Vehicle.set_mavlink_callback() ` method provides asynchronous -notification when any *MAVLink* packet is received from this vehicle. - -.. tip:: - - Use :ref:`attribute observers ` instead of this method where possible. - - -The code snippet below shows how to set a “demo” callback function as the callback handler: - -.. code:: python - - # Demo callback handler for raw MAVLink messages - def mavrx_debug_handler(message): - print "Received", message - - # Set MAVLink callback handler (after getting Vehicle instance) - v.set_mavlink_callback(mavrx_debug_handler) - - -.. warning:: - - At time of writing there is no way to `disable this callback `_. - - -.. _vehicle_state_channel_override: - -Channel Overrides ------------------ - -.. warning:: - - Channel Overrides may be useful for simulating user input and when implementing certain types of joystick control. - They should not be used for direct control of the vehicle unless there is no other choice! - - Instead use the appropriate MAVLink commands like DO_SET_SERVO/DO_SET_RELAY, or more generally set the desired position or direction/speed. - -The :py:attr:`channel_override ` attribute takes a dictionary argument defining the RC *output* channels to be overridden (specified by channel number), and their new values. Channels that are not specified in the dictionary are not overridden. All multi-channel updates are atomic. To cancel an override call ``channel_override`` again, setting zero for the overridden channels. - -The values of the first four channels map to the main flight controls: 1=Roll, 2=Pitch, 3=Throttle, 4=Yaw (the mapping is defined in ``RCMAP_`` parameters in -`Plane `_, -`Copter `_ , -`Rover `_). - -The remaining channel values are configurable, and their purpose can be determined using the -`RCn_FUNCTION parameters `_. -In general a value of 0 set for a specific ``RCn_FUNCTION`` indicates that the channel can be -`mission controlled `_ (i.e. it will not directly be -controlled by normal autopilot code). - -An example of setting and clearing overrides is given below: - -.. code:: python - - # Override the channel for roll and yaw - v.channel_override = { "1" : 900, "4" : 1000 } - v.flush() - - #print current override values - print "Current overrides are:", v.channel_override - - # Print channel values (values if overrides removed) - print "Channel default values:", v.channel_readback - - # Cancel override by setting channels to 0 - v.channel_override = { "1" : 0, "4" : 0 } - v.flush() - - - - -.. _api-information-known-issues: - -Known issues -============ - -Below are a number of bugs and known issues related to vehicle state and settings: - -* `#12 Timeout error when setting a parameter `_ -* `#60 Attribute observer callbacks are called with heartbeat until disabled - after first called `_ -* `#107 Add implementation for observer methods in Parameter class `_ -* `#114 DroneKit has no method for detecting command failure `_ -* `#115 No way to disable the callback set_mavlink_callback `_ - - +.. _vehicle-information: + +=========================== +Vehicle State and Settings +=========================== + +The :py:class:`Vehicle ` class exposes *most* state information (position, speed, etc.) through python +:ref:`attributes `, while vehicle :ref:`parameters ` (settings) +are accessed though named elements of :py:attr:`Vehicle.parameters `. + +This topic explains how to get, set and observe vehicle state and parameter information (including getting the +:ref:`Home location `). It also describes a few APIs that +:ref:`should be used with caution `. + +.. tip:: You can test most of the code in this topic by running the :ref:`Vehicle State ` example. + + +.. _vehicle_state_attributes: + +Attributes +========== + +Vehicle state information is exposed through vehicle *attributes*. DroneKit-Python currently supports the following +"standard" attributes: +:py:attr:`Vehicle.location `, +:py:attr:`Vehicle.attitude `, +:py:attr:`Vehicle.velocity `, +:py:attr:`Vehicle.mode `, +:py:attr:`Vehicle.airspeed `, +:py:attr:`Vehicle.groundspeed `, +:py:attr:`Vehicle.gps_0 `, +:py:attr:`Vehicle.armed `, +:py:attr:`Vehicle.location `, +:py:attr:`Vehicle.mount_status `, +:py:attr:`Vehicle.battery `, +:py:attr:`Vehicle.system_status `. + +All of the attributes can be :ref:`read ` and :ref:`observed `, +but only the :py:attr:`Vehicle.mode ` and :py:attr:`Vehicle.armed ` +status can be :ref:`written `. + + +.. _vehicle_state_read_attributes: + +Getting attributes +------------------ + +The code fragment below shows how to read and print all the attributes. The values are retrieved from the remote device +(not cached). + +.. code:: python + + # v is an instance of the Vehicle class + print "Location: %s" % v.location + print "Attitude: %s" % v.attitude + print "Velocity: %s" % v.velocity + print "GPS: %s" % v.gps_0 + print "Groundspeed: %s" % v.groundspeed + print "Airspeed: %s" % v.airspeed + print "Mount status: %s" % v.mount_status + print "Battery: %s" % v.battery + print "System status: %s" % v.system_status + print "Mode: %s" % v.mode.name # settable + print "Armed: %s" % v.armed # settable + + +If these attributes cannot be retrieved or are invalid then the returned object will usually contain +``None`` values for its members (for example, if there was no GPS lock then +:py:attr:`Vehicle.gps_0 ` would return a :py:class:`GPSInfo ` +with ``None`` values for ``eph``, ``satellites_visible`` etc.) + +The :py:attr:`Vehicle.system_status ` has slightly different behaviour from the other attributes: + +* It will return the last value retrieved if the heartbeat fails (rather than ``None``). +* The attribute returns a ``MAV_STATE`` enum value for comparisons, and a human-readable string for the state when printed. + + +.. todo:: we need to be able to verify mount_status works/setup. + + + +.. _vehicle_state_set_attributes: + +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. + +.. code:: python + + #disarm the vehicle + v.armed = False + v.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**. + 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 `_. + + +Code should not assume that an attempt to set an attribute will succeed. The example code snippet below polls the attribute values +to confirm they have changed before proceeding. + +.. code:: python + + v.mode = VehicleMode("GUIDED") + v.armed = True + v.flush() # Flush to ensure changes are sent to autopilot + while not v.mode.name=='GUIDED' and not v.armed and not api.exit: + print " Getting ready to take off ..." + time.sleep(1) + + + +.. _vehicle_state_observe_attributes: + +Observing attribute changes +--------------------------- + +You can observe any of the attributes and will receive notification if their values change. This allows you to +monitor changes to velocity and other vehicle state without the need for polling. + +.. warning:: + + There is currently `a defect (#60) `_ that means that after an + observer is triggered, the callback function is run on every heartbeat (whether or not the observed attribute changes). + +Observers are added using :py:func:`Vehicle.add_attribute_observer() `, +specifying the name of the attribute to observe and a callback function. The same string is passed to the callback +when it is notified. Observers are removed using :py:func:`remove_attribute_observer() `. + +The code snippet below shows how to add (and remove) a callback function to observe :py:attr:`location ` attribute changes. The two second ``sleep()`` is required because otherwise the observer might be removed before the the callback is first run. + +.. code:: python + + # Callback function. The parameter is the name of the observed attribute (a string) + def location_callback(attribute): + print " CALLBACK: Location changed to: ", v.location + + # Add a callback. The first parameter the name of the observed attribute (a string). + v.add_attribute_observer('location', location_callback) + + # Wait 2s so callback can be notified before the observer is removed + time.sleep(2) + + # Remove observer - specifying the attribute and previously registered callback function + v.remove_attribute_observer('location', location_callback) + + + + + +.. _vehicle_state_parameters: + +Parameters +========== + +Vehicle parameters provide the information used to configure the autopilot for the vehicle-specific hardware/capabilities. +These can be read and set using the :py:attr:`Vehicle.parameters ` +attribute (a :py:class:`Parameters ` object). + +.. tip:: + + `Copter Parameters `_, + `Plane Parameters `_, + and `Rover Parameters `_ list all the supported parameters for each platform. + The lists are automatically generated from the latest ArduPilot source code, and may contain parameters + that are not yet in the stable released versions of the code. + + + +Getting parameters +------------------ + +The parameters are read using the parameter name as a key. Reads will generally succeed unless you attempt to read an unsupported parameter +(which results in a Key error exception). + +The code example below shows how to set Minimum Throttle (THR_MIN) setting. On Copter and Rover (not Plane), this is the minimum PWM setting for the +throttle at which the motors will keep spinning. + +.. code:: python + + # Print the value of the THR_MIN parameter. + print "Param: %s" % vehicle.parameters['THR_MIN'] + + + + +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. + +.. code:: python + + # Change the parameter value (Copter, Rover) + vehicle.parameters['THR_MIN']=100 + vehicle.flush() + + + +Observing parameter changes +--------------------------- + +At time of writing :py:class:`Parameters ` does `not support `_ observing parameter changes. + +.. todo:: + + Check to see if observers have been implemented and if so, update the information here, in about, and in Vehicle class: + https://github.com/diydrones/dronekit-python/issues/107 + + + + +.. _vehicle_state_home_location: + +Home location +============= + +The *Home location* is set when a vehicle is armed and first gets a good location fix from the GPS. The location is used +as the target when the vehicle does a "return to launch". In Copter missions (and most Plane) missions, the altitude of +waypoints is set relative to this position. + +Unlike other vehicle state information, the home location is accessed as the 0 index value of +:py:attr:`Vehicle.commands `: + +.. code:: python + + cmds = v.commands + cmds.download() + cmds.wait_valid() + print " Home WP: %s" % cmds[0] + +The returned value is a :py:class:`Command ` object. + + + +.. _vehicle_state_disrecommended: + +Discommended APIs +================= + +This section describes methods that we recommend you do not use! In general they are provided to handle the (hopefully rare) +cases where the "proper" API is missing some needed functionality. + +If you have to use these methods please `provide feedback explaining why `_. + + +.. _vehicle_state_set_mavlink_callback: + +MAVLink Message Observer +------------------------ + +The :py:func:`Vehicle.set_mavlink_callback() ` method provides asynchronous +notification when any *MAVLink* packet is received from this vehicle. + +.. tip:: + + Use :ref:`attribute observers ` instead of this method where possible. + + +The code snippet below shows how to set a “demo” callback function as the callback handler: + +.. code:: python + + # Demo callback handler for raw MAVLink messages + def mavrx_debug_handler(message): + print "Received", message + + # Set MAVLink callback handler (after getting Vehicle instance) + v.set_mavlink_callback(mavrx_debug_handler) + + +.. warning:: + + At time of writing there is no way to `disable this callback `_. + + +.. _vehicle_state_channel_override: + +Channel Overrides +----------------- + +.. warning:: + + Channel Overrides may be useful for simulating user input and when implementing certain types of joystick control. + They should not be used for direct control of the vehicle unless there is no other choice! + + Instead use the appropriate MAVLink commands like DO_SET_SERVO/DO_SET_RELAY, or more generally set the desired position or direction/speed. + +The :py:attr:`channel_override ` attribute takes a dictionary argument defining the RC *output* channels to be overridden (specified by channel number), and their new values. Channels that are not specified in the dictionary are not overridden. All multi-channel updates are atomic. To cancel an override call ``channel_override`` again, setting zero for the overridden channels. + +The values of the first four channels map to the main flight controls: 1=Roll, 2=Pitch, 3=Throttle, 4=Yaw (the mapping is defined in ``RCMAP_`` parameters in +`Plane `_, +`Copter `_ , +`Rover `_). + +The remaining channel values are configurable, and their purpose can be determined using the +`RCn_FUNCTION parameters `_. +In general a value of 0 set for a specific ``RCn_FUNCTION`` indicates that the channel can be +`mission controlled `_ (i.e. it will not directly be +controlled by normal autopilot code). + +An example of setting and clearing overrides is given below: + +.. code:: python + + # Override the channel for roll and yaw + v.channel_override = { "1" : 900, "4" : 1000 } + v.flush() + + #print current override values + print "Current overrides are:", v.channel_override + + # Print channel values (values if overrides removed) + print "Channel default values:", v.channel_readback + + # Cancel override by setting channels to 0 + v.channel_override = { "1" : 0, "4" : 0 } + v.flush() + + + + +.. _api-information-known-issues: + +Known issues +============ + +Below are a number of bugs and known issues related to vehicle state and settings: + +* `#12 Timeout error when setting a parameter `_ +* `#60 Attribute observer callbacks are called with heartbeat until disabled - after first called `_ +* `#107 Add implementation for observer methods in Parameter class `_ +* `#114 DroneKit has no method for detecting command failure `_ +* `#115 No way to disable the callback set_mavlink_callback `_ + + Other API issues and improvement suggestions can viewed on `github here `_. \ No newline at end of file diff --git a/droneapi/lib/__init__.py b/droneapi/lib/__init__.py index d7cce8840..ee29778f5 100644 --- a/droneapi/lib/__init__.py +++ b/droneapi/lib/__init__.py @@ -192,21 +192,6 @@ def __str__(self): return "Battery:voltage={},current={},level={}".format(self.voltage, self.current, self.level) -class Rangefinder(object): - """ - Rangefinder readings. - - :param distance: Distance. - :param voltage: Voltage. - """ - def __init__(self, distance, voltage): - self.distance = distance - self.voltage = voltage - - def __str__(self): - return "Rangefinder: distance={}, voltage={}".format(self.distance, self.voltage) - - class VehicleMode(object): """ This object is used to get and set the current "flight mode". @@ -481,7 +466,7 @@ class Vehicle(HasObservers): Gets the ``system_status`` value from the most recently received `heartbeat `_ message. This attribute provides high-level information about whether the vehicle is on the ground, flying, in failsafe, etc. For example, - you can check if the vehicle is in a critical state as shown: + to check if the vehicle is in a critical state: .. code:: python @@ -491,6 +476,13 @@ class Vehicle(HasObservers): if v.system_status == mavutil.mavlink.MAV_STATE_CRITICAL: print "DON'T PANIC!" + If printed, the attribute returns a human-readable string containing both the ``MAV_STATE`` enum name and a description. For example: + + .. code:: bash + + [MAV_STATE_STANDBY]: System is grounded and on standby. It can be launched any time. + + The possible values of the status are defined in the `MAV_STATE `_ enum (reproduced below). .. list-table:: MAV_STATE enum. @@ -527,6 +519,11 @@ class Vehicle(HasObservers): - System just initialized its power-down sequence and will shut down now. + .. note:: + + This attribute is of type :py:class:`SystemStatus `. + + .. py:attribute:: battery @@ -905,7 +902,6 @@ class CommandSequence(object): cmds = vehicle.commands cmds.clear() - vehicle.flush() lat = -34.364114, lon = 149.166022 altitude = 30.0 @@ -974,13 +970,6 @@ def goto(self, location): def clear(self): ''' Clear the command list. - - .. warning:: - - Call ``flush()`` immediately after clearing the commands/before adding new commands (see - `#132 for more information `_). - - .. todo:: The above note should be removed when https://github.com/diydrones/dronekit-python/issues/132 fixed ''' pass @@ -1021,15 +1010,11 @@ def next(self, value): class SystemStatus(object): """ - A simple way to work with MAV_STATE messages + A convenience class (transparently) used by :py:func:`Vehicle.system_status ` for working with ``MAV_STATE`` messages. - Supported properties: + The class provides a human readable string for the system state when ``Vehicle.system_status`` is printed, and an enum value otherwise (for comparison). - ============= ====================================== - Name Description - ============= ====================================== - mav_state int - ============= ====================================== + :param int mav_state: The current system ``MAV_STATE`` enum. """ STATES = { diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index 94619059a..82afc7741 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -1,109 +1,109 @@ -# -# This example shows how to use DroneKit-Python to get and set vehicle state, parameter and channel-override information. -# It also demonstrates how to observe vehicle attribute (state) changes. -# -# Usage: -# * mavproxy.py -# * module load api -# * api start vehicle-state.py -# -from droneapi.lib import VehicleMode -from pymavlink import mavutil -import time - -# First get an instance of the API endpoint -api = local_connect() -# Get the connected vehicle (currently only one vehicle can be returned). -v = api.get_vehicles()[0] - -# Get all vehicle attributes (state) -print "\nGet all vehicle attribute values:" -print " Location: %s" % v.location -print " Attitude: %s" % v.attitude -print " Velocity: %s" % v.velocity -print " GPS: %s" % v.gps_0 -print " Groundspeed: %s" % v.groundspeed -print " Airspeed: %s" % v.airspeed -print " Mount status: %s" % v.mount_status -print " Battery: %s" % v.battery -print " System status: %s" % v.system_status -print " Mode: %s" % v.mode.name # settable -print " Armed: %s" % v.armed # settable - - -# when trying to compare v.system_status with enum from mavlink -# it will always yeild the enum instead of string value -if v.system_status == mavutil.mavlink.MAV_STATE_STANDBY: - print 'Standing by waiting instructions' - -# Set vehicle mode and armed attributes (the only settable attributes) -print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name -v.mode = VehicleMode("GUIDED") -v.flush() # Flush to guarantee that previous writes to the vehicle have taken place -while not v.mode.name=='GUIDED' and not api.exit: #Wait until mode has changed - print " Waiting for mode change ..." - time.sleep(1) - -print "Set Vehicle.armed=True (currently: %s)" % v.armed -v.armed = True -v.flush() -while not v.armed and not api.exit: - print " Waiting for arming..." - time.sleep(1) - -# Show how to add and remove and attribute observer callbacks (using mode as example) -def mode_callback(attribute): - print " CALLBACK: Mode changed to: ", v.mode.name - -print "\nAdd mode attribute observer for Vehicle.mode" -v.add_attribute_observer('mode', mode_callback) - -print " Set mode=STABILIZE (currently: %s)" % v.mode.name -v.mode = VehicleMode("STABILIZE") -v.flush() - -print " Wait 2s so callback invoked before observer removed" -time.sleep(2) - -# Remove observer - specifying the attribute and previously registered callback function -v.remove_attribute_observer('mode', mode_callback) - - -# Get Vehicle Home location ((0 index in Vehicle.commands) -print "\nGet home location" -cmds = v.commands -cmds.download() -cmds.wait_valid() -print " Home WP: %s" % cmds[0] - - -# Get/Set Vehicle Parameters -print "\nRead vehicle param 'THR_MIN': %s" % v.parameters['THR_MIN'] -print "Write vehicle param 'THR_MIN' : 10" -v.parameters['THR_MIN']=10 -v.flush() -print "Read new value of param 'THR_MIN': %s" % v.parameters['THR_MIN'] - - -# Overriding an RC channel -# NOTE: CHANNEL OVERRIDES may be useful for simulating user input and when implementing certain types of joystick control. -#DO NOT use unless there is no other choice (there almost always is!) -print "\nOverriding RC channels for roll and yaw" -v.channel_override = { "1" : 900, "4" : 1000 } -v.flush() -print " Current overrides are:", v.channel_override -print " Channel default values:", v.channel_readback # All channel values before override - -# Cancel override by setting channels to 0 -print " Cancelling override" -v.channel_override = { "1" : 0, "4" : 0 } -v.flush() - - -## Reset variables to sensible values. -print "\nReset vehicle attributes/parameters and exit" -v.mode = VehicleMode("STABILIZE") -v.armed = False -v.parameters['THR_MIN']=130 -v.flush() - +# +# This example shows how to use DroneKit-Python to get and set vehicle state, parameter and channel-override information. +# It also demonstrates how to observe vehicle attribute (state) changes. +# +# Usage: +# * mavproxy.py +# * module load api +# * api start vehicle-state.py +# +from droneapi.lib import VehicleMode +from pymavlink import mavutil +import time + +# First get an instance of the API endpoint +api = local_connect() +# Get the connected vehicle (currently only one vehicle can be returned). +v = api.get_vehicles()[0] + +# Get all vehicle attributes (state) +print "\nGet all vehicle attribute values:" +print " Location: %s" % v.location +print " Attitude: %s" % v.attitude +print " Velocity: %s" % v.velocity +print " GPS: %s" % v.gps_0 +print " Groundspeed: %s" % v.groundspeed +print " Airspeed: %s" % v.airspeed +print " Mount status: %s" % v.mount_status +print " Battery: %s" % v.battery +print " System status: %s" % v.system_status +print " Mode: %s" % v.mode.name # settable +print " Armed: %s" % v.armed # settable + + +# Printing Vehicle.system_status returns a string. Otherwise the attribute yields a +# MAV_STATE enum value that can be used for comparisons (as shown below). +if v.system_status == mavutil.mavlink.MAV_STATE_STANDBY: + print 'Standing by - waiting for instructions' + +# Set vehicle mode and armed attributes (the only settable attributes) +print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name +v.mode = VehicleMode("GUIDED") +v.flush() # Flush to guarantee that previous writes to the vehicle have taken place +while not v.mode.name=='GUIDED' and not api.exit: #Wait until mode has changed + print " Waiting for mode change ..." + time.sleep(1) + +print "Set Vehicle.armed=True (currently: %s)" % v.armed +v.armed = True +v.flush() +while not v.armed and not api.exit: + print " Waiting for arming..." + time.sleep(1) + +# Show how to add and remove and attribute observer callbacks (using mode as example) +def mode_callback(attribute): + print " CALLBACK: Mode changed to: ", v.mode.name + +print "\nAdd mode attribute observer for Vehicle.mode" +v.add_attribute_observer('mode', mode_callback) + +print " Set mode=STABILIZE (currently: %s)" % v.mode.name +v.mode = VehicleMode("STABILIZE") +v.flush() + +print " Wait 2s so callback invoked before observer removed" +time.sleep(2) + +# Remove observer - specifying the attribute and previously registered callback function +v.remove_attribute_observer('mode', mode_callback) + + +# Get Vehicle Home location ((0 index in Vehicle.commands) +print "\nGet home location" +cmds = v.commands +cmds.download() +cmds.wait_valid() +print " Home WP: %s" % cmds[0] + + +# Get/Set Vehicle Parameters +print "\nRead vehicle param 'THR_MIN': %s" % v.parameters['THR_MIN'] +print "Write vehicle param 'THR_MIN' : 10" +v.parameters['THR_MIN']=10 +v.flush() +print "Read new value of param 'THR_MIN': %s" % v.parameters['THR_MIN'] + + +# Overriding an RC channel +# NOTE: CHANNEL OVERRIDES may be useful for simulating user input and when implementing certain types of joystick control. +#DO NOT use unless there is no other choice (there almost always is!) +print "\nOverriding RC channels for roll and yaw" +v.channel_override = { "1" : 900, "4" : 1000 } +v.flush() +print " Current overrides are:", v.channel_override +print " Channel default values:", v.channel_readback # All channel values before override + +# Cancel override by setting channels to 0 +print " Cancelling override" +v.channel_override = { "1" : 0, "4" : 0 } +v.flush() + + +## Reset variables to sensible values. +print "\nReset vehicle attributes/parameters and exit" +v.mode = VehicleMode("STABILIZE") +v.armed = False +v.parameters['THR_MIN']=130 +v.flush() + From 1e5b9f4a33ce31c563f6765ec66f5390842d1067 Mon Sep 17 00:00:00 2001 From: Tim Ryan Date: Fri, 24 Jul 2015 14:09:39 -0700 Subject: [PATCH 7/7] Fixes merge issues. --- docs/examples/vehicle_state.rst | 139 +--- docs/guide/vehicle_state_and_parameters.rst | 692 ++++++++++---------- examples/vehicle_state/vehicle_state.py | 218 +++--- 3 files changed, 461 insertions(+), 588 deletions(-) diff --git a/docs/examples/vehicle_state.rst b/docs/examples/vehicle_state.rst index 87fe4f42b..f4537039e 100644 --- a/docs/examples/vehicle_state.rst +++ b/docs/examples/vehicle_state.rst @@ -14,7 +14,7 @@ should be used. Running the example =================== -The vehicle and DroneKit should be set up as described in :ref:`get-started`. +The vehicle and DroneKit should be set up as described in the :ref:`quick-start` or :ref:`get-started`. If you're using a simulated vehicle, remember to :ref:`disable arming checks ` so that the example can run. @@ -42,10 +42,10 @@ On the *MAVProxy* console you should see (something like): Airspeed: 0.0 Mount status: [None, None, None] Battery: Battery:voltage=12.587,current=0.0,level=98 - System status: 3 + System status: [MAV_STATE_STANDBY]: System is grounded and on standby. It can be launched any time. Mode: STABILIZE Armed: False - Current Status: MAV_STATE_STANDBY: System is grounded and on standby. It can be launched any time. + Standing by - waiting for instructions Set Vehicle.mode=GUIDED (currently: STABILIZE) Waiting for mode change ... Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} @@ -120,135 +120,8 @@ Two cases where you may observe issues are: Source code =========== -The full source code at documentation build-time is listed below (`current version on github `_): - +The full source code at documentation build-time is listed below (`current version on github `_): + .. literalinclude:: ../../examples/vehicle_state/vehicle_state.py :language: python - -======= -.. _example-vehicle-state: - -====================== -Example: Vehicle State -====================== - -This example shows how to get/set vehicle attribute, parameter and channel-override 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. - - -Running the example -=================== - -The vehicle and DroneKit should be set up as described in the :ref:`quick-start` or :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 vehicle_state.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/vehicle_state/vehicle_state.py``. - - -On the *MAVProxy* console you should see (something like): - -.. code:: bash - - MAV> api start vehicle_state.py - STABILIZE> - - Get all vehicle attribute values: - Location: Attitude: Attitude:pitch=-0.00405988190323,yaw=-0.0973932668567,roll=-0.00393210304901 - Velocity: [0.06, -0.07, 0.0] - GPS: GPSInfo:fix=3,num_sat=10 - Groundspeed: 0.0 - Airspeed: 0.0 - Mount status: [None, None, None] - Battery: Battery:voltage=12.587,current=0.0,level=98 - System status: [MAV_STATE_STANDBY]: System is grounded and on standby. It can be launched any time. - Mode: STABILIZE - Armed: False - Standing by - waiting for instructions - Set Vehicle.mode=GUIDED (currently: STABILIZE) - Waiting for mode change ... - Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} - GUIDED> Mode GUIDED - Set Vehicle.armed=True (currently: False) - Waiting for arming... - APM: ARMING MOTORS - APM: Initialising APM... - Got MAVLink msg: COMMAND_ACK {command : 400, result : 0} - ARMED - - Add mode attribute observer for Vehicle.mode - Set mode=STABILIZE (currently: GUIDED) - Wait 2s so callback invoked before observer removed - Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} - STABILIZE> Mode STABILIZE - CALLBACK: Mode changed to: STABILIZE - - Get home location - Requesting 0 waypoints t=Fri May 15 11:35:58 2015 now=Fri May 15 11:35:58 2015 - Home WP: MISSION_ITEM {target_system : 255, 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 : 583.729980469} - - Read vehicle param 'THR_MIN': 130.0 - Write vehicle param 'THR_MIN' : 10 - timeout setting THR_MIN to 10.000000 - Read new value of param 'THR_MIN': 10.0 - - Overriding RC channels for roll and yaw - Current overrides are: {'1': 900, '4': 1000} - Channel default values: {'1': 1500, '3': 1000, '2': 1500, '5': 1800, '4': 1500, '7': 1000, '6': 1000, '8': 1800} - Cancelling override - - Reset vehicle atributes/parameters and exit - Got MAVLink msg: COMMAND_ACK {command : 11, result : 0} - APM: DISARMING MOTORS - Got MAVLink msg: COMMAND_ACK {command : 400, result : 0} - DISARMED - timeout setting THR_MIN to 130.000000 - APIThread-0 exiting... - - - -How does it work? -================= - -The guide topic :ref:`vehicle-information` provides an explanation of how this code works. - -.. INTERNAL COMMENT: - - Normally we'd highlight code here but all of it is worth of highlight, and we do that in the - linked guide - - -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 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. - See `#60 Attribute observer callbacks are called with heartbeat until disabled - after first called `_ - for more information. - - - -Source code -=========== - -The full source code at documentation build-time is listed below (`current version on github `_): - -.. literalinclude:: ../../examples/vehicle_state/vehicle_state.py - :language: python + diff --git a/docs/guide/vehicle_state_and_parameters.rst b/docs/guide/vehicle_state_and_parameters.rst index 13efd4551..41cf2dcf6 100644 --- a/docs/guide/vehicle_state_and_parameters.rst +++ b/docs/guide/vehicle_state_and_parameters.rst @@ -1,347 +1,347 @@ -.. _vehicle-information: - -=========================== -Vehicle State and Settings -=========================== - -The :py:class:`Vehicle ` class exposes *most* state information (position, speed, etc.) through python -:ref:`attributes `, while vehicle :ref:`parameters ` (settings) -are accessed though named elements of :py:attr:`Vehicle.parameters `. - -This topic explains how to get, set and observe vehicle state and parameter information (including getting the -:ref:`Home location `). It also describes a few APIs that -:ref:`should be used with caution `. - -.. tip:: You can test most of the code in this topic by running the :ref:`Vehicle State ` example. - - -.. _vehicle_state_attributes: - -Attributes -========== - -Vehicle state information is exposed through vehicle *attributes*. DroneKit-Python currently supports the following -"standard" attributes: -:py:attr:`Vehicle.location `, -:py:attr:`Vehicle.attitude `, -:py:attr:`Vehicle.velocity `, -:py:attr:`Vehicle.mode `, -:py:attr:`Vehicle.airspeed `, -:py:attr:`Vehicle.groundspeed `, -:py:attr:`Vehicle.gps_0 `, -:py:attr:`Vehicle.armed `, -:py:attr:`Vehicle.location `, -:py:attr:`Vehicle.mount_status `, -:py:attr:`Vehicle.battery `, -:py:attr:`Vehicle.system_status `. - -All of the attributes can be :ref:`read ` and :ref:`observed `, -but only the :py:attr:`Vehicle.mode ` and :py:attr:`Vehicle.armed ` -status can be :ref:`written `. - - -.. _vehicle_state_read_attributes: - -Getting attributes ------------------- - -The code fragment below shows how to read and print all the attributes. The values are retrieved from the remote device -(not cached). - -.. code:: python - - # v is an instance of the Vehicle class - print "Location: %s" % v.location - print "Attitude: %s" % v.attitude - print "Velocity: %s" % v.velocity - print "GPS: %s" % v.gps_0 - print "Groundspeed: %s" % v.groundspeed - print "Airspeed: %s" % v.airspeed - print "Mount status: %s" % v.mount_status - print "Battery: %s" % v.battery - print "System status: %s" % v.system_status - print "Mode: %s" % v.mode.name # settable - print "Armed: %s" % v.armed # settable - - -If these attributes cannot be retrieved or are invalid then the returned object will usually contain -``None`` values for its members (for example, if there was no GPS lock then -:py:attr:`Vehicle.gps_0 ` would return a :py:class:`GPSInfo ` -with ``None`` values for ``eph``, ``satellites_visible`` etc.) - -The :py:attr:`Vehicle.system_status ` has slightly different behaviour from the other attributes: - -* It will return the last value retrieved if the heartbeat fails (rather than ``None``). -* The attribute returns a ``MAV_STATE`` enum value for comparisons, and a human-readable string for the state when printed. - - -.. todo:: we need to be able to verify mount_status works/setup. - - - -.. _vehicle_state_set_attributes: - -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. - -.. code:: python - - #disarm the vehicle - v.armed = False - v.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**. - 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 `_. - - -Code should not assume that an attempt to set an attribute will succeed. The example code snippet below polls the attribute values -to confirm they have changed before proceeding. - -.. code:: python - - v.mode = VehicleMode("GUIDED") - v.armed = True - v.flush() # Flush to ensure changes are sent to autopilot - while not v.mode.name=='GUIDED' and not v.armed and not api.exit: - print " Getting ready to take off ..." - time.sleep(1) - - - -.. _vehicle_state_observe_attributes: - -Observing attribute changes ---------------------------- - -You can observe any of the attributes and will receive notification if their values change. This allows you to -monitor changes to velocity and other vehicle state without the need for polling. - -.. warning:: - - There is currently `a defect (#60) `_ that means that after an - observer is triggered, the callback function is run on every heartbeat (whether or not the observed attribute changes). - -Observers are added using :py:func:`Vehicle.add_attribute_observer() `, -specifying the name of the attribute to observe and a callback function. The same string is passed to the callback -when it is notified. Observers are removed using :py:func:`remove_attribute_observer() `. - -The code snippet below shows how to add (and remove) a callback function to observe :py:attr:`location ` attribute changes. The two second ``sleep()`` is required because otherwise the observer might be removed before the the callback is first run. - -.. code:: python - - # Callback function. The parameter is the name of the observed attribute (a string) - def location_callback(attribute): - print " CALLBACK: Location changed to: ", v.location - - # Add a callback. The first parameter the name of the observed attribute (a string). - v.add_attribute_observer('location', location_callback) - - # Wait 2s so callback can be notified before the observer is removed - time.sleep(2) - - # Remove observer - specifying the attribute and previously registered callback function - v.remove_attribute_observer('location', location_callback) - - - - - -.. _vehicle_state_parameters: - -Parameters -========== - -Vehicle parameters provide the information used to configure the autopilot for the vehicle-specific hardware/capabilities. -These can be read and set using the :py:attr:`Vehicle.parameters ` -attribute (a :py:class:`Parameters ` object). - -.. tip:: - - `Copter Parameters `_, - `Plane Parameters `_, - and `Rover Parameters `_ list all the supported parameters for each platform. - The lists are automatically generated from the latest ArduPilot source code, and may contain parameters - that are not yet in the stable released versions of the code. - - - -Getting parameters ------------------- - -The parameters are read using the parameter name as a key. Reads will generally succeed unless you attempt to read an unsupported parameter -(which results in a Key error exception). - -The code example below shows how to set Minimum Throttle (THR_MIN) setting. On Copter and Rover (not Plane), this is the minimum PWM setting for the -throttle at which the motors will keep spinning. - -.. code:: python - - # Print the value of the THR_MIN parameter. - print "Param: %s" % vehicle.parameters['THR_MIN'] - - - - -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. - -.. code:: python - - # Change the parameter value (Copter, Rover) - vehicle.parameters['THR_MIN']=100 - vehicle.flush() - - - -Observing parameter changes ---------------------------- - -At time of writing :py:class:`Parameters ` does `not support `_ observing parameter changes. - -.. todo:: - - Check to see if observers have been implemented and if so, update the information here, in about, and in Vehicle class: - https://github.com/diydrones/dronekit-python/issues/107 - - - - -.. _vehicle_state_home_location: - -Home location -============= - -The *Home location* is set when a vehicle is armed and first gets a good location fix from the GPS. The location is used -as the target when the vehicle does a "return to launch". In Copter missions (and most Plane) missions, the altitude of -waypoints is set relative to this position. - -Unlike other vehicle state information, the home location is accessed as the 0 index value of -:py:attr:`Vehicle.commands `: - -.. code:: python - - cmds = v.commands - cmds.download() - cmds.wait_valid() - print " Home WP: %s" % cmds[0] - -The returned value is a :py:class:`Command ` object. - - - -.. _vehicle_state_disrecommended: - -Discommended APIs -================= - -This section describes methods that we recommend you do not use! In general they are provided to handle the (hopefully rare) -cases where the "proper" API is missing some needed functionality. - -If you have to use these methods please `provide feedback explaining why `_. - - -.. _vehicle_state_set_mavlink_callback: - -MAVLink Message Observer ------------------------- - -The :py:func:`Vehicle.set_mavlink_callback() ` method provides asynchronous -notification when any *MAVLink* packet is received from this vehicle. - -.. tip:: - - Use :ref:`attribute observers ` instead of this method where possible. - - -The code snippet below shows how to set a “demo” callback function as the callback handler: - -.. code:: python - - # Demo callback handler for raw MAVLink messages - def mavrx_debug_handler(message): - print "Received", message - - # Set MAVLink callback handler (after getting Vehicle instance) - v.set_mavlink_callback(mavrx_debug_handler) - - -.. warning:: - - At time of writing there is no way to `disable this callback `_. - - -.. _vehicle_state_channel_override: - -Channel Overrides ------------------ - -.. warning:: - - Channel Overrides may be useful for simulating user input and when implementing certain types of joystick control. - They should not be used for direct control of the vehicle unless there is no other choice! - - Instead use the appropriate MAVLink commands like DO_SET_SERVO/DO_SET_RELAY, or more generally set the desired position or direction/speed. - -The :py:attr:`channel_override ` attribute takes a dictionary argument defining the RC *output* channels to be overridden (specified by channel number), and their new values. Channels that are not specified in the dictionary are not overridden. All multi-channel updates are atomic. To cancel an override call ``channel_override`` again, setting zero for the overridden channels. - -The values of the first four channels map to the main flight controls: 1=Roll, 2=Pitch, 3=Throttle, 4=Yaw (the mapping is defined in ``RCMAP_`` parameters in -`Plane `_, -`Copter `_ , -`Rover `_). - -The remaining channel values are configurable, and their purpose can be determined using the -`RCn_FUNCTION parameters `_. -In general a value of 0 set for a specific ``RCn_FUNCTION`` indicates that the channel can be -`mission controlled `_ (i.e. it will not directly be -controlled by normal autopilot code). - -An example of setting and clearing overrides is given below: - -.. code:: python - - # Override the channel for roll and yaw - v.channel_override = { "1" : 900, "4" : 1000 } - v.flush() - - #print current override values - print "Current overrides are:", v.channel_override - - # Print channel values (values if overrides removed) - print "Channel default values:", v.channel_readback - - # Cancel override by setting channels to 0 - v.channel_override = { "1" : 0, "4" : 0 } - v.flush() - - - - -.. _api-information-known-issues: - -Known issues -============ - -Below are a number of bugs and known issues related to vehicle state and settings: - -* `#12 Timeout error when setting a parameter `_ -* `#60 Attribute observer callbacks are called with heartbeat until disabled - after first called `_ -* `#107 Add implementation for observer methods in Parameter class `_ -* `#114 DroneKit has no method for detecting command failure `_ -* `#115 No way to disable the callback set_mavlink_callback `_ - - +.. _vehicle-information: + +=========================== +Vehicle State and Settings +=========================== + +The :py:class:`Vehicle ` class exposes *most* state information (position, speed, etc.) through python +:ref:`attributes `, while vehicle :ref:`parameters ` (settings) +are accessed though named elements of :py:attr:`Vehicle.parameters `. + +This topic explains how to get, set and observe vehicle state and parameter information (including getting the +:ref:`Home location `). It also describes a few APIs that +:ref:`should be used with caution `. + +.. tip:: You can test most of the code in this topic by running the :ref:`Vehicle State ` example. + + +.. _vehicle_state_attributes: + +Attributes +========== + +Vehicle state information is exposed through vehicle *attributes*. DroneKit-Python currently supports the following +"standard" attributes: +:py:attr:`Vehicle.location `, +:py:attr:`Vehicle.attitude `, +:py:attr:`Vehicle.velocity `, +:py:attr:`Vehicle.mode `, +:py:attr:`Vehicle.airspeed `, +:py:attr:`Vehicle.groundspeed `, +:py:attr:`Vehicle.gps_0 `, +:py:attr:`Vehicle.armed `, +:py:attr:`Vehicle.location `, +:py:attr:`Vehicle.mount_status `, +:py:attr:`Vehicle.battery `, +:py:attr:`Vehicle.system_status `. + +All of the attributes can be :ref:`read ` and :ref:`observed `, +but only the :py:attr:`Vehicle.mode ` and :py:attr:`Vehicle.armed ` +status can be :ref:`written `. + + +.. _vehicle_state_read_attributes: + +Getting attributes +------------------ + +The code fragment below shows how to read and print all the attributes. The values are retrieved from the remote device +(not cached). + +.. code:: python + + # v is an instance of the Vehicle class + print "Location: %s" % v.location + print "Attitude: %s" % v.attitude + print "Velocity: %s" % v.velocity + print "GPS: %s" % v.gps_0 + print "Groundspeed: %s" % v.groundspeed + print "Airspeed: %s" % v.airspeed + print "Mount status: %s" % v.mount_status + print "Battery: %s" % v.battery + print "System status: %s" % v.system_status + print "Mode: %s" % v.mode.name # settable + print "Armed: %s" % v.armed # settable + + +If these attributes cannot be retrieved or are invalid then the returned object will usually contain +``None`` values for its members (for example, if there was no GPS lock then +:py:attr:`Vehicle.gps_0 ` would return a :py:class:`GPSInfo ` +with ``None`` values for ``eph``, ``satellites_visible`` etc.) + +The :py:attr:`Vehicle.system_status ` has slightly different behaviour from the other attributes: + +* It will return the last value retrieved if the heartbeat fails (rather than ``None``). +* The attribute returns a ``MAV_STATE`` enum value for comparisons, and a human-readable string for the state when printed. + + +.. todo:: we need to be able to verify mount_status works/setup. + + + +.. _vehicle_state_set_attributes: + +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. + +.. code:: python + + #disarm the vehicle + v.armed = False + v.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**. + 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 `_. + + +Code should not assume that an attempt to set an attribute will succeed. The example code snippet below polls the attribute values +to confirm they have changed before proceeding. + +.. code:: python + + v.mode = VehicleMode("GUIDED") + v.armed = True + v.flush() # Flush to ensure changes are sent to autopilot + while not v.mode.name=='GUIDED' and not v.armed and not api.exit: + print " Getting ready to take off ..." + time.sleep(1) + + + +.. _vehicle_state_observe_attributes: + +Observing attribute changes +--------------------------- + +You can observe any of the attributes and will receive notification if their values change. This allows you to +monitor changes to velocity and other vehicle state without the need for polling. + +.. warning:: + + There is currently `a defect (#60) `_ that means that after an + observer is triggered, the callback function is run on every heartbeat (whether or not the observed attribute changes). + +Observers are added using :py:func:`Vehicle.add_attribute_observer() `, +specifying the name of the attribute to observe and a callback function. The same string is passed to the callback +when it is notified. Observers are removed using :py:func:`remove_attribute_observer() `. + +The code snippet below shows how to add (and remove) a callback function to observe :py:attr:`location ` attribute changes. The two second ``sleep()`` is required because otherwise the observer might be removed before the the callback is first run. + +.. code:: python + + # Callback function. The parameter is the name of the observed attribute (a string) + def location_callback(attribute): + print " CALLBACK: Location changed to: ", v.location + + # Add a callback. The first parameter the name of the observed attribute (a string). + v.add_attribute_observer('location', location_callback) + + # Wait 2s so callback can be notified before the observer is removed + time.sleep(2) + + # Remove observer - specifying the attribute and previously registered callback function + v.remove_attribute_observer('location', location_callback) + + + + + +.. _vehicle_state_parameters: + +Parameters +========== + +Vehicle parameters provide the information used to configure the autopilot for the vehicle-specific hardware/capabilities. +These can be read and set using the :py:attr:`Vehicle.parameters ` +attribute (a :py:class:`Parameters ` object). + +.. tip:: + + `Copter Parameters `_, + `Plane Parameters `_, + and `Rover Parameters `_ list all the supported parameters for each platform. + The lists are automatically generated from the latest ArduPilot source code, and may contain parameters + that are not yet in the stable released versions of the code. + + + +Getting parameters +------------------ + +The parameters are read using the parameter name as a key. Reads will generally succeed unless you attempt to read an unsupported parameter +(which results in a Key error exception). + +The code example below shows how to set Minimum Throttle (THR_MIN) setting. On Copter and Rover (not Plane), this is the minimum PWM setting for the +throttle at which the motors will keep spinning. + +.. code:: python + + # Print the value of the THR_MIN parameter. + print "Param: %s" % vehicle.parameters['THR_MIN'] + + + + +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. + +.. code:: python + + # Change the parameter value (Copter, Rover) + vehicle.parameters['THR_MIN']=100 + vehicle.flush() + + + +Observing parameter changes +--------------------------- + +At time of writing :py:class:`Parameters ` does `not support `_ observing parameter changes. + +.. todo:: + + Check to see if observers have been implemented and if so, update the information here, in about, and in Vehicle class: + https://github.com/diydrones/dronekit-python/issues/107 + + + + +.. _vehicle_state_home_location: + +Home location +============= + +The *Home location* is set when a vehicle is armed and first gets a good location fix from the GPS. The location is used +as the target when the vehicle does a "return to launch". In Copter missions (and most Plane) missions, the altitude of +waypoints is set relative to this position. + +Unlike other vehicle state information, the home location is accessed as the 0 index value of +:py:attr:`Vehicle.commands `: + +.. code:: python + + cmds = v.commands + cmds.download() + cmds.wait_valid() + print " Home WP: %s" % cmds[0] + +The returned value is a :py:class:`Command ` object. + + + +.. _vehicle_state_disrecommended: + +Discommended APIs +================= + +This section describes methods that we recommend you do not use! In general they are provided to handle the (hopefully rare) +cases where the "proper" API is missing some needed functionality. + +If you have to use these methods please `provide feedback explaining why `_. + + +.. _vehicle_state_set_mavlink_callback: + +MAVLink Message Observer +------------------------ + +The :py:func:`Vehicle.set_mavlink_callback() ` method provides asynchronous +notification when any *MAVLink* packet is received from this vehicle. + +.. tip:: + + Use :ref:`attribute observers ` instead of this method where possible. + + +The code snippet below shows how to set a “demo” callback function as the callback handler: + +.. code:: python + + # Demo callback handler for raw MAVLink messages + def mavrx_debug_handler(message): + print "Received", message + + # Set MAVLink callback handler (after getting Vehicle instance) + v.set_mavlink_callback(mavrx_debug_handler) + + +.. warning:: + + At time of writing there is no way to `disable this callback `_. + + +.. _vehicle_state_channel_override: + +Channel Overrides +----------------- + +.. warning:: + + Channel Overrides may be useful for simulating user input and when implementing certain types of joystick control. + They should not be used for direct control of the vehicle unless there is no other choice! + + Instead use the appropriate MAVLink commands like DO_SET_SERVO/DO_SET_RELAY, or more generally set the desired position or direction/speed. + +The :py:attr:`channel_override ` attribute takes a dictionary argument defining the RC *output* channels to be overridden (specified by channel number), and their new values. Channels that are not specified in the dictionary are not overridden. All multi-channel updates are atomic. To cancel an override call ``channel_override`` again, setting zero for the overridden channels. + +The values of the first four channels map to the main flight controls: 1=Roll, 2=Pitch, 3=Throttle, 4=Yaw (the mapping is defined in ``RCMAP_`` parameters in +`Plane `_, +`Copter `_ , +`Rover `_). + +The remaining channel values are configurable, and their purpose can be determined using the +`RCn_FUNCTION parameters `_. +In general a value of 0 set for a specific ``RCn_FUNCTION`` indicates that the channel can be +`mission controlled `_ (i.e. it will not directly be +controlled by normal autopilot code). + +An example of setting and clearing overrides is given below: + +.. code:: python + + # Override the channel for roll and yaw + v.channel_override = { "1" : 900, "4" : 1000 } + v.flush() + + #print current override values + print "Current overrides are:", v.channel_override + + # Print channel values (values if overrides removed) + print "Channel default values:", v.channel_readback + + # Cancel override by setting channels to 0 + v.channel_override = { "1" : 0, "4" : 0 } + v.flush() + + + + +.. _api-information-known-issues: + +Known issues +============ + +Below are a number of bugs and known issues related to vehicle state and settings: + +* `#12 Timeout error when setting a parameter `_ +* `#60 Attribute observer callbacks are called with heartbeat until disabled - after first called `_ +* `#107 Add implementation for observer methods in Parameter class `_ +* `#114 DroneKit has no method for detecting command failure `_ +* `#115 No way to disable the callback set_mavlink_callback `_ + + Other API issues and improvement suggestions can viewed on `github here `_. \ No newline at end of file diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index 82afc7741..444b66a5f 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -1,109 +1,109 @@ -# -# This example shows how to use DroneKit-Python to get and set vehicle state, parameter and channel-override information. -# It also demonstrates how to observe vehicle attribute (state) changes. -# -# Usage: -# * mavproxy.py -# * module load api -# * api start vehicle-state.py -# -from droneapi.lib import VehicleMode -from pymavlink import mavutil -import time - -# First get an instance of the API endpoint -api = local_connect() -# Get the connected vehicle (currently only one vehicle can be returned). -v = api.get_vehicles()[0] - -# Get all vehicle attributes (state) -print "\nGet all vehicle attribute values:" -print " Location: %s" % v.location -print " Attitude: %s" % v.attitude -print " Velocity: %s" % v.velocity -print " GPS: %s" % v.gps_0 -print " Groundspeed: %s" % v.groundspeed -print " Airspeed: %s" % v.airspeed -print " Mount status: %s" % v.mount_status -print " Battery: %s" % v.battery -print " System status: %s" % v.system_status -print " Mode: %s" % v.mode.name # settable -print " Armed: %s" % v.armed # settable - - -# Printing Vehicle.system_status returns a string. Otherwise the attribute yields a -# MAV_STATE enum value that can be used for comparisons (as shown below). -if v.system_status == mavutil.mavlink.MAV_STATE_STANDBY: - print 'Standing by - waiting for instructions' - -# Set vehicle mode and armed attributes (the only settable attributes) -print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name -v.mode = VehicleMode("GUIDED") -v.flush() # Flush to guarantee that previous writes to the vehicle have taken place -while not v.mode.name=='GUIDED' and not api.exit: #Wait until mode has changed - print " Waiting for mode change ..." - time.sleep(1) - -print "Set Vehicle.armed=True (currently: %s)" % v.armed -v.armed = True -v.flush() -while not v.armed and not api.exit: - print " Waiting for arming..." - time.sleep(1) - -# Show how to add and remove and attribute observer callbacks (using mode as example) -def mode_callback(attribute): - print " CALLBACK: Mode changed to: ", v.mode.name - -print "\nAdd mode attribute observer for Vehicle.mode" -v.add_attribute_observer('mode', mode_callback) - -print " Set mode=STABILIZE (currently: %s)" % v.mode.name -v.mode = VehicleMode("STABILIZE") -v.flush() - -print " Wait 2s so callback invoked before observer removed" -time.sleep(2) - -# Remove observer - specifying the attribute and previously registered callback function -v.remove_attribute_observer('mode', mode_callback) - - -# Get Vehicle Home location ((0 index in Vehicle.commands) -print "\nGet home location" -cmds = v.commands -cmds.download() -cmds.wait_valid() -print " Home WP: %s" % cmds[0] - - -# Get/Set Vehicle Parameters -print "\nRead vehicle param 'THR_MIN': %s" % v.parameters['THR_MIN'] -print "Write vehicle param 'THR_MIN' : 10" -v.parameters['THR_MIN']=10 -v.flush() -print "Read new value of param 'THR_MIN': %s" % v.parameters['THR_MIN'] - - -# Overriding an RC channel -# NOTE: CHANNEL OVERRIDES may be useful for simulating user input and when implementing certain types of joystick control. -#DO NOT use unless there is no other choice (there almost always is!) -print "\nOverriding RC channels for roll and yaw" -v.channel_override = { "1" : 900, "4" : 1000 } -v.flush() -print " Current overrides are:", v.channel_override -print " Channel default values:", v.channel_readback # All channel values before override - -# Cancel override by setting channels to 0 -print " Cancelling override" -v.channel_override = { "1" : 0, "4" : 0 } -v.flush() - - -## Reset variables to sensible values. -print "\nReset vehicle attributes/parameters and exit" -v.mode = VehicleMode("STABILIZE") -v.armed = False -v.parameters['THR_MIN']=130 -v.flush() - +# +# This example shows how to use DroneKit-Python to get and set vehicle state, parameter and channel-override information. +# It also demonstrates how to observe vehicle attribute (state) changes. +# +# Usage: +# * mavproxy.py +# * module load api +# * api start vehicle-state.py +# +from droneapi.lib import VehicleMode +from pymavlink import mavutil +import time + +# First get an instance of the API endpoint +api = local_connect() +# Get the connected vehicle (currently only one vehicle can be returned). +v = api.get_vehicles()[0] + +# Get all vehicle attributes (state) +print "\nGet all vehicle attribute values:" +print " Location: %s" % v.location +print " Attitude: %s" % v.attitude +print " Velocity: %s" % v.velocity +print " GPS: %s" % v.gps_0 +print " Groundspeed: %s" % v.groundspeed +print " Airspeed: %s" % v.airspeed +print " Mount status: %s" % v.mount_status +print " Battery: %s" % v.battery +print " System status: %s" % v.system_status +print " Mode: %s" % v.mode.name # settable +print " Armed: %s" % v.armed # settable + + +# Printing Vehicle.system_status returns a string. Otherwise the attribute yields a +# MAV_STATE enum value that can be used for comparisons (as shown below). +if v.system_status == mavutil.mavlink.MAV_STATE_STANDBY: + print 'Standing by - waiting for instructions' + +# Set vehicle mode and armed attributes (the only settable attributes) +print "Set Vehicle.mode=GUIDED (currently: %s)" % v.mode.name +v.mode = VehicleMode("GUIDED") +v.flush() # Flush to guarantee that previous writes to the vehicle have taken place +while not v.mode.name=='GUIDED' and not api.exit: #Wait until mode has changed + print " Waiting for mode change ..." + time.sleep(1) + +print "Set Vehicle.armed=True (currently: %s)" % v.armed +v.armed = True +v.flush() +while not v.armed and not api.exit: + print " Waiting for arming..." + time.sleep(1) + +# Show how to add and remove and attribute observer callbacks (using mode as example) +def mode_callback(attribute): + print " CALLBACK: Mode changed to: ", v.mode.name + +print "\nAdd mode attribute observer for Vehicle.mode" +v.add_attribute_observer('mode', mode_callback) + +print " Set mode=STABILIZE (currently: %s)" % v.mode.name +v.mode = VehicleMode("STABILIZE") +v.flush() + +print " Wait 2s so callback invoked before observer removed" +time.sleep(2) + +# Remove observer - specifying the attribute and previously registered callback function +v.remove_attribute_observer('mode', mode_callback) + + +# Get Vehicle Home location ((0 index in Vehicle.commands) +print "\nGet home location" +cmds = v.commands +cmds.download() +cmds.wait_valid() +print " Home WP: %s" % cmds[0] + + +# Get/Set Vehicle Parameters +print "\nRead vehicle param 'THR_MIN': %s" % v.parameters['THR_MIN'] +print "Write vehicle param 'THR_MIN' : 10" +v.parameters['THR_MIN']=10 +v.flush() +print "Read new value of param 'THR_MIN': %s" % v.parameters['THR_MIN'] + + +# Overriding an RC channel +# NOTE: CHANNEL OVERRIDES may be useful for simulating user input and when implementing certain types of joystick control. +#DO NOT use unless there is no other choice (there almost always is!) +print "\nOverriding RC channels for roll and yaw" +v.channel_override = { "1" : 900, "4" : 1000 } +v.flush() +print " Current overrides are:", v.channel_override +print " Channel default values:", v.channel_readback # All channel values before override + +# Cancel override by setting channels to 0 +print " Cancelling override" +v.channel_override = { "1" : 0, "4" : 0 } +v.flush() + + +## Reset variables to sensible values. +print "\nReset vehicle attributes/parameters and exit" +v.mode = VehicleMode("STABILIZE") +v.armed = False +v.parameters['THR_MIN']=130 +v.flush() +