Urgent: Integrating code with displaying logging values

Discussions about all things Bitcraze
Post Reply
Abanoub.G
Beginner
Posts: 12
Joined: Mon Jan 29, 2018 3:46 pm

Urgent: Integrating code with displaying logging values

Post by Abanoub.G » Wed Feb 28, 2018 1:26 am

Hi,
I have been trying to integrate my code which does a certain maneuver with the bit of code from basiclog.py example on the VM.

However all of my trials ended up giving me the error of 'Could not add Stabilizer log config, bad configuration'.

Shown below is my code and the code example that I'd like to integrate. Would really appreciate some prompt help.

This my code

Code: Select all

"Simple code to achieve perching on a wall"
import logging
import time
from threading import Thread

import cflib
from cflib.crazyflie import Crazyflie

# import cflib.crtp  # noqa
# from cflib.crazyflie.log import LogConfig

logging.basicConfig(level=logging.ERROR)


class Perching_manouevre:
    """Example that connects to a Crazyflie and ramps the motors up/down and
    the 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)
        # Variable used to keep main loop occupied until disconnec

    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."""
        print('Connected to %s' % link_uri)
        # Start a separate thread to do the motor test.
        # Do not hijack the calling thread!
        Thread(target=self._manouevre).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 _manouevre(self):
        thrust = 10001
        pitch = 3
        roll = 2
        yawrate = 0
        counter = 0

        wait_hover = 10
        wait_forward = 0.8
        wait_stop = 0.1#25

        forwards_pitch = 30
        perching_pitch = -90

        # thrust = thrust + thrust_step*7
        thrust = thrust*4.3
        thrust = round(thrust)
        # Unlock startup thrust protection
        self._cf.commander.send_setpoint(0, 0, 0, 0)

        print(thrust)
        while thrust == thrust:

            counter = counter+0.1
            pitch = forwards_pitch
            if counter > wait_forward:
                pitch = perching_pitch
            if counter > wait_forward + wait_stop :
                print("Close connection")
                self._cf.commander.send_setpoint(0, 0, 0, 0)
                self._cf.close_link()

            self._cf.commander.send_setpoint(roll, pitch, yawrate, thrust)
            time.sleep(0.1)



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('Crazyflies found:')

    for i in available:
        print(i[0])

    if len(available) > 0:
        le = Perching_manouevre(available[0][0])
    else:
        print('No Crazyflies found, cannot run example')
This is the basiclog that has the code parts that I'd like to include into my code to get values of the motors.

Code: Select all

# -*- coding: utf-8 -*-
#
#     ||          ____  _ __
#  +------+      / __ )(_) /_______________ _____  ___
#  | 0xBC |     / __  / / __/ ___/ ___/ __ `/_  / / _ \
#  +------+    / /_/ / / /_/ /__/ /  / /_/ / / /_/  __/
#   ||  ||    /_____/_/\__/\___/_/   \__,_/ /___/\___/
#
#  Copyright (C) 2014 Bitcraze AB
#
#  Crazyflie Nano Quadcopter Client
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA  02110-1301, USA.
"""
Simple example that connects to the first Crazyflie found, logs the Stabilizer
and prints it to the console. After 10s the application disconnects and exits.
"""
import logging
import time
from threading import Timer

import cflib.crtp  # noqa
from cflib.crazyflie import Crazyflie
from cflib.crazyflie.log import LogConfig

# Only output errors from the logging framework
logging.basicConfig(level=logging.ERROR)


class LoggingExample:
    """
    Simple logging example class that logs the Stabilizer from a supplied
    link uri and disconnects after 5s.
    """

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

        # Create a Crazyflie object without specifying any cache dirs
        self._cf = Crazyflie()

        # Connect some callbacks from the Crazyflie API
        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)

        print('Connecting to %s' % link_uri)

        # Try to connect to the Crazyflie
        self._cf.open_link(link_uri)

        # Variable used to keep main loop occupied until disconnect
        self.is_connected = True

    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."""
        print('Connected to %s' % link_uri)

        # The definition of the logconfig can be made before connecting
        self._lg_stab = LogConfig(name='Stabilizer', period_in_ms=10)
        self._lg_stab.add_variable('stabilizer.thrust', 'float')
        self._lg_stab.add_variable('stabilizer.roll', 'float')
        self._lg_stab.add_variable('stabilizer.pitch', 'float')
        # self._lg_stab.add_variable('stabilizer.yaw', 'float')
        self._lg_stab.add_variable('motor.m1', 'float')
        self._lg_stab.add_variable('motor.m2', 'float')
        self._lg_stab.add_variable('motor.m3', 'float')
        # self._lg_stab.add_variable('motor.m4', 'float')

        # Adding the configuration cannot be done until a Crazyflie is
        # connected, since we need to check that the variables we
        # would like to log are in the TOC.
        try:
            self._cf.log.add_config(self._lg_stab)
            # This callback will receive the data
            self._lg_stab.data_received_cb.add_callback(self._stab_log_data)
            # This callback will be called on errors
            self._lg_stab.error_cb.add_callback(self._stab_log_error)
            # Start the logging
            self._lg_stab.start()


        except KeyError as e:
            print('Could not start log configuration,'
                  '{} not found in TOC'.format(str(e)))
        except AttributeError:
            print('Could not add Stabilizer log config, bad configuration.')

        # Start a timer to disconnect in 10s
        t = Timer(5, self._cf.close_link)
        t.start()

    def _stab_log_error(self, logconf, msg):
        """Callback from the log API when an error occurs"""
        print('Error when logging %s: %s' % (logconf.name, msg))

    def _stab_log_data(self, timestamp, data, logconf):
        """Callback froma the log API when data arrives"""
        print('[%d][%s]: %s' % (timestamp, logconf.name, data))

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

    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)
        self.is_connected = False


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('Crazyflies found:')
    for i in available:
        print(i[0])

    if len(available) > 0:
        le = LoggingExample(available[0][0])
    else:
        print('No Crazyflies found, cannot run example')

    # The Crazyflie lib doesn't contain anything to keep the application alive,
    # so this is where your application should do something. In our case we
    # are just waiting until we are disconnected.
    while le.is_connected:
        time.sleep(1)



arnaud
Bitcraze
Posts: 2097
Joined: Tue Feb 06, 2007 12:36 pm

Re: Urgent: Integrating code with displaying logging values

Post by arnaud » Wed Feb 28, 2018 4:14 pm

I tested the second code and the log part works for me:

Code: Select all

$ python3 test.py 
Scanning interfaces for Crazyflies...
Crazyflies found:
radio://0/94/2M
Connecting to radio://0/94/2M
Connected to radio://0/94/2M
[105789][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 1.0175193548202515, 'stabilizer.roll': -1.249812126159668, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
[105799][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 1.0127460956573486, 'stabilizer.roll': -1.2254458665847778, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
[105809][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 0.9769782423973083, 'stabilizer.roll': -1.1836609840393066, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
[105819][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 0.9617494940757751, 'stabilizer.roll': -1.1392955780029297, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
[105829][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 0.9656851887702942, 'stabilizer.roll': -1.1146514415740967, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
[105839][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 0.9210825562477112, 'stabilizer.roll': -1.100810170173645, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
[105849][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 0.9072151184082031, 'stabilizer.roll': -1.092944622039795, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
[105859][Stabilizer]: {'motor.m3': 0.0, 'stabilizer.pitch': 0.9520643949508667, 'stabilizer.roll': -1.1956344842910767, 'motor.m2': 0.0, 'stabilizer.thrust': 0.0, 'motor.m1': 0.0}
And the first code does not contains any reference to log. Are you getting an error with the second code?

Ps. there is no need to write Urgent in the title of your posts. We strive to answer the forum post as fast as we can and marking the posts as urgent will not makes them answered any faster.

abush
Beginner
Posts: 2
Joined: Tue Jun 18, 2019 5:51 pm

Re: Urgent: Integrating code with displaying logging values

Post by abush » Sun Jun 30, 2019 7:46 pm

Hey arnaud, How did you test the code? when i run the code it says no crazyflies found. And when I connect the crazyflie with usb the consule says' connecting to usb' then i couldn't get the output.

arnaud
Bitcraze
Posts: 2097
Joined: Tue Feb 06, 2007 12:36 pm

Re: Urgent: Integrating code with displaying logging values

Post by arnaud » Mon Jul 01, 2019 11:20 am

I tested the code exactly as shown in my message, running it with python3.

If you can connect your crazyflie from the client, and if the crazyflies are on the default address, it should work. Note that the client needs to be disconnected first before running the script.

Post Reply