diff --git a/docs/examples/create_attribute.rst b/docs/examples/create_attribute.rst new file mode 100644 index 000000000..283b20593 --- /dev/null +++ b/docs/examples/create_attribute.rst @@ -0,0 +1,212 @@ +.. _example_create_attribute: + +================================ +Example: Create Attribute in App +================================ + +This example shows how you can create attributes for MAVLink messages within your DroneKit-Python script and +use them in *in the same way* as the built-in :py:class:`Vehicle ` attributes. + +Additional information is provided in the guide topic :ref:`mavlink_messages`. + +.. tip:: + + This approach is useful when you urgently need to access messages that are not yet supported as + :py:class:`Vehicle ` attributes. + + Please :ref:`contribute your code to the API ` so that it is available to + (and can be tested by) the whole DroneKit-Python community. + + + +Running the example +=================== + +The vehicle and DroneKit should be set up as described in :ref:`get-started`. It can be run as described in +:doc:`running_examples`. + +In summary, after cloning the repository: + +#. Navigate to the example folder as shown: + + .. code-block:: bash + + cd dronekit-python\examples\create_attribute\ + + +#. Start the example, passing the :ref:`connection string ` you wish to use in the ``--connect`` parameter: + + .. code-block:: bash + + python create_attribute.py --connect 127.0.0.1:14550 + + .. note:: + + The examples uses the ``--connect`` parameter to pass the :ref:`connection string ` into the script. + The command above would be used to connect to :ref:`SITL ` running on the local machine via UDP port 14550. + + + +On the command prompt you should see (something like): + +.. code:: bash + + RAW_IMU: time_boot_us=41270000,xacc=0,yacc=0,zacc=-999,xgyro=1,ygyro=1,zgyro=1,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=41510000,xacc=0,yacc=0,zacc=-1000,xgyro=1,ygyro=0,zgyro=1,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=41750000,xacc=1,yacc=0,zacc=-1000,xgyro=1,ygyro=1,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=41990000,xacc=0,yacc=0,zacc=-999,xgyro=0,ygyro=0,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=42230000,xacc=0,yacc=0,zacc=-1000,xgyro=0,ygyro=0,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=42470000,xacc=0,yacc=0,zacc=-999,xgyro=1,ygyro=0,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=42710000,xacc=0,yacc=0,zacc=-999,xgyro=0,ygyro=0,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=42950000,xacc=0,yacc=0,zacc=-1000,xgyro=1,ygyro=1,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=43190000,xacc=0,yacc=0,zacc=-999,xgyro=1,ygyro=1,zgyro=1,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=43430000,xacc=0,yacc=0,zacc=-999,xgyro=0,ygyro=0,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=43670000,xacc=0,yacc=0,zacc=-999,xgyro=1,ygyro=0,zgyro=1,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=43910000,xacc=0,yacc=0,zacc=-999,xgyro=1,ygyro=0,zgyro=1,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=44150000,xacc=0,yacc=0,zacc=-999,xgyro=1,ygyro=1,zgyro=0,xmag=153,ymag=52,zmag=-364 + RAW_IMU: time_boot_us=44390000,xacc=0,yacc=0,zacc=-999,xgyro=1,ygyro=1,zgyro=0,xmag=153,ymag=52,zmag=-364 + APIThread-0 exiting... + + + +How does it work? +================= + +The example first defines a class for the attribute. This has members for each of the values in the message +(in this case `RAW_IMU `_). It provides an initialiser and a string +representation for printing the object. + +.. code:: python + + class RawIMU(object): + """ + The RAW IMU readings for the usual 9DOF sensor setup. + This contains the true raw values without any scaling to allow data capture and system debugging. + + The message definition is here: http://mavlink.org/messages/common#RAW_IMU + + :param time_boot_us: Timestamp (microseconds since system boot). #Note, not milliseconds as per spec + :param xacc: X acceleration (mg) + :param yacc: Y acceleration (mg) + :param zacc: Z acceleration (mg) + :param xgyro: Angular speed around X axis (millirad /sec) + :param ygyro: Angular speed around Y axis (millirad /sec) + :param zgyro: Angular speed around Z axis (millirad /sec) + :param xmag: X Magnetic field (milli tesla) + :param ymag: Y Magnetic field (milli tesla) + :param zmag: Z Magnetic field (milli tesla) + """ + + def __init__(self, time_boot_us, xacc, yacc, zacc, xygro, ygyro, zgyro, xmag, ymag, zmag): + """ + RawIMU object constructor. + """ + self.time_boot_us = time_boot_us + self.xacc = xacc + self.yacc = yacc + self.zacc = zacc + self.xgyro = zgyro + self.ygyro = ygyro + self.zgyro = zgyro + self.xmag = xmag + self.ymag = ymag + self.zmag = zmag + + def __str__(self): + """ + String representation of the RawIMU object + """ + return "RAW_IMU: time_boot_us={},xacc={},yacc={},zacc={},xgyro={},ygyro={},zgyro={},xmag={},ymag={},zmag={}".format(self.time_boot_us, self.xacc, self.yacc,self.zacc,self.xgyro,self.ygyro,self.zgyro,self.xmag,self.ymag,self.zmag) + +The script should then create an instance of the class and add it as an attribute to the vehicle object retrieved from the local connection. +All values in the new attribute should be set to ``None`` so that it is obvious to users when no messages have been received. + +.. code:: python + + # Get an instance of the API endpoint + api = local_connect() + # Get the connected vehicle (currently only one vehicle can be returned). + vehicle = api.get_vehicles()[0] + + #Create an Vehicle.raw_imu object and set all values to None. + vehicle.raw_imu=RawIMU(None,None,None,None,None,None,None,None,None,None) + +We can set a callback to intercept MAVLink messages using :py:func:`Vehicle.set_mavlink_callback() ` +as shown below. + +.. code:: python + + def mavrx_debug_handler(message): + """ + Handler for MAVLink messages. + """ + #Handle raw_imu messages + mav_raw_imu_handler(message) + + # Set MAVLink callback handler (after getting Vehicle instance) + vehicle.set_mavlink_callback(mavrx_debug_handler) + +For clarity we have separated the handling code for the RAW_IMU message into ``mav_raw_imu_handler()``. The handler simply checks the message type and +(for the correct messages) writes the values into the attribute. It then calls ``vehicle.notify_observers('raw_imu')`` to notify all observers of this attribute type. + +.. code:: python + + def mav_raw_imu_handler(message): + """ + Writes received message to the (newly attached) vehicle.raw_imu object and notifies observers. + """ + messagetype=str(message).split('{')[0].strip() + if messagetype=='RAW_IMU': + vehicle.raw_imu.time_boot_us=message.time_usec + vehicle.raw_imu.xacc=message.xacc + vehicle.raw_imu.yacc=message.yacc + vehicle.raw_imu.zacc=message.zacc + vehicle.raw_imu.xgyro=message.xgyro + vehicle.raw_imu.ygyro=message.ygyro + vehicle.raw_imu.zgyro=message.zgyro + vehicle.raw_imu.xmag=message.xmag + vehicle.raw_imu.ymag=message.ymag + vehicle.raw_imu.zmag=message.zmag + + #Add Notify all observers of new message. + vehicle.notify_observers('raw_imu') + + +At this point the ``Vehicle.raw_imu`` attribute can be treated the same as any other attribute for the duration of the session. +You can query the attribute to get any of the values, and even add an observer as shown: + + +.. code:: python + + #Callback to print the raw_imu + def raw_imu_callback(rawimu): + print vehicle.raw_imu + + + #Add observer for the vehicle's current location + vehicle.add_attribute_observer('raw_imu', raw_imu_callback) + + +.. note:: + + It is not possible to reliably use this approach to create independent modules because: + + * Only one MAVLink callback can be set at a time in the running program (``set_mavlink_callback()``) + * There is no reliable way to import modules without adding them properly to the Python environment. + + + +Known issues +============ + +This code has no known issues. + + +Source code +=========== + +The full source code at documentation build-time is listed below (`current version on github `_): + +.. literalinclude:: ../../examples/create_attribute/create_attribute.py + :language: python + diff --git a/docs/examples/index.rst b/docs/examples/index.rst index 65b983659..55504b717 100644 --- a/docs/examples/index.rst +++ b/docs/examples/index.rst @@ -18,6 +18,7 @@ during missions and outside missions using custom commands. Guided Movement and Commands Basic Mission Mission Import/Export + Create Attribute in App Follow Me (Linux only) Drone Delivery Flight Replay diff --git a/docs/guide/index.rst b/docs/guide/index.rst index 612d296a7..d63671773 100644 --- a/docs/guide/index.rst +++ b/docs/guide/index.rst @@ -17,3 +17,4 @@ The guide contains how-to documentation for using the DroneKit-Python API. These copter/guided_mode Missions debugging + mavlink_messages \ No newline at end of file diff --git a/docs/guide/mavlink_messages.rst b/docs/guide/mavlink_messages.rst new file mode 100644 index 000000000..ea614d154 --- /dev/null +++ b/docs/guide/mavlink_messages.rst @@ -0,0 +1,86 @@ +.. _mavlink_messages: + +================ +MAVLink Messages +================ + +Some useful MAVLink messages sent by the autopilot are not (yet) directly available to DroneKit-Python scripts +through the :ref:`observable attributes ` in :py:class:`Vehicle `. + +This topic shows how you can intercept MAVLink messages using +:py:func:`Vehicle.set_mavlink_callback() `. + +.. tip:: + + :ref:`example_create_attribute` shows how you can extend this approach to create a new :py:class:`Vehicle ` + attribute in your client code. + + + +.. _mavlink_messages_set_mavlink_callback: + +Creating the message observer +============================= + +The :py:func:`Vehicle.set_mavlink_callback() ` method provides asynchronous +notification when any *MAVLink* packet is received from the connected vehicle. + +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 type(message) + print message + + + # Set MAVLink callback handler (after getting Vehicle instance) + vehicle.set_mavlink_callback(mavrx_debug_handler) + +.. note:: + + DroneKit-Python only supports a single MAVLink message observer at a time. This can be removed or replaced + with a different observer. + +The messages are `classes `_ from the `pymavlink `_ library. +The output of the code above looks something like: + +.. code:: bash + + + RANGEFINDER {distance : 0.0899999961257, voltage : 0.00900000054389} + + TERRAIN_REPORT {lat : -353632610, lon : 1491652299, spacing : 100, terrain_height : 583.88470459, current_height : 0.0, pending : 0, loaded : 504} + + EKF_STATUS_REPORT {flags : 933, velocity_variance : 0.0, pos_horiz_variance : 0.0, pos_vert_variance : 0.000532002304681, compass_variance : 0.00632426189259, terrain_alt_variance : 0.0} + + VIBRATION {time_usec : 88430000, vibration_x : 0.0, vibration_y : 0.0, vibration_z : 0.0, clipping_0 : 0, clipping_1 : 0, clipping_2 : 0} + ... + +You can access the message fields directly. For example, to access the ``RANGEFINDER`` message your handler might look like this: + +.. code:: python + + # Handler for message: RANGEFINDER {distance : 0.0899999961257, voltage : 0.00900000054389} + def mavrx_debug_handler(message): + messagetype=str(message).split('{')[0].strip() + if messagetype=='RANGEFINDER': + print 'distance: %s' % message.distance + print 'voltage: %s' % message.voltage + + + + + + +Clearing the observer +===================== + +The observer is unset by calling :py:func:`Vehicle.unset_mavlink_callback `. + +The observer will also be removed when the thread exits. + + + + \ No newline at end of file diff --git a/examples/create_attribute/create_attribute.py b/examples/create_attribute/create_attribute.py new file mode 100644 index 000000000..360396ced --- /dev/null +++ b/examples/create_attribute/create_attribute.py @@ -0,0 +1,126 @@ +""" +create_attribute.py: + +Demonstrates how to create attributes for MAVLink messages within your DroneKit-Python script +and use them in the same way as the built-in Vehicle attributes. + +The code adds a new attribute to the Vehicle class, populating it with information from RAW_IMU messages +intercepted using set_mavlink_callback. + +Full documentation is provided at http://python.dronekit.io/examples/create_attribute.html +""" + +from dronekit import connect +from dronekit.lib import VehicleMode +from pymavlink import mavutil +import time + + +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Print out vehicle state information. Connects to SITL on local PC by default.') +parser.add_argument('--connect', default='127.0.0.1:14550', + help="vehicle connection target. Default '127.0.0.1:14550'") +args = parser.parse_args() + + +# Connect to the Vehicle +print 'Connecting to vehicle on: %s' % args.connect +vehicle = connect(args.connect, await_params=True) + + + +class RawIMU(object): + """ + The RAW IMU readings for the usual 9DOF sensor setup. + This contains the true raw values without any scaling to allow data capture and system debugging. + + The message definition is here: https://pixhawk.ethz.ch/mavlink/#RAW_IMU + + :param time_boot_us: Timestamp (microseconds since system boot). #Note, not milliseconds as per spec + :param xacc: X acceleration (mg) + :param yacc: Y acceleration (mg) + :param zacc: Z acceleration (mg) + :param xgyro: Angular speed around X axis (millirad /sec) + :param ygyro: Angular speed around Y axis (millirad /sec) + :param zgyro: Angular speed around Z axis (millirad /sec) + :param xmag: X Magnetic field (milli tesla) + :param ymag: Y Magnetic field (milli tesla) + :param zmag: Z Magnetic field (milli tesla) + """ + def __init__(self, time_boot_us, xacc, yacc, zacc, xygro, ygyro, zgyro, xmag, ymag, zmag): + """ + RawIMU object constructor. + """ + self.time_boot_us = time_boot_us + self.xacc = xacc + self.yacc = yacc + self.zacc = zacc + self.xgyro = zgyro + self.ygyro = ygyro + self.zgyro = zgyro + self.xmag = xmag + self.ymag = ymag + self.zmag = zmag + + def __str__(self): + """ + String representation used to print the RawIMU object. + """ + return "RAW_IMU: time_boot_us={},xacc={},yacc={},zacc={},xgyro={},ygyro={},zgyro={},xmag={},ymag={},zmag={}".format(self.time_boot_us, self.xacc, self.yacc,self.zacc,self.xgyro,self.ygyro,self.zgyro,self.xmag,self.ymag,self.zmag) + + + +#Create an Vehicle.raw_imu object and set all values to None. +vehicle.raw_imu=RawIMU(None,None,None,None,None,None,None,None,None,None) + + +def mav_raw_imu_handler(message): + """ + Writes received message to the (newly attached) vehicle.raw_imu object and notifies observers. + """ + messagetype=str(message).split('{')[0].strip() + if messagetype=='RAW_IMU': + vehicle.raw_imu.time_boot_us=message.time_usec + vehicle.raw_imu.xacc=message.xacc + vehicle.raw_imu.yacc=message.yacc + vehicle.raw_imu.zacc=message.zacc + vehicle.raw_imu.xgyro=message.xgyro + vehicle.raw_imu.ygyro=message.ygyro + vehicle.raw_imu.zgyro=message.zgyro + vehicle.raw_imu.xmag=message.xmag + vehicle.raw_imu.ymag=message.ymag + vehicle.raw_imu.zmag=message.zmag + + #Add Notify all observers of new message. + vehicle.notify_observers('raw_imu') + + +def mavrx_debug_handler(message): + """ + Handler for MAVLink messages. + """ + #Handle raw_imu messages + mav_raw_imu_handler(message) + +# Set MAVLink callback handler (after getting Vehicle instance) +vehicle.set_mavlink_callback(mavrx_debug_handler) + +""" +From this point vehicle.raw_imu can be used just like any other attribute. +""" + +#Callback to print the raw_imu +def raw_imu_callback(rawimu): + print vehicle.raw_imu + + +#Add observer for the vehicle's current location +vehicle.add_attribute_observer('raw_imu', raw_imu_callback) + +print 'Display RAW_IMU messages for 5 seconds and then exit.' +time.sleep(5) + +#The observer can be unset using ``vehicle.unset_mavlink_callback()`` OR +# ``vehicle.set_mavlink_callback(None)``. +#It is automatically removed when the thread exits.