# -*- 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
from threading import Thread

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

import numpy as np

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


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

    def __init__(self):
        """ Initialize and run the example with the specified link_uri """
        
        self._cf = Crazyflie(rw_cache='./cache')
        
        # Initialize the low-level drivers (don't list the debug drivers)
        cflib.crtp.init_drivers(enable_debug_driver=False)
        print('Scanning interfaces for Crazyflies...')
        available=cflib.crtp.scan_interfaces()
        print('Crazyflies found:')
        for i in available:
            print(i[0])
        numdrone=input('Inserisci il numero del drone: ')
        if numdrone=="exit":
            exit('Programma arrestato')
            
        
        if len(available) > 0:
            link_uri=available[int(numdrone)][0]
            print(link_uri)
        else:
            print('No Crazyflies found, cannot run example')
        self.link_uri=link_uri
        # 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
        self.calc_offset = True

    def crazyflie(self):
        return self._cf

    def close_link(self):
        self._cf.close_link()

    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._lg1 = LogConfig(name='Block1', period_in_ms=100)
        self._lg2 = LogConfig(name='Block2', period_in_ms=100)
        self._lg3 = LogConfig(name='Block3', period_in_ms=100)
        self._lg4 = LogConfig(name='Block4', period_in_ms=100)
        self._lg5 = LogConfig(name='Block5', period_in_ms=100)
        #Euler Angles

        #self._lg.add_variable('stabilizer.roll', 'float')
        #self._lg.add_variable('stabilizer.pitch', 'float')
        #self._lg.add_variable('stabilizer.yaw', 'float')

        #Quaternions
        self._lg1.add_variable('kalman.q0', 'float')
        self._lg1.add_variable('kalman.q1', 'float')
        self._lg1.add_variable('kalman.q2', 'float')
        self._lg1.add_variable('kalman.q3', 'float')

        self._lg2.add_variable('gyro.x', 'float')
        self._lg2.add_variable('gyro.y', 'float')
        self._lg2.add_variable('gyro.z', 'float')

        self._lg3.add_variable('kalman.stateX', 'float')        
        self._lg3.add_variable('kalman.stateY', 'float')
        self._lg3.add_variable('kalman.stateZ', 'float')

        self._lg3.add_variable('kalman_states.vx', 'float')
        self._lg3.add_variable('kalman_states.vy', 'float')
        self._lg3.add_variable('kalman.statePZ', 'float')

        self._lg4.add_variable('kalman.varPX', 'float')
        self._lg4.add_variable('kalman.varPY', 'float')
        self._lg4.add_variable('kalman.varPZ', 'float')
        
        self._lg5.add_variable('motor.m1', 'float')
        self._lg5.add_variable('motor.m2', 'float')
        self._lg5.add_variable('motor.m3', 'float')
        self._lg5.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._lg1)
            self._cf.log.add_config(self._lg2)
            self._cf.log.add_config(self._lg3)
            self._cf.log.add_config(self._lg4)
            self._cf.log.add_config(self._lg5)
            # This callback will receive the data
            self._lg1.data_received_cb.add_callback(self.log_data_block1)
            self._lg2.data_received_cb.add_callback(self.log_data_block2)
            self._lg3.data_received_cb.add_callback(self.log_data_block3)
            self._lg4.data_received_cb.add_callback(self.log_data_block4)
            self._lg5.data_received_cb.add_callback(self.log_data_block5)
            # This callback will be called on errors
            self._lg1.error_cb.add_callback(self.log_error)
            self._lg2.error_cb.add_callback(self.log_error)
            self._lg3.error_cb.add_callback(self.log_error)
            self._lg4.error_cb.add_callback(self.log_error)
            self._lg5.error_cb.add_callback(self.log_error)
            # Start the logging
            self._lg1.start()
            self._lg2.start()
            self._lg3.start()
            self._lg4.start()
            self._lg5.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.')

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

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

    def log_data_block1(self, timestamp, data, logconf):
        """Callback froma the log API when data arrives"""
        print('[%s]: %s' % (logconf.name, data))
        estimate = open('estimate.txt' , 'a')
        write = estimate.write(str(timestamp)+ ','+str(data)+ '\n')
        estimate.closed
        self.q0 = data['kalman.q0']
        self.q1 = data['kalman.q1']
        self.q2 = data['kalman.q2']
        self.q3 = data['kalman.q3']

    def log_data_block2(self, timestamp, data, logconf):
        """Callback froma the log API when data arrives"""
        print('[%s]: %s' % (logconf.name, data))
        estimate = open('estimate.txt' , 'a')
        write = estimate.write(str(timestamp)+ ','+str(data)+ '\n')
        estimate.closed
        self.wx = np.deg2rad(data['gyro.x'])
        self.wy = np.deg2rad(data['gyro.y'])
        self.wz = np.deg2rad(data['gyro.z'])

    def log_data_block3(self, timestamp, data, logconf):
        """Callback froma the log API when data arrives"""
        print('[%s]: %s' % (logconf.name, data))
        estimate = open('estimate.txt' , 'a')
        write = estimate.write(str(timestamp)+ ','+str(data)+ '\n')
        estimate.closed
        if self.calc_offset:
            self.offset_x = data['kalman.stateX']
            self.offset_y = data['kalman.stateY']
            self.calc_offset = False
        self.px = data['kalman.stateX'] - self.offset_x
        self.py = data['kalman.stateY'] - self.offset_y
        self.pz = data['kalman.stateZ']
        self.vx = data['kalman_states.vx']
        self.vy = data['kalman_states.vy']
        self.vz = data['kalman.statePZ']
        
    def log_data_block4(self, timestamp, data, logconf):
        print('[%s]: %s' % (logconf.name, data))
        estimate = open('estimate.txt' , 'a')
        write = estimate.write(str(timestamp)+ ','+str(data)+ '\n')
        estimate.closed
        self.varX = data['kalman.varPX']
        self.varY = data['kalman.varPY']
        self.varZ = data['kalman.varPZ']

    def log_data_block5(self, timestamp, data, logconf):
        print('[%s]: %s' % (logconf.name, data))
        estimate = open('estimate.txt' , 'a')
        write = estimate.write(str(timestamp)+ ','+str(data)+ '\n')
        estimate.closed
        self.rollRate = data['motor.m1']
        self.pitchRate = data['motor.m2']
        self.yawRate = data['motor.m3']
        self.actuatorThrust = data['motor.m4']

    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)


    le=Logger()


    a = 12
    b = 25
    v = 0.2
    if le.is_connected:
        time.sleep(1)

        #le._cf.param.set_value('kalman.resetEstimation', '1')
        #time.sleep(1)
       # le._cf.param.set_value('kalman.resetEstimation', '0')
       # time.sleep(1)
        ##########Decollo#############
        for y in range(a):
            le._cf.commander.send_hover_setpoint(0, 0, 0, y / b)
            time.sleep(0.1)
  
        for _ in range(40):
            le._cf.commander.send_hover_setpoint(0, 0, 0, a/b)
            time.sleep(0.1)
#  
#         #########Quadrato##########
#         
#         for _ in range(10):
#             le._cf.commander.send_hover_setpoint(v, 0, 0, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(30):
#             le._cf.commander.send_hover_setpoint(0, 0, 15*2, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(10):
#             le._cf.commander.send_hover_setpoint(v, 0, 0, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(30):
#             le._cf.commander.send_hover_setpoint(0, 0, 15*2, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(10):
#             le._cf.commander.send_hover_setpoint(v, 0, 0, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(30):
#             le._cf.commander.send_hover_setpoint(0, 0, 15*2, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(10):
#             le._cf.commander.send_hover_setpoint(v, 0, 0, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(30):
#             le._cf.commander.send_hover_setpoint(0, 0, 15*2, a/b)
#             time.sleep(0.1)
#  
#         for _ in range(40):
#             le._cf.commander.send_hover_setpoint(0, 0, 0, a/b)
#             time.sleep(0.1)
#  
#         ###### Infinito###########
        for _ in range(50):
            le._cf.commander.send_hover_setpoint(v, 0, 40 * 2, a/b)
            time.sleep(0.1)
  
  
        for _ in range(50):
            le._cf.commander.send_hover_setpoint(v, 0, -40 * 2, a/b)
            time.sleep(0.1)
#         ####### Cerchio ########
#         for _ in range(40):
#             le._cf.commander.send_hover_setpoint(0, 0, 0, a/b)
#             time.sleep(0.1)
#              
#         for _ in range(50):
#             le._cf.commander.send_hover_setpoint(v, 0, 40 * 2, a/b)
#             time.sleep(0.1)
#         #######Atterra ###########
        for y in range(a):
            le._cf.commander.send_hover_setpoint(0, 0, 0, (a - y) / b)
            time.sleep(0.1)
#         for i in range(10):
#             print(i)
#              
#         le._cf.commander.send_stop_setpoint()
#         time.sleep(0.1)        
        le._lg1.stop()
        le._lg2.stop()
        le._lg3.stop()
        le._lg4.stop()
        le._lg5.stop()
        #le._disconnected(le.link_uri)
        time.sleep(0.5)
        le._disconnected('radio://0/80/2M')
        time.sleep(0.5)
        le._cf.close_link
        print('Fine If')
   # le._cf.commander.send_stop_setpoint()
    
    if le.is_connected:
        print('Connesso')
    else:
         print('Disconnesso')
#le._cf.commander.send_stop_setpoint()
