Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/examples/vehicle_state.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <disable-arming-checks>` so
that the example can run.

Expand All @@ -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: [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}
Expand Down Expand Up @@ -118,8 +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 <https://github.com/diydrones/dronekit-python/blob/master/examples/vehicle_state/vehicle_state.py>`_):
The full source code at documentation build-time is listed below (`current version on github <https://github.com/diydrones/dronekit-python/blob/master/examples/simple_goto/simple_goto.py>`_):
.. literalinclude:: ../../examples/vehicle_state/vehicle_state.py
:language: python

23 changes: 17 additions & 6 deletions docs/guide/vehicle_state_and_parameters.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ Vehicle state information is exposed through vehicle *attributes*. DroneKit-Pyth
:py:attr:`Vehicle.gps_0 <droneapi.lib.Vehicle.gps_0>`,
:py:attr:`Vehicle.armed <droneapi.lib.Vehicle.location>`,
:py:attr:`Vehicle.location <droneapi.lib.Vehicle.armed>`,
:py:attr:`Vehicle.mount_status <droneapi.lib.Vehicle.mount_status>`.
:py:attr:`Vehicle.mount_status <droneapi.lib.Vehicle.mount_status>`,
:py:attr:`Vehicle.battery <droneapi.lib.Vehicle.battery>`,
:py:attr:`Vehicle.system_status <droneapi.lib.Vehicle.system_status>`.

All of the attributes can be :ref:`read <vehicle_state_read_attributes>` and :ref:`observed <vehicle_state_observe_attributes>`,
but only the :py:attr:`Vehicle.mode <droneapi.lib.Vehicle.mode>` and :py:attr:`Vehicle.armed <droneapi.lib.Vehicle.armed>`
Expand All @@ -53,17 +55,26 @@ 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 <droneapi.lib.Vehicle.gps_0>` would return a :py:class:`GPSInfo <droneapi.lib.GPSInfo>`
with ``None`` values for ``eph``, ``satellites_visible`` etc.)


The :py:attr:`Vehicle.system_status <droneapi.lib.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.


Expand Down
116 changes: 93 additions & 23 deletions droneapi/lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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".
Expand Down Expand Up @@ -476,6 +461,70 @@ 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 <https://pixhawk.ethz.ch/mavlink/#HEARTBEAT>`_ message.

This attribute provides high-level information about whether the vehicle is on the ground, flying, in failsafe, etc. For example,
to check if the vehicle is in a critical state:

.. code:: python

from pymavlink import mavutil
...

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 <https://pixhawk.ethz.ch/mavlink/>`_ 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.


.. note::

This attribute is of type :py:class:`SystemStatus <droneapi.lib.SystemStatus>`.



.. py:attribute:: battery

Current system :py:class:`Battery` status.
Expand Down Expand Up @@ -853,7 +902,6 @@ class CommandSequence(object):

cmds = vehicle.commands
cmds.clear()
vehicle.flush()
lat = -34.364114,
lon = 149.166022
altitude = 30.0
Expand Down Expand Up @@ -922,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 <https://github.com/diydrones/dronekit-python/issues/132>`_).

.. todo:: The above note should be removed when https://github.com/diydrones/dronekit-python/issues/132 fixed
'''
pass

Expand Down Expand Up @@ -966,3 +1007,32 @@ def next(self, value):
.. INTERNAL NOTE: (implementation provided by subclass)
"""
pass

class SystemStatus(object):
"""
A convenience class (transparently) used by :py:func:`Vehicle.system_status <droneapi.lib.Vehicle.system_status>` for working with ``MAV_STATE`` messages.

The class provides a human readable string for the system state when ``Vehicle.system_status`` is printed, and an enum value otherwise (for comparison).

:param int mav_state: The current system ``MAV_STATE`` enum.

"""
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]
8 changes: 7 additions & 1 deletion droneapi/module/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -355,6 +359,7 @@ def __init__(self, mpstate):
"<control> (USERNAME) (PASSWORD) (VEHICLEID)", "<disconnect>" ])
self.api = MPAPIConnection(self)
self.vehicle = self.api.get_vehicles()[0]
self.system_status = None
self.lat = None
self.lon = None
self.alt = None
Expand Down Expand Up @@ -461,6 +466,7 @@ def mavlink_packet(self, m):
self.level = m.battery_remaining
self.__on_change('battery')
elif typ == "HEARTBEAT":
self.system_status = SystemStatus(m.system_status)
self.__on_change('mode', 'armed')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't 'system_status' be added to the self._on_change()?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you are right, let me ponder on this for a bit.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think its only use is to have the ability to add an attribute_observer. I think you should add it to keep consistent with the other attributes.

elif typ in ["WAYPOINT_CURRENT", "MISSION_CURRENT"]:
self.last_waypoint = m.seq
Expand Down
33 changes: 19 additions & 14 deletions examples/vehicle_state/vehicle_state.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -26,46 +26,51 @@
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
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()

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)
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()
Expand All @@ -81,7 +86,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 }
Expand All @@ -96,7 +101,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
Expand Down