API Python, and Plotter Tab

Discussions and questions about the Crazyflie Nano Quadcopter
Post Reply
ycolmenares
Beginner
Posts: 10
Joined: Tue May 15, 2018 7:39 am

API Python, and Plotter Tab

Post by ycolmenares »

Hello all !,

I am using the crazyflie1, and I added an ultrasonic sensor, I wrote a code in C to measure the distance between the drone and the ground, then I found an API for controlling the crazyflie with python (because I don't have a controller so I want an autonomous flight). Now I try to use the plotter from the cfclient, but I can't use the API for controlling the flight and the plotter tab showing the measures taken by the sensor at the same time (I want to watch the graph while the crazyflie is flying). Is there someone with an answer for this?

Thanks in advance
arnaud
Bitcraze
Posts: 2538
Joined: Tue Feb 06, 2007 12:36 pm

Re: API Python, and Plotter Tab

Post by arnaud »

If I understand well you would like to run your own python script to control a Crazyflie while the client is connected.

There is a ZMQ interface in the client that allows to control the Crazyflie from a separate script: https://wiki.bitcraze.io/doc:crazyflie: ... put_device. This should allow you to do what you want, thought there is currently no way to get log variables with ZMQ so if your script relies on logging the distance this will be a problem.

Another way would be to make a tab in the client to run your code, it is fairly easy to make a new tab and an example tab is already included in the client code: https://github.com/bitcraze/crazyflie-c ... mpleTab.py, the tab needs to be enabled in __init__: https://github.com/bitcraze/crazyflie-c ... t__.py#L48
ycolmenares
Beginner
Posts: 10
Joined: Tue May 15, 2018 7:39 am

Re: API Python, and Plotter Tab

Post by ycolmenares »

Thanks for your reply!,
Yes, I have already tried to use the zmq interface and it doesn't work. So, you say I need to make a tab for the script :?: honestly I'm really confused I don't know what to put on the tab...I have this script to set the hover mode during an intervale of time...

Code: Select all

import time
import sys
from threading import Thread
import logging

sys.path.append("../src/cflib")
import cflib.crtp
from cflib.crazyflie import Crazyflie  #noqa

logging.basicConfig(level=logging.ERROR)

class HoverTest:
#Example that connects to a Crazyflie and sets the hover mode during "30" seconds and then disconnects.

    def __init__(self, link_uri):
        #Initialize and run the example with the specified link_uri.

        self._cf = Crazyflie()

        self._cf.connected.add_callback(self._connected)
        self._cf.disconnected.add_callback(self._disconnected)
        self._cf.connection_failed.add_callback(self._connection_failed)
        self._cf.connection_lost.add_callback(self._connection_lost)

        self._cf.open_link(link_uri)

        print("Connecting to %s" % link_uri)

    def _connected(self, link_uri):
        #This callback is called form the Crazyflie API when a Crazyflie
        #has been connected and the TOCs have been downloaded.

        # Start a separate thread to do the motor test.
        # Do not hijack the calling thread!
        Thread(target=self._hover).start()

    def _connection_failed(self, link_uri, msg):
        """Callback when connection initial connection fails (i.e no Crazyflie
        at the specified address)"""
        print("Connection to %s failed: %s" % (link_uri, msg))

    def _connection_lost(self, link_uri, msg):
        """Callback when disconnected after a connection has been made (i.e
        Crazyflie moves out of range)"""
        print("Connection to %s lost: %s" % (link_uri, msg))

    def _disconnected(self, link_uri):
#"Callback when the Crazyflie is disconnected (called in all cases)"""
        print("Disconnected from %s" % link_uri)

    
    
    def _hover(self):
        thrust = 20000
        pitch = 0.2
        roll = -2
        yawrate = 0
    
        # Unlock startup thrust protection
        self._cf.commander.send_setpoint(0, 0, 0, 0)
      
        interval = 2
        time_initial = time.time()
        while (time.time()-time_initial) <= interval:
            self._cf.commander.send_setpoint(roll, pitch, yawrate, thrust)
            self._cf.param.set_value("flightmode.althold","True")
            time.sleep(0.1)

        self._cf.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._cf.close_link()


if __name__ == '__main__':
    # Initialize the low-level drivers (don't list the debug drivers)
    cflib.crtp.init_drivers(enable_debug_driver=False)
    # Scan for Crazyflies and use the first one found
    print("Scanning interfaces for Crazyflies...")
    available = cflib.crtp.scan_interfaces()
    print(available)
    print("Crazyflies found:")
    for i in available:
        print(i[0])

    if len(available) > 0:
        le = HoverTest(available[0][0])
    else:
        print("No Crazyflies found, cannot run test") 
So, do I need to make a new tab to enter the thrust value and the time intervale?
Thanks again for your time :D .
arnaud
Bitcraze
Posts: 2538
Joined: Tue Feb 06, 2007 12:36 pm

Re: API Python, and Plotter Tab

Post by arnaud »

This code should run fine with zmq, what was your problem? The alt-hold function is activated with the alt1 control if I am not mistaken.

To write a tab the best is to start from the example tab: : https://github.com/bitcraze/crazyflie-c ... mpleTab.py

There is an old video tutorial that shows how to add a tab in the client, it is outdated for the details (ie. files have moved), but it should give you an idea of the procedure: https://www.youtube.com/watch?v=cutgIMfHwyQ.

The tab code has a callback for when the Crazyflie is connected, from there you can run any code you want, start a thread and send setpoint with the provided crazyflie object. Since you want to send setpoint you will need this function to disable gamepad from controlling the Crazylfie: https://github.com/bitcraze/crazyflie-c ... issues/334

Unfortunatly there is no example that implements all that but these info should be enough to get you started.
ycolmenares
Beginner
Posts: 10
Joined: Tue May 15, 2018 7:39 am

Re: API Python, and Plotter Tab

Post by ycolmenares »

Hello Arnaud, thanks again for your reply
I have made a new tab (Altitude Control), and I want to send thrust values through the cfclient, but I don't know how to get commands from the cfclient.
Image

So, I added theses lines on my AltitudeControlTab.py

Code: Select all

    def __init__(self, tabWidget, helper, *args):
        super(CtrlAltTab, self).__init__(*args)
        self.setupUi(self)       
       
        self.targetThrust.valueChanged.connect(self._thrust_changed)   
        self.targetThrust.setValue(HoverTest()._hover("thrust")) 
and this definition

Code: Select all

    def _thrust_changed(self,value):           
       
        logger.debug("Thrust updated to [%f]" % value)
        HoverTest()._hover("thrust", value) 
But it doesn't work, I get this error

Code: Select all

self.targetThrust.setValue(HoverTest()._hover("thrust"))
TypeError: __init__() takes exactly 2 arguments (1 given)
I hope I have made myself clear and you can give me a hand
Have a good day
Post Reply