User Tools

Site Tools


projects:crazyflie:pc_utils:pylib

This is an old revision of the document!


The Crazyflie Python API

In order to easily use and control the Crazyflie there's an library made in Python that gives high-level functions and hides the details. This page contains generic information about how to use this library and the API that it implements.

If you are interested in more details look in the PyDoc in the code or:

Structure of the library

The library is asynchronous and based on callbacks for events. Functions like open_link will return immediately, and the callback connected will be called when the link is opened. The library doesn't contain any threads or locks that will keep the application running, it's up to the application that is using the library to do this.

Uniform Resource Identifier (URI)

All communication links are identified using an URI build up of the following: InterfaceType://InterfaceId/InterfaceChannel/InterfaceSpeed

Currently only radio and debug interfaces are used but there's ideas for more like udp, serial, usb, etc…Here are some examples:

  • Radio interface, USB dongle number 0, radio channel 10 and radio speed 250 Kbit/s: radio://0/10/250K
  • Debug interface, id 0, channel 1: debug://0/1

Variables and logging

The library supports setting up logging configurations that are used for logging variables from the firmware. Each log configuration contains a number of variables that should be logged as well as a time period (in ms) of how often the data should be sent back to the host. Once the log configuration is added to the firmware the firmware will automatically send back the data at every period. These configurations are used in the following way:

  • Connect to the Crazyflie (log configurations needs a TOC to work)
  • Create a log configuration that contains a number of variables to log and a period at which they should be logged
  • Add the log configuration. This will also validate that the log configuration is sane (i.e uses a supported period and all variables are in the TOC)
  • After checking that the configuration is valid, set up callbacks for the data in your application and start the log configuration
  • Each time the firmware sends data back to the host the callback will the called with a time-stamp and the data

There's a few limitations that needs to be taken into account:

  • Each packet is limited to 32bytes, which means that the data that is logged and the packet that is sent to set it up cannot be larger than this. It limits the logging to about 14 variables, but this is dependent on what types they are
  • The minimum period of a for a log configuration is multiples of 10ms

Parameters

The library supports reading and writing parameters at run-time to the firmware. This is intended to be used for data that is not continuously being changed by the firmware, like setting regulation parameters and reading out if the power-on self-tests passed. Parameters should only change in the firmware when being set from the host or during start-up. The library doesn't continuously update the parameter values, this should only be done once after connecting. After each write to a parameter the firmware will send back the updated value and this will be forwarded to callbacks registered for reading this parameter. The parameters should be used in the following way:

  • Register parameter updated callbacks at any time in your application
  • Connect to your Crazyflie (this will download the parameter TOC)
  • Request updates for all the parameters
  • The library will call all the callbacks registered
  • The host can now write parameters that will be forwarded to the firmware
  • For each write all the callbacks registered for this parameter will be called back

Variable and parameter names

All names of parameters and log variables use the same structure: group.name

The group should be used to bundle together logical groups, like everything that has to do with the stabilizer should be in the group stabilizer.

There's a limit of 28 chars in total and here are some examples:

  • stabilizer.roll
  • stabilizer.pitch
  • pm.vbat
  • imu_tests.MPU6050
  • pid_attitide.pitch_kd

Utilities

Callbacks

All callbacks are handled using the Caller class that contains the following methods:

    def add_callback(cb)
        """ Register cb as a new callback. Will not register duplicates. """
 
    def remove_callback(cb):
        """ Un-register cb from the callbacks """
 
    def call(*args):
        """ Call the callbacks registered with the arguments args """

Debug driver

The library contains a special link driver, named DebugDriver. This driver will emulate a Crazyflie and is used for testing of the UI and library. Normally this will be hidden from the user except if explicitly enabled. The driver supports the following:

  • Connecting a download param and log TOCs
  • Setting up log configurations and sending back fake data
  • Setting and reading parameters
  • Bootloading

There are a number of different URIs that will be returned from the driver. These will have different functions, like always returning a random TOC CRC to always trigger TOC downloading or failing during connect. The driver also has support for sending back data with random delays to trigger random re-sending by the library.

