diff --git a/docs/examples/vehicle_state.rst b/docs/examples/vehicle_state.rst index 8c693c4fa..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. @@ -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} @@ -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 `_): - +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 f4a4ace79..41cf2dcf6 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,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 ` 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. diff --git a/droneapi/lib/__init__.py b/droneapi/lib/__init__.py index 26bd20853..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". @@ -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 `_ 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 `_ 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 `. + + + .. py:attribute:: battery Current system :py:class:`Battery` status. @@ -853,7 +902,6 @@ class CommandSequence(object): cmds = vehicle.commands cmds.clear() - vehicle.flush() lat = -34.364114, lon = 149.166022 altitude = 30.0 @@ -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 `_). - - .. todo:: The above note should be removed when https://github.com/diydrones/dronekit-python/issues/132 fixed ''' pass @@ -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 ` 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] diff --git a/droneapi/module/api.py b/droneapi/module/api.py index 0992a1e7a..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) @@ -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 = 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 e48487ee0..444b66a5f 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 @@ -26,34 +26,39 @@ 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() @@ -61,11 +66,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() @@ -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 } @@ -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