Before the library can be used the link drivers have to he initialized. This will search for available drivers and instantiate them.

    def init_drivers(enable_debug_driver=False)
       """ Search for and initialize link drivers. If enable_debug_driver is True then the DebugDriver will also be used."""

Operations on the link and connection will return directly and will call the following callbacks when events occur:

    # Called on disconnect, no matter the reason
    disconnected = Caller()
    # Called on unintentional disconnect only
    connection_lost = Caller()
    # Called when the first packet in a new link is received
    link_established = Caller()
    # Called when the user requests a connection
    connection_requested = Caller()
    # Called when the link is established and the TOCs (that are not cached)
    # have been downloaded
    connected = Caller()
    # Called if establishing of the link fails (i.e times out)
    connection_failed = Caller()
    # Called for every packet received
    packet_received = Caller()
    # Called for every packet sent
    packet_sent = Caller()
    # Called when the link driver updates the link quality measurement
    link_quality_updated = Caller()

To register for callbacks the following is used:

    crazyflie = Crazyflie()
    crazyflie.connected.add_callback(crazyflie_connected)

Finding a Crazyflie and connecting

The first thing to do is to find a Crazyflie quadcopter that we can connect to. This is done by queuing the library that will scan all the available interfaces (currently the debug and radio interface).

    cflib.crtp.init_drivers()
    available = cflib.crtp.scan_interfaces()
    for i in available:
        print "Interface with URI [%s] found and name/comment [%s]" % (i[0], i[1])

Opening and closing a communication link is doing by using the Crazyflie object:

    crazyflie = Crazyflie()
    crazyflie.open_link("radio://0/10/250K")
    # Do stuff
    crazyflie.close_link()

Sending control commands

Currently all the communication is either parameters, logging or control commands. The special case of control commands is to minimize latency since it's a faster way than using parameters.

To send a new control set-point use the following:

    roll    = 0.0
    pitch   = 0.0
    yawrate = 0
    thrust  = 0
    crazyflie.commander.send_setpoint(roll, pitch, yawrate, thrust)

Thrust is an integer value ranging from 10001 (next to no power) to 60000 (full power). Sending a command makes it apply for 0.5 seconds, after which the firmware will cut out the power. Depending on where the Crazyflie is, this can be a Bad Thing! With this in mind, you need to try and maintain a thrust level, with a tick being sent at least once every 2 seconds. Ideally you should be sending one tick every 0.01 seconds, for 100 commands a second. This has a nice added benefit of allowing for very precise control.

Parameters

The parameter framework is used to read and set parameters. This functionality should be used when:

  • The parameter is not changed by the Crazyflie but by the client
  • The parameter is not read periodically

If this is not the case then the logging framework should be used instead.

To set a parameter you have to the connected to the Crazyflie. A parameter is set using:

    param_name = "group.name"
    param_value = 3
    crazyflie.param.set_value(param_name, param_value)

The parameter reading is done using callbacks. When the connection is established to the Crazyflie all the parameters are read. When a parameter is updated from the client (using the code above) the parameter will be requested again by the library and this will trigger the callbacks. Parameter callbacks can be added at any time (you don't have to be connected to a Crazyflie).

    crazyflie.param.add_update_callback(group="group", name="name", param_updated_callback)
 
    def param_updated_callback(name, value):
        print "%s has value %d" % (name, value)

Logging

The logging framework is used to enable the “automatic” sending of variable values at specified intervals to the client. This functionality should be used when:

  • The variable is changed by the Crazyflie and not by the client
  • The variable is updated at high rate and you want to read the value periodically

If this is not the case then the parameter framework should be used instead.

To create a logging configuration the following can be used:

    logconf = LogConfig(name="Logging", period_in_ms=100)
    logconf.add_variable("group1.name1", "float")
    logconf.add_variable("group1.name2", "uint8_t")
    logconf.add_variable("group2.name1", "int16_t")

The datatype should match what has been configured in the Crazyflie firmware. The valid datatypes are:

  • float
  • uint8_t and int8_t
  • uint16_t and int16_t
  • uint32_t and int32_t
  • FP16 (this is a fixed point version of floating point)

The logging cannot be started until your are connected to a Crazyflie:

    # Callback called when the connection is established to the Crazyflie
    def connected(link_uri):
        crazyflie.log.add_coonfig(logconf)
 
        if logconf.valid:
            logconf.data_received_cb.add_callback(data_received_callback)
            logconf.error_cb.add_callback(logging_error)
            logconf.start()
        else:
            print "One or more of the variables in the configuration was not found in log TOC. No logging will be possible."
 
    def data_received_callback(timestamp, data, logconf):
        print "[%d][%s]: %s" % (timestamp, logconf.name, data)
 
    def logging_error(logconf, msg)

Logging and parameter examples

Below are the two examples described in the video <insert link to video here when done> that shows the parameter and logging framework. They have been re-written to fit outside the QT context so they do not match the video 1:1 but they show the same concept.

Remember that if you use the callbacks for parameters and logging together with QT and the callbacks manipulate objects in the UI then they have to be wrapped using signals. Otherwise you will en up with timing issues that will (at some point) crash the application since UI objects should only be updated with the same thread that draws the objects.

Adding a parameter

In this example we will add a parameter that will be used to “freeze” the LED update function. This isn't very useful but it shows how to use parameters :-)

First of all we need to add the parameter to the firmware, this is done by using the macros PARAM_GROUP_START, PARAM_ADD and PARAM_GROUP_STOP. In crazyflie-firmware/drivers/src/led.c we insert the following to add a parameter:

#include "param.h"
 
bool ledFreeze = false;
 
PARAM_GROUP_START(led)
PARAM_ADD(PARAM_UINT8, freeze, &ledFreeze)
PARAM_GROUP_STOP(led)

This will add a parameter in the TOC named led.freeze of the type uint8_t.

Now we should use this parameter on the client side. This can either be done by reading or writing the parameter. First we add the code to write the parameter:

# crazyflie is an instance of the Crazyflie class that has been instantiated and connected
    crazyflie.param.setParamValue("led.freeze", True)

The parameter-framework relies on the fact that the parameters are changed from the client or that the client polls the value of parameters. If you are interested in logging changes that the Crazyflie does itself then the logging-framework is better. If you are interested in reading a parameter this should be done using a callback that will be called from the framework when the value for the parameter is updated. This happens in two cases:

  • When the Crazyflie has connected values for all the parameters in the TOC are fetched
  • When the client changes a value for a parameter the new value will be sent back from the Crazyflie

To register for a callback and to implement the callback the following is used:

    crazyflie = Crazyflie()
    crazyflie.param.addParamUpdateCallback("led.freeze", paramUpdateCallback)
 
    def paramUpdateCallback(name, value):
        print "%s has value %s" % (name, value) # This will in our example print: led.freeze has value True

Adding loggable variables

In this example we will add logging for the raw gyro values read from the sensor.

First of all we add the variables to the logging TOC by using the macros LOG_GROUP_START, LOG_ADD and LOG_GROUP_STOP. In our example we edit the file crazyflie-firmware/modules/src/stabalizer.c:

#include "log.h"
// The raw gyro values are stored in the gyro struct
LOG_GROUP_START(gyro)
LOG_ADD(LOG_FLOAT, x, &gyro.x)
LOG_ADD(LOG_FLOAT, y, &gyro.y)
LOG_ADD(LOG_FLOAT, z, &gyro.z)
LOG_GROUP_STOP(gyro)

This will add the variables gyro.x, gyro.y and gyro.z to the logging TOC as floats.

On the client side we now add the log configuration, start the logging and then a callback will be called every 10 ms when data arrives from the Crazyflie:

    # Callback called when the connection is established to the Crazyflie
    def connected(linkURI):
        gyroconf = LogConfig("Gyro", 10)
        gyroconf.addVariable(LogVariable("gyro.x", "float"))
        gyroconf.addVariable(LogVariable("gyro.y", "float"))
        gyroconf.addVariable(LogVariable("gyro.z", "float"))
 
        # crazyflie is an instance of the Crazyflie class that has been instantiated and connected
        gyrolog = crazyflie.log.newLogPacket(gyroconf)
 
        if (gyrolog != None):
            gyrolog.data_received.addCallback(gyroData)
            gyrolog.startLogging()
        else:
            print "gyro.x/y/z not found in log TOC"
 
    def gyroData(data):
        print "Gyrodata: x=%.2f, y=%.2f, z=%.2f" % (data["gyro.x"], data["gyro.y"], data["gyro.z"])

Code example to add accelerometer logging

This example requires Crazyflie firmware newer then this commit where the accelerometer variables has been exposed by the firmware. (It is not included in the 2013.4 release)

import logging
 
import cflib.crtp
from cfclient.utils.logconfigreader import LogConfig
from cfclient.utils.logconfigreader import LogVariable
from cflib.crazyflie import Crazyflie
 
logging.basicConfig(level=logging.DEBUG)
 
 
class Main:
    """
    Class is required so that methods can access the object fields.
    """
    def __init__(self):
        """
        Connect to Crazyflie, initialize drivers and set up callback.
 
        The callback takes care of logging the accelerometer values.
        """
        self.crazyflie = Crazyflie()
        cflib.crtp.init_drivers()
 
        self.crazyflie.connectSetupFinished.add_callback(
                                                    self.connectSetupFinished)
 
        self.crazyflie.open_link("radio://0/10/250K")
 
    def connectSetupFinished(self, linkURI):
        """
        Configure the logger to log accelerometer values and start recording.
 
        The logging variables are added one after another to the logging
        configuration. Then the configuration is used to create a log packet
        which is cached on the Crazyflie. If the log packet is None, the
        program exits. Otherwise the logging packet receives a callback when
        it receives data, which prints the data from the logging packet's
        data dictionary as logging info.
        """
        # Set accelerometer logging config
        accel_log_conf = LogConfig("Accel", 10)
        accel_log_conf.addVariable(LogVariable("acc.x", "float"))
        accel_log_conf.addVariable(LogVariable("acc.y", "float"))
        accel_log_conf.addVariable(LogVariable("acc.z", "float"))
 
        # Now that the connection is established, start logging
        self.accel_log = self.crazyflie.log.create_log_packet(accel_log_conf)
 
        if self.accel_log is not None:
            self.accel_log.data_received.add_callback(self.log_accel_data)
            self.accel_log.start()
        else:
            print("acc.x/y/z not found in log TOC")
 
    def log_accel_data(self, data):
        logging.info("Accelerometer: x=%.2f, y=%.2f, z=%.2f" %
                        (data["acc.x"], data["acc.y"], data["acc.z"]))
 
Main()

Simple code example

As a starter guide, this application connects to the Crazyflie, turns on the motors, ramps up/down the rpm and then quits.

import time, sys
from threading import Thread
 
sys.path.append("lib")
import cflib
from cflib.crazyflie import Crazyflie
 
class Main:
    def __init__(self):
        self.crazyflie = Crazyflie()
        cflib.crtp.init_drivers()
 
        # You may need to update this value if your Crazyradio uses a different frequency.
        self.crazyflie.open_link("radio://0/10/250K")
        # Set up the callback when connected
        self.crazyflie.connectSetupFinished.add_callback(self.connectSetupFinished)
 
    def connectSetupFinished(self, linkURI):
        # Start a separate thread to do the motor test.
        # Do not hijack the calling thread!
        Thread(target=self.pulse_command).start()
 
    def pulse_command(self):
        thrust_mult = 1
        thrust_step = 500
	thrust = 20000
        pitch = 0
        roll = 0
        yawrate = 0
        while thrust >= 20000:
	    self.crazyflie.commander.send_setpoint(roll, pitch, yawrate, thrust)
            time.sleep(0.1)
            if (thrust >= 25000):
                thrust_mult = -1
            thrust = thrust + (thrust_step * thrust_mult)
        self.crazyflie.commander.send_setpoint(0,0,0,0)
        # Make sure that the last packet leaves before the link is closed
        # since the message queue is not flushed before closing
	time.sleep(0.1)
        self.crazyflie.close_link()
 
Main()
projects/crazyflie/pc_utils/pylib.1391502775.txt.gz · Last modified: 2015-07-15 16:30 (external edit)