Skip to content
C

Add files via upload

Jobit Joseph9ecc816f9f0a
diff --git a/Firmware/esp-drone/components/core/crazyflie/CMakeLists.txt b/Firmware/esp-drone/components/core/crazyflie/CMakeLists.txt
new file mode 100644
index 0000000..8625c59
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/CMakeLists.txt
@@ -0,0 +1,81 @@
+idf_component_register(SRCS "./hal/src/buzzer.c"
+ "./hal/src/freeRTOSdebug.c"
+ "./hal/src/ledseq.c"
+ "./hal/src/pm_esplane.c"
+ "./hal/src/sensors_mpu6050_hm5883L_ms5611.c"
+ "./hal/src/sensors.c"
+ "./hal/src/usec_time.c"
+ "./hal/src/wifilink.c"
+ "./modules/src/app_handler.c"
+ "./modules/src/app_channel.c"
+ "./modules/src/attitude_pid_controller.c"
+ "./modules/src/comm.c"
+ "./modules/src/commander.c"
+ "./modules/src/console.c"
+ "./modules/src/controller_indi.c"
+ "./modules/src/controller_mellinger.c"
+ "./modules/src/controller_pid.c"
+ "./modules/src/controller.c"
+ "./modules/src/crtp_commander_generic.c"
+ "./modules/src/crtp_commander_high_level.c"
+ "./modules/src/crtp_commander_rpyt.c"
+ "./modules/src/crtp_commander.c"
+ "./modules/src/crtp.c"
+ "./modules/src/crtpservice.c"
+ "./modules/src/estimator_complementary.c"
+ "./modules/src/estimator_kalman.c"
+ "./modules/src/estimator.c"
+ "./modules/src/kalman_core.c"
+ "./modules/src/kalman_supervisor.c"
+ "./modules/src/log.c"
+ "./modules/src/mem.c"
+ "./modules/src/msp.c"
+ "./modules/src/outlierFilter.c"
+ "./modules/src/param.c"
+ "./modules/src/pid.c"
+ "./modules/src/planner.c"
+ "./modules/src/platformservice.c"
+ "./modules/src/position_controller_indi.c"
+ "./modules/src/position_controller_pid.c"
+ "./modules/src/position_estimator_altitude.c"
+ "./modules/src/power_distribution_stock.c"
+ "./modules/src/pptraj_compressed.c"
+ "./modules/src/pptraj.c"
+ "./modules/src/queuemonitor.c"
+ "./modules/src/range.c"
+ "./modules/src/sensfusion6.c"
+ "./modules/src/sitaw.c"
+ "./modules/src/sound_cf2.c"
+ "./modules/src/stabilizer.c"
+ "./modules/src/sysload.c"
+ "./modules/src/system.c"
+ "./modules/src/trigger.c"
+ "./modules/src/worker.c"
+ "./utils/src/abort.c"
+ "./utils/src/cfassert.c"
+ "./utils/src/clockCorrectionEngine.c"
+ "./utils/src/configblockeeprom.c"
+ "./utils/src/cpuid.c"
+ "./utils/src/crc_bosch.c"
+ "./utils/src/crc.c"
+ "./utils/src/debug_cf.c"
+ "./utils/src/eprintf.c"
+ "./utils/src/filter.c"
+ "./utils/src/FreeRTOS-openocd.c"
+ "./utils/src/num.c"
+ "./utils/src/sleepus.c"
+ "./utils/src/statsCnt.c"
+ "./utils/src/version.c"
+ "./utils/src/rateSupervisor.c"
+ INCLUDE_DIRS "./hal/interface" "./modules/interface" "./utils/interface"
+ REQUIRES i2c_bus deck mpu6050 ms5611 hmc5883l pmw3901 vl53l1 vl53l0 platform config led eeprom dsp_lib motors wifi adc esp_timer)
+
+idf_component_get_property( FREERTOS_ORIG_INCLUDE_PATH freertos ORIG_INCLUDE_PATH)
+target_include_directories(${COMPONENT_TARGET} PUBLIC
+ "${FREERTOS_ORIG_INCLUDE_PATH}"
+)
+target_compile_options(${COMPONENT_LIB} PRIVATE "-fno-strict-aliasing"
+ "-Wno-error=stringop-truncation"
+ "-Wno-absolute-value"
+ "-Wno-address-of-packed-member"
+ "-Wno-stringop-truncation")
\ No newline at end of file
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/cf_math.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/cf_math.h
new file mode 100644
index 0000000..def3365
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/cf_math.h
@@ -0,0 +1,111 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2018 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * Utilities to simplify unit testing
+ *
+ */
+
+#pragma once
+
+// Include "xtensa_math.h". This header generates some warnings, especially in
+// unit tests. We hide them to avoid noise.
+//TODO: NEED ESP32 SUPPORT
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wpedantic"
+#pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
+#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
+#pragma GCC diagnostic ignored "-Wunused-parameter"
+#include "xtensa_math.h"
+#pragma GCC diagnostic pop
+
+#include "cfassert.h"
+
+
+#define DEG_TO_RAD (PI/180.0f)
+#define RAD_TO_DEG (180.0f/PI)
+
+#define MIN(a, b) ((b) < (a) ? (b) : (a))
+#define MAX(a, b) ((b) > (a) ? (b) : (a))
+
+// Matrix data must be aligned on 4 byte bundaries
+static inline void assert_aligned_4_bytes(const xtensa_matrix_instance_f32 *matrix)
+{
+ const uint32_t address = (uint32_t)matrix->pData;
+ ASSERT((address & 0x3) == 0);
+}
+
+static inline void mat_trans(const xtensa_matrix_instance_f32 *pSrc, xtensa_matrix_instance_f32 *pDst)
+{
+ assert_aligned_4_bytes(pSrc);
+ assert_aligned_4_bytes(pDst);
+
+ ASSERT(XTENSA_MATH_SUCCESS == xtensa_mat_trans_f32(pSrc, pDst));
+}
+
+static inline void mat_inv(const xtensa_matrix_instance_f32 *pSrc, xtensa_matrix_instance_f32 *pDst)
+{
+ assert_aligned_4_bytes(pSrc);
+ assert_aligned_4_bytes(pDst);
+
+ ASSERT(XTENSA_MATH_SUCCESS == xtensa_mat_inverse_f32(pSrc, pDst));
+}
+
+static inline void mat_mult(const xtensa_matrix_instance_f32 *pSrcA, const xtensa_matrix_instance_f32 *pSrcB, xtensa_matrix_instance_f32 *pDst)
+{
+ assert_aligned_4_bytes(pSrcA);
+ assert_aligned_4_bytes(pSrcB);
+ assert_aligned_4_bytes(pDst);
+
+ ASSERT(XTENSA_MATH_SUCCESS == xtensa_mat_mult_f32(pSrcA, pSrcB, pDst));
+}
+
+static inline float xtensa_sqrt(float32_t in)
+{
+ float pOut = 0;
+ xtensa_status result = xtensa_sqrt_f32(in, &pOut);
+ ASSERT(XTENSA_MATH_SUCCESS == result);
+ return pOut;
+}
+
+static inline float limPos(float in)
+{
+ if (in < 0.0f) {
+ return 0.0f;
+ }
+
+ return in;
+}
+
+static inline float clip1(float a)
+{
+ if (a < -1.0f) {
+ return -1.0f;
+ }
+
+ if (a > 1.0f) {
+ return 1.0f;
+ }
+
+ return a;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/cfassert.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/cfassert.h
new file mode 100644
index 0000000..88588b9
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/cfassert.h
@@ -0,0 +1,101 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+*
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * cfassert.h - Assert macro
+ */
+
+#include "console.h"
+
+#ifndef __CFASSERT_H__
+#define __CFASSERT_H__
+
+#define ASSERT(e) if (e) ; \
+ else assertFail( #e, __FILE__, __LINE__ )
+
+#ifdef DEBUG_EP2
+#define IF_DEBUG_ASSERT(e) if (e) ; \
+ else assertFail( #e, __FILE__, __LINE__ )
+#else
+#define IF_DEBUG_ASSERT(e)
+#endif
+
+#define ASSERT_FAILED() assertFail( "", __FILE__, __LINE__ )
+
+/**
+ * @brief Assert that verifies that a pointer is pointing at memory that can be
+ * used for DMA transfers. There are two types of RAM in the Crazyflie and CCM
+ * does not work for DMA. Flash and RAM can be accessed by the DMA.
+ *
+ * @param[in] PTR : the pointer to verify
+ */
+#ifdef STM32F4XX
+#define ASSERT_DMA_SAFE(PTR) if (((uint32_t)(PTR) >= 0x10000000) && ((uint32_t)(PTR) <= 0x1000FFFF)) assertFail( "", __FILE__, __LINE__ )
+#else
+#define ASSERT_DMA_SAFE(PTR)
+#endif
+
+
+/**
+ * Assert handler function
+ */
+void assertFail(char *exp, char *file, int line);
+/**
+ * Print assert snapshot data
+ */
+void printAssertSnapshotData();
+/**
+ * Store assert snapshot data to be read at startup if a reset is triggered (watchdog)
+ */
+void storeAssertFileData(const char *file, int line);
+/**
+ * Store hardfault data to be read at startup if a reset is triggered (watchdog)
+ * Line information can be printed using:
+ * > make gdb
+ * gdb> info line *0x<PC>
+ */
+void storeAssertHardfaultData(
+ unsigned int r0,
+ unsigned int r1,
+ unsigned int r2,
+ unsigned int r3,
+ unsigned int r12,
+ unsigned int lr,
+ unsigned int pc,
+ unsigned int psr);
+
+/**
+ * Store assert data to be read at startup if a reset is triggered (watchdog)
+ */
+void storeAssertTextData(const char *text);
+
+/**
+ * @brief Check for assert information to indicate that the system was restarted
+ * after a failed assert.
+ *
+ * @return true If assert information exists
+ * @return false If no assert information exists
+ */
+bool cfAssertNormalStartTest(void);
+
+#endif //__CFASSERT_H__
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/clockCorrectionEngine.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/clockCorrectionEngine.h
new file mode 100644
index 0000000..60aa549
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/clockCorrectionEngine.h
@@ -0,0 +1,44 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2018 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * clockCorrectionEngine.h - utitlity for keeping track of clock drift
+ * in UWB positioning system.
+ */
+
+#ifndef clockCorrectionEngine_h
+#define clockCorrectionEngine_h
+
+#include <stdbool.h>
+#include <stdint.h>
+
+typedef struct {
+ double clockCorrection;
+ unsigned int clockCorrectionBucket;
+} clockCorrectionStorage_t;
+
+double clockCorrectionEngineGet(const clockCorrectionStorage_t* storage);
+double clockCorrectionEngineCalculate(const uint64_t new_t_in_cl_reference, const uint64_t old_t_in_cl_reference, const uint64_t new_t_in_cl_x, const uint64_t old_t_in_cl_x, const uint64_t mask);
+bool clockCorrectionEngineUpdate(clockCorrectionStorage_t* storage, const double clockCorrectionCandidate);
+
+#endif /* clockCorrectionEngine_h */
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/configblock.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/configblock.h
new file mode 100644
index 0000000..e089f42
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/configblock.h
@@ -0,0 +1,44 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * configblock.h - Simple static implementation of the config block
+ */
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#ifndef __CONFIGBLOCK_H__
+#define __CONFIGBLOCK_H__
+
+int configblockInit(void);
+bool configblockTest(void);
+
+/* Static accessors */
+int configblockGetRadioChannel(void);
+int configblockGetRadioSpeed(void);
+uint64_t configblockGetRadioAddress(void);
+
+float configblockGetCalibPitch(void);
+float configblockGetCalibRoll(void);
+
+#endif //__CONFIGBLOCK_H__
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/cpuid.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/cpuid.h
new file mode 100644
index 0000000..3593e61
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/cpuid.h
@@ -0,0 +1,35 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * cpuid.h - CPU ID and Flash size function
+ */
+
+#ifndef __CPUID_H__
+#define __CPUID_H__
+
+//The CPU ID is 12 bytes long
+unsigned char * cpuidGetId();
+int cpuIdGetFlashSize();
+
+#endif /* __CPUID_H__ */
+
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/crc.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/crc.h
new file mode 100644
index 0000000..57c01c4
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/crc.h
@@ -0,0 +1,123 @@
+/**********************************************************************
+ *
+ * Filename: crc.h
+ *
+ * Description: A header file describing the various CRC standards.
+ *
+ * Notes: See crc.c
+ *
+ *
+ * Copyright (c) 2012 Bitcraze AB
+ * Copyright (c) 2000 by Michael Barr. This software is placed into
+ * the public domain and may be used for any purpose. However, this
+ * notice must not be changed or removed and no warranty is either
+ * expressed or implied by its publication or distribution.
+ **********************************************************************/
+/**
+ * @file
+ * Efficient implementation of various CRC standards.
+ *
+ * Two CRC calculation function are implemented: flow and fast. The slow version
+ * is espcially inefficient but virtually use no RAM at all. The fast function
+ * is more efficient cpu-wise but require from 512 to 1KiB of RAM located lookup
+ * table (might be possible to move the table into FLASH, but then it would take
+ * 1K of flash ...).
+ *
+ * crcInit() shall be used *only* if the fast version of CRC is used.
+ *
+ * The CRC algorythm to use is choosen in crc.h.
+ */
+
+#ifndef _crc_h
+#define _crc_h
+
+#include <stdint.h>
+
+#define FALSE 0
+#define TRUE !FALSE
+
+/**
+ * Select the CRC standard from the list that follows.
+ */
+#define CRC32
+
+
+#if defined(CRC_CCITT)
+
+typedef uint16_t crc;
+
+#define CRC_NAME "CRC-CCITT"
+#define POLYNOMIAL 0x1021
+#define INITIAL_REMAINDER 0xFFFF
+#define FINAL_XOR_VALUE 0x0000
+#define REFLECT_DATA FALSE
+#define REFLECT_REMAINDER FALSE
+#define CHECK_VALUE 0x29B1
+
+#elif defined(CRC16)
+
+typedef uint16_t crc;
+
+#define CRC_NAME "CRC-16"
+#define POLYNOMIAL 0x8005
+#define INITIAL_REMAINDER 0x0000
+#define FINAL_XOR_VALUE 0x0000
+#define REFLECT_DATA TRUE
+#define REFLECT_REMAINDER TRUE
+#define CHECK_VALUE 0xBB3D
+
+#elif defined(CRC32)
+
+typedef uint32_t crc;
+
+#define CRC_NAME "CRC-32"
+#define POLYNOMIAL 0x04C11DB7
+#define INITIAL_REMAINDER 0xFFFFFFFF
+#define FINAL_XOR_VALUE 0xFFFFFFFF
+#define REFLECT_DATA TRUE
+#define REFLECT_REMAINDER TRUE
+#define CHECK_VALUE 0xCBF43926
+
+#else
+
+#error "One of CRC_CCITT, CRC16, or CRC32 must be #define'd."
+
+#endif
+
+/**
+ * Init function that must be called before using crcFast().
+ * This function is useless for crcSlow() and shall not be called if only
+ * crcSlow() is used!
+ *
+ * @note Using this function will use 1KiB of BSS ram!
+ */
+void crcInit(void);
+
+/**
+ * Slow implementation of CRC.
+ *
+ * This function trades speeds for memory usage as it does not require
+ * pre-calculated tables but executes some code for each data bits. Good for one
+ * time CRC calculation. Bad for data communication check.
+ *
+ * @param datas Pointer to the data buffer onto the CRC will be calculated.
+ * @param nBytes Number of bytes to calculate the CRC from.
+ * @return The CRC value.
+ */
+crc crcSlow(void * datas, int nBytes);
+
+/**
+ * Fast implementation of CRC.
+ *
+ * This function trades memory usage for speed as it requires pre-calculated
+ * table (calculated by crcInit()). The requirement is 512Bytes for 16bits CRC
+ * and 1024Bytes for 32bits CRC.
+ *
+ * @param datas Pointer to the data buffer onto the CRC will be calculated.
+ * @param nBytes Number of bytes to calculate the CRC from.
+ * @return The CRC value.
+ */
+crc crcFast(void * datas, int nBytes);
+
+
+#endif /* _crc_h */
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/crc_bosch.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/crc_bosch.h
new file mode 100644
index 0000000..a70a87a
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/crc_bosch.h
@@ -0,0 +1,138 @@
+/**
+ * Copyright (C) 2017 Bosch Sensortec GmbH
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * Neither the name of the copyright holder nor the names of the
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ * OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ * The information provided is believed to be accurate and reliable.
+ * The copyright holder assumes no responsibility
+ * for the consequences of use
+ * of such information nor for any infringement of patents or
+ * other rights of third parties which may result from its use.
+ * No license is granted by implication or otherwise under any patent or
+ * patent rights of the copyright holder.
+ */
+
+#ifndef _crc_h
+#define _crc_h
+
+#include <inttypes.h>
+
+#define FALSE 0
+#define TRUE !FALSE
+
+/* select the CRC standard from the list that follows */
+#define CRC32
+
+/* CRC standard list */
+#if defined(CRC8)
+
+typedef uint8_t crc;
+
+#define CRC_NAME "CRC-8"
+#define POLYNOMIAL 0x07
+#define CHECK_VALUE 0x04
+#define INITIAL_REMAINDER 0x00
+#define FINAL_XOR_VALUE 0x00
+#define REFLECT 0
+
+#elif defined(CRC16C)
+
+typedef unsigned short crc;
+
+#define CRC_NAME "CRC-16/CCITT-FALSE"
+#define POLYNOMIAL 0x1021
+#define CHECK_VALUE 0x29B1
+#define INITIAL_REMAINDER 0xFFFF
+#define FINAL_XOR_VALUE 0x0000
+#define REFLECT 0
+
+#elif defined(CRC16A)
+
+typedef unsigned short crc;
+
+#define CRC_NAME "CRC-16/ARC"
+#define POLYNOMIAL 0xA001
+#define CHECK_VALUE 0xBB3D
+#define INITIAL_REMAINDER 0x0000
+#define FINAL_XOR_VALUE 0x0000
+#define REFLECT 1
+
+#elif defined(CRC16B)
+
+typedef unsigned short crc;
+
+#define CRC_NAME "CRC-16/BUYPASS"
+#define POLYNOMIAL 0x8005
+#define CHECK_VALUE 0xFEE8
+#define INITIAL_REMAINDER 0x0000
+#define FINAL_XOR_VALUE 0x0000
+#define REFLECT 0
+
+#elif defined(CRC32)
+
+typedef unsigned long crc;
+
+#define CRC_NAME "CRC-32"
+#define POLYNOMIAL 0xEDB88320
+#define CHECK_VALUE 0xCBF43926
+#define INITIAL_REMAINDER 0xFFFFFFFF
+#define FINAL_XOR_VALUE 0xFFFFFFFF
+#define RESIDUE 0xDEBB20e3
+#define REFLECT 1
+
+#elif defined(CRC32B)
+
+typedef unsigned long crc;
+
+#define CRC_NAME "CRC-32/BZIP2"
+#define POLYNOMIAL 0x04C11DB7
+#define CHECK_VALUE 0xFC891918
+#define INITIAL_REMAINDER 0xFFFFFFFF
+#define FINAL_XOR_VALUE 0xFFFFFFFF
+#define RESIDUE 0xC704DD7B
+#define REFLECT 0
+
+#else
+
+#error "one of CRC standard has to be #define'd."
+
+#endif
+
+#define WIDTH (8 * sizeof(crc))
+#define TOPBIT (1 << (WIDTH - 1))
+
+void crcTableInit(crc* crcTable);
+crc crcByBit(const uint8_t* message, uint32_t bytesToProcess,
+ crc remainder, crc finalxor);
+crc crcByByte(const uint8_t* message, uint32_t bytesToProcess,
+ crc remainder, crc finalxor, crc* crcTable);
+
+#endif /* _crc_h */
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/debug_cf.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/debug_cf.h
new file mode 100644
index 0000000..5551804
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/debug_cf.h
@@ -0,0 +1,106 @@
+/*
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * debug_cf.h - Debugging utility functions
+ */
+#ifndef _DEBUG_CF_H
+#define _DEBUG_CF_H
+
+#include "config.h"
+#include "console.h"
+//if enable, some message will print to remote client
+//#define DEBUG_PRINT_ON_CONSOLE
+#ifdef DEBUG_PRINT_ON_UART
+ #include "uart1.h"
+ #define uartPrintf uart1Printf
+#endif
+
+#ifdef DEBUG_PRINT_ON_SEGGER_RTT
+ #include "SEGGER_RTT.h"
+#endif
+
+#ifndef DEBUG_MODULE
+ #define DEBUG_MODULE "NULL"
+ #define DEBUG_FMT(fmt) (DEBUG_MODULE ": " fmt)
+#else
+ #define DEBUG_FMT(fmt) (DEBUG_MODULE ": " fmt)
+#endif
+
+#ifndef DEBUG_FMT
+#define DEBUG_FMT(fmt) fmt
+#endif
+
+void debugInit(void);
+
+#include "esp_log.h"
+#define DEBUG_PRINT_LOCAL(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+#define DEBUG_PRINT_REMOT(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
+
+#if defined(DEBUG_PRINT_ON_UART)
+ #define DEBUG_PRINT(fmt, ...) uartPrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
+ #define DEBUG_PRINT_OS(fmt, ...) uartPrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
+#elif defined(DEBUG_PRINT_ON_SWO)
+ #define DEBUG_PRINT(fmt, ...) eprintf(ITM_SendChar, fmt, ## __VA_ARGS__)
+ #define DEBUG_PRINT_OS(fmt, ...) eprintf(ITM_SendChar, fmt, ## __VA_ARGS__)
+#elif defined(DEBUG_PRINT_ON_SEGGER_RTT)
+ #define DEBUG_PRINT(fmt, ...) SEGGER_RTT_printf(0, fmt, ## __VA_ARGS__)
+ #define DEBUG_PRINT_OS(fmt, ...) SEGGER_RTT_printf(0, fmt, ## __VA_ARGS__)
+#elif defined(DEBUG_PRINT_ON_CONSOLE)// Debug using radio or USB
+ #include "esp_log.h"
+ #define DEBUG_PRINT(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINTE(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
+ #define DEBUG_PRINTW(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
+ #define DEBUG_PRINTI(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
+ #define DEBUG_PRINTD(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINTV(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_VERBOSE,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINT_OS(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+#else
+ #define DEBUG_PRINT(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINTE(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_ERROR,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINTW(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_WARN,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINTI(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINTD(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINTV(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_VERBOSE,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+ #define DEBUG_PRINT_OS(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO,DEBUG_MODULE,fmt, ##__VA_ARGS__)
+#endif
+
+#ifndef PRINT_OS_DEBUG_INFO
+ #undef DEBUG_PRINT_OS
+ #define DEBUG_PRINT_OS(fmt, ...)
+#endif
+
+
+#ifdef TEST_PRINTS
+ #define TEST_AND_PRINT(e, msgOK, msgFail)\
+ if(e) { DEBUG_PRINT(msgOK); } else { DEBUG_PRINT(msgFail); }
+ #define FAIL_PRINT(msg) DEBUG_PRINT(msg)
+#else
+ #define TEST_AND_PRINT(e, msgOK, msgFail)
+ #define FAIL_PRINT(msg)
+#endif
+
+#endif
+
+
+
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/eprintf.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/eprintf.h
new file mode 100644
index 0000000..812b3e6
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/eprintf.h
@@ -0,0 +1,44 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (c) 2012 Bitcraze AB
+ *
+ * eprintf.c: Memory-friendly ultra-limited embedded implementation of printf
+ */
+
+#include <stdarg.h>
+
+#ifndef __EPRINTF_H__
+#define __EPRINTF_H__
+
+/**
+ * putc function pointer definition
+ */
+typedef int (*putc_t)(int c);
+
+/**
+ * Light printf implementation
+ * @param[in] putcf Putchar function to be used by Printf
+ * @param[in] fmt Format string
+ * @param[in] ... Parameters to print
+ * @return the number of character printed
+ */
+int eprintf(putc_t putcf, char * fmt, ...)
+ __attribute__ (( format(printf, 2, 3) ));
+
+/**
+ * Light printf implementation
+ * @param[in] putcf Putchar function to be used by Printf
+ * @param[in] fmt Format string
+ * @param[in] ap Parameters to print
+ * @return the number of character printed
+ */
+int evprintf(putc_t putcf, char * fmt, va_list ap);
+
+#endif //__EPRINTF_H__
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/filter.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/filter.h
new file mode 100644
index 0000000..fcb53b6
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/filter.h
@@ -0,0 +1,193 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * filter.h - Filtering functions
+ */
+#ifndef FILTER_H_
+#define FILTER_H_
+#include <stdint.h>
+#include "math.h"
+
+#define IIR_SHIFT 8
+
+int16_t iirLPFilterSingle(int32_t in, int32_t attenuation, int32_t* filt);
+
+typedef struct {
+ float a1;
+ float a2;
+ float b0;
+ float b1;
+ float b2;
+ float delay_element_1;
+ float delay_element_2;
+} lpf2pData;
+
+void lpf2pInit(lpf2pData* lpfData, float sample_freq, float cutoff_freq);
+void lpf2pSetCutoffFreq(lpf2pData* lpfData, float sample_freq, float cutoff_freq);
+float lpf2pApply(lpf2pData* lpfData, float sample);
+float lpf2pReset(lpf2pData* lpfData, float sample);
+
+/** Second order low pass filter structure.
+ *
+ * using biquad filter with bilinear z transform
+ *
+ * http://en.wikipedia.org/wiki/Digital_biquad_filter
+ * http://www.earlevel.com/main/2003/03/02/the-bilinear-z-transform
+ *
+ * Laplace continious form:
+ *
+ * 1
+ * H(s) = -------------------
+ * s^2/w^2 + s/w*Q + 1
+ *
+ *
+ * Polynomial discrete form:
+ *
+ * b0 + b1 z^-1 + b2 z^-2
+ * H(z) = ----------------------
+ * a0 + a1 z^-1 + a2 z^-2
+ *
+ * with:
+ * a0 = 1
+ * a1 = 2*(K^2 - 1) / (K^2 + K/Q + 1)
+ * a2 = (K^2 - K/Q + 1) / (K^2 + K/Q + 1)
+ * b0 = K^2 / (K^2 + K/Q + 1)
+ * b1 = 2*b0
+ * b2 = b0
+ * K = tan(pi*Fc/Fs) ~ pi*Fc/Fs = Ts/(2*tau)
+ * Fc: cutting frequency
+ * Fs: sampling frequency
+ * Ts: sampling period
+ * tau: time constant (tau = 1/(2*pi*Fc))
+ * Q: gain at cutoff frequency
+ *
+ * Note that b[0]=b[2], so we don't need to save b[2]
+ */
+struct SecondOrderLowPass {
+ float a[2]; ///< denominator gains
+ float b[2]; ///< numerator gains
+ float i[2]; ///< input history
+ float o[2]; ///< output history
+};
+
+/** Init second order low pass filter.
+ *
+ * @param filter second order low pass filter structure
+ * @param tau time constant of the second order low pass filter
+ * @param Q Q value of the second order low pass filter
+ * @param sample_time sampling period of the signal
+ * @param value initial value of the filter
+ */
+static inline void init_second_order_low_pass(struct SecondOrderLowPass *filter, float tau, float Q, float sample_time,
+ float value)
+{
+ float K = tanf(sample_time / (2.0f * tau));
+ float poly = K * K + K / Q + 1.0f;
+ filter->a[0] = 2.0f * (K * K - 1.0f) / poly;
+ filter->a[1] = (K * K - K / Q + 1.0f) / poly;
+ filter->b[0] = K * K / poly;
+ filter->b[1] = 2.0f * filter->b[0];
+ filter->i[0] = filter->i[1] = filter->o[0] = filter->o[1] = value;
+}
+
+/** Update second order low pass filter state with a new value.
+ *
+ * @param filter second order low pass filter structure
+ * @param value new input value of the filter
+ * @return new filtered value
+ */
+static inline float update_second_order_low_pass(struct SecondOrderLowPass *filter, float value)
+{
+ float out = filter->b[0] * value
+ + filter->b[1] * filter->i[0]
+ + filter->b[0] * filter->i[1]
+ - filter->a[0] * filter->o[0]
+ - filter->a[1] * filter->o[1];
+ filter->i[1] = filter->i[0];
+ filter->i[0] = value;
+ filter->o[1] = filter->o[0];
+ filter->o[0] = out;
+ return out;
+}
+
+/** Get current value of the second order low pass filter.
+ *
+ * @param filter second order low pass filter structure
+ * @return current value of the filter
+ */
+static inline float get_second_order_low_pass(struct SecondOrderLowPass *filter)
+{
+ return filter->o[0];
+}
+
+struct SecondOrderLowPass_int {
+ int32_t a[2]; ///< denominator gains
+ int32_t b[2]; ///< numerator gains
+ int32_t i[2]; ///< input history
+ int32_t o[2]; ///< output history
+ int32_t loop_gain; ///< loop gain
+};
+
+/** Second order Butterworth low pass filter.
+ */
+typedef struct SecondOrderLowPass Butterworth2LowPass;
+
+/** Init a second order Butterworth filter.
+ *
+ * based on the generic second order filter
+ * with Q = 0.7071 = 1/sqrt(2)
+ *
+ * http://en.wikipedia.org/wiki/Butterworth_filter
+ *
+ * @param filter second order Butterworth low pass filter structure
+ * @param tau time constant of the second order low pass filter
+ * @param sample_time sampling period of the signal
+ * @param value initial value of the filter
+ */
+static inline void init_butterworth_2_low_pass(Butterworth2LowPass *filter, float tau, float sample_time, float value)
+{
+ init_second_order_low_pass((struct SecondOrderLowPass *)filter, tau, 0.7071, sample_time, value);
+}
+
+/** Update second order Butterworth low pass filter state with a new value.
+ *
+ * @param filter second order Butterworth low pass filter structure
+ * @param value new input value of the filter
+ * @return new filtered value
+ */
+static inline float update_butterworth_2_low_pass(Butterworth2LowPass *filter, float value)
+{
+ return update_second_order_low_pass((struct SecondOrderLowPass *)filter, value);
+}
+
+/** Get current value of the second order Butterworth low pass filter.
+ *
+ * @param filter second order Butterworth low pass filter structure
+ * @return current value of the filter
+ */
+static inline float get_butterworth_2_low_pass(Butterworth2LowPass *filter)
+{
+ return filter->o[0];
+}
+
+#endif //FILTER_H_
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve.h
new file mode 100644
index 0000000..0f37fb9
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve.h
@@ -0,0 +1,46 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * kveStorage.h - Low level storage functions
+ *
+ */
+
+#pragma once
+
+#include "kve/kve_common.h"
+
+#include <stddef.h>
+#include <stdbool.h>
+
+void kveDefrag(kveMemory_t *kve);
+
+bool kveStore(kveMemory_t *kve, char* key, const void* buffer, size_t length);
+
+size_t kveFetch(kveMemory_t *kve, const char* key, void* buffer, size_t bufferLength);
+
+bool kveDelete(kveMemory_t *kve, char* key);
+
+void kveFormat(kveMemory_t *kve);
+
+bool kveCheck(kveMemory_t *kve);
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve_common.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve_common.h
new file mode 100644
index 0000000..6164dec
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve_common.h
@@ -0,0 +1,38 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * kve_common.h - Common type definition for kve
+ *
+ */
+
+#pragma once
+
+#include <stddef.h>
+
+typedef struct {
+ size_t memorySize;
+ size_t (*read)(size_t address, void* data, size_t length);
+ size_t (*write)(size_t address, const void* data, size_t length);
+ void (*flush)(void);
+} kveMemory_t;
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve_storage.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve_storage.h
new file mode 100644
index 0000000..1225b37
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/kve/kve_storage.h
@@ -0,0 +1,111 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * kveStorage.h - Low level storage functions
+ *
+ */
+
+/**
+ * These functions are intended to be used insternally by the embedded
+ * key-value module. They are not intended to be used by any other
+ * modules.
+ */
+
+#pragma once
+
+#include "kve/kve_common.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+
+#define KVE_STORAGE_IS_VALID(a) (a != SIZE_MAX)
+
+#define KVE_STORAGE_INVALID_ADDRESS (SIZE_MAX)
+
+#define END_TAG_LENDTH 2
+
+typedef struct itemHeader_s {
+ uint16_t full_length;
+ uint8_t key_length;
+} __attribute((packed)) kveItemHeader_t;
+
+/** Add the item at address "address"
+ *
+ * This is a utility function that does not check for anything, the caller is
+ * responsible for checking that no access after the end of the memory is made
+ *
+ * Return the full length of the item in memory
+ */
+int kveStorageWriteItem(kveMemory_t *kve, size_t address, const char* key, const void* buffer, size_t length);
+
+/** Write holes spanning full_length at address
+ *
+ * The hole MUST be at least 3 bytes wide. No check is done in this function!
+ *
+ * Return the full length of the item in memory
+ */
+uint16_t kveStorageWriteHole(kveMemory_t *kve, size_t address, size_t full_length);
+
+/** Write end the the table at address
+ *
+ * No check is done in this function, there should be
+ * at least 2 bytes available at address
+ *
+ * Return the full length of the item in memory
+ */
+uint16_t kveStorageWriteEnd(kveMemory_t *kve, size_t address);
+
+/** Move a block of memory from an address to another
+ *
+ * Source address MUST be > than destination address
+ */
+void kveStorageMoveMemory(kveMemory_t *kve, size_t sourceAddress, size_t destinationAddress, size_t length);
+
+size_t kveStorageFindItemByKey(kveMemory_t *kve, size_t address, const char * key);
+
+/** Find and return the address of the end of table
+ *
+ * Address can be set to the begining of an item to start the search
+ * in the middle of the table.
+ *
+ * This function return an invalid address if the end of the memory
+ * is reached before finding the end tag. If that appens, the table
+ * is corrupted! (good for checking the health of the kve table)
+ */
+size_t kveStorageFindEnd(kveMemory_t *kve, size_t address);
+
+size_t kveStorageFindHole(kveMemory_t *kve, size_t address);
+
+size_t kveStorageFindNextItem(kveMemory_t *kve, size_t address);
+
+kveItemHeader_t kveStorageGetItemInfo(kveMemory_t *kve, size_t address);
+
+size_t kveStorageGetKeyLength(kveItemHeader_t header);
+
+size_t kveStorageGetBufferLength(kveItemHeader_t header);
+
+size_t kveStorageGetKey(kveMemory_t *kve, size_t address, kveItemHeader_t header, char* key, size_t maxLength);
+
+size_t kveStorageGetBuffer(kveMemory_t *kve, size_t address, kveItemHeader_t header, void* buffer, size_t maxLength);
\ No newline at end of file
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/lighthouse_calibration.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/lighthouse_calibration.h
new file mode 100644
index 0000000..80ce022
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/lighthouse_calibration.h
@@ -0,0 +1,88 @@
+#pragma once
+
+#include "ootx_decoder.h"
+
+typedef struct {
+ float phase;
+ float tilt;
+ float curve;
+ float gibmag;
+ float gibphase;
+ // Lh2 extra params
+ float ogeemag;
+ float ogeephase;
+} __attribute__((packed)) lighthouseCalibrationSweep_t;
+
+typedef struct {
+ lighthouseCalibrationSweep_t sweep[2];
+ bool valid;
+} __attribute__((packed)) lighthouseCalibration_t;
+
+/**
+ * @brief Initialize calibration structure from basestation ootx frame
+ *
+ * @param calib Calibration object to initialize, calib->valid will be set to true
+ * @param frame ootx frame received from the basestation
+ */
+void lighthouseCalibrationInitFromFrame(lighthouseCalibration_t *calib, struct ootxDataFrame_s *frame);
+
+/**
+ * @brief Apply basestation calibration to the two received angles for LH 1
+ *
+ * @param calib Calibration object to use
+ * @param rawAngles Array containing the two raw measured angles
+ * @param correctedAngles Array containing the two corrected angles after applying calibration
+ */
+void lighthouseCalibrationApplyV1(const lighthouseCalibration_t* calib, const float* rawAngles, float* correctedAngles);
+
+/**
+ * @brief Apply basestation calibration to the two received angles for LH 2
+ *
+ * @param calib Calibration object to use
+ * @param rawAngles Array containing the two raw measured angles
+ * @param correctedAngles Array containing the two corrected angles after applying calibration
+ */
+void lighthouseCalibrationApplyV2(const lighthouseCalibration_t* calib, const float* rawAngles, float* correctedAngles);
+
+/**
+ * @brief Apply no basestation calibration to the two received angles, that is copy the raw angles
+ *
+ * @param rawAngles i/j raw angles measured
+ * @param correctedAngles i/j will be same as the raw angles
+ */
+void lighthouseCalibrationApplyNothing(const float rawAngles[2], float correctedAngles[2]);
+
+/**
+ * @brief Generic function pointer type for a calibration measurement model.
+ * Predict the measured sweep angle based on a position for a lighthouse rotor. The position is relative to the rotor reference frame.
+ * @param x meters
+ * @param y meters
+ * @param z meters
+ * @param t Tilt of the light plane in radians
+ * @param calib Calibration data for the rotor
+ * @return float The predicted uncompensated sweep angle of the rotor
+ *
+ */
+typedef float (*lighthouseCalibrationMeasurementModel_t)(const float x, const float y, const float z, const float t, const lighthouseCalibrationSweep_t* calib);
+
+/**
+ * @brief Predict the measured sweep angle based on a position for a lighthouse 1 rotor. The position is relative to the rotor reference frame.
+ * @param x meters
+ * @param y meters
+ * @param z meters
+ * @param t Tilt of the light plane in radians - not used in LH1, will always use 0
+ * @param calib Calibration data for the rotor
+ * @return float The predicted uncompensated sweep angle of the rotor
+ */
+float lighthouseCalibrationMeasurementModelLh1(const float x, const float y, const float z, const float t, const lighthouseCalibrationSweep_t* calib);
+
+/**
+ * @brief Predict the measured sweep angle based on a position for a lighthouse 2 rotor. The position is relative to the rotor reference frame.
+ * @param x meters
+ * @param y meters
+ * @param z meters
+ * @param t Tilt of the light plane in radians
+ * @param calib Calibration data for the rotor
+ * @return float The predicted uncompensated sweep angle of the rotor
+ */
+float lighthouseCalibrationMeasurementModelLh2(const float x, const float y, const float z, const float t, const lighthouseCalibrationSweep_t* calib);
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/lighthouse_geometry.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/lighthouse_geometry.h
new file mode 100644
index 0000000..71fc157
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/lighthouse_geometry.h
@@ -0,0 +1,84 @@
+#pragma once
+
+#include <stdbool.h>
+#include "xtensa_math.h"
+#include "stabilizer_types.h"
+
+typedef struct {
+ __attribute__((aligned(4))) vec3d origin;
+ __attribute__((aligned(4))) mat3d mat;
+ bool valid;
+} __attribute__((packed)) baseStationGeometry_t;
+
+typedef struct {
+ __attribute__((aligned(4))) mat3d baseStationInvertedRotationMatrixes;
+ __attribute__((aligned(4))) mat3d lh1Rotor2RotationMatrixes;
+ __attribute__((aligned(4))) mat3d lh1Rotor2InvertedRotationMatrixes;
+} baseStationGeometryCache_t;
+
+/**
+ * @brief Find closest point between rays from two bases stations.
+ *
+ * @param baseStations - Geometry data for the two base statsions (position and orientation)
+ * @param angles1 - array with 2 angles, horizontal and vertical sweep angle for base station 1
+ * @param angles2 - array with 2 angles, horizontal and vertical sweep angle for base station 2
+ * @param position - (output) the closest point between the rays
+ * @param postion_delta - (output) the distance between the rays at the closest point
+ */
+bool lighthouseGeometryGetPositionFromRayIntersection(const baseStationGeometry_t baseStations[2], float angles1[2], float angles2[2], vec3d position, float *position_delta);
+
+/**
+ * @brief Get the base station position from the base station geometry in world reference frame. This position can be seen as the
+ * point where the lazers originate from.
+ *
+ * @param baseStation - Geometry data for the base statsion (position and orientation)
+ * @param baseStationPos - (output) the base station position
+ */
+void lighthouseGeometryGetBaseStationPosition(const baseStationGeometry_t* baseStationGeometry, vec3d baseStationPos);
+
+/**
+ * @brief Get a normalized vector representing the direction of a ray in world reference frame, based on
+ * sweep angles and base station orientation.
+ *
+ * @param baseStation - Geometry data for the base statsion (position and orientation)
+ * @param angle1 - horizontal sweep angle
+ * @param angle2 - vertical sweep angle
+ * @param ray - (output) the resulting normalized vector
+ */
+void lighthouseGeometryGetRay(const baseStationGeometry_t* baseStationGeometry, const float angle1, const float angle2, vec3d ray);
+
+/**
+ * @brief Calculates the intersection point between a plane and a line
+ *
+ * @param linePoint - a point on the line
+ * @param lineVec - a normalized vector in the direction of the line
+ * @param planePoint - a point in the plane
+ * @param PlaneNormal - the normal to the plane (normalized)
+ * @param intersectionPoint - (output) the intersection point
+ * @return true if an intersection exists
+ */
+bool lighthouseGeometryIntersectionPlaneVector(const vec3d linePoint, const vec3d lineVec, const vec3d planePoint, const vec3d PlaneNormal, vec3d intersectionPoint);
+
+/**
+ * @brief Calculate the position of a sensor on the deck in world reference frame.
+ * Note: the origin of the Crazyflie is set in the center of the deck
+ *
+ * @param cfPos - Crazyflie position
+ * @param R - Crazyflie rotation matrix
+ * @param sensorPosition - the sensor position relative to the center of the Crazyflie
+ * @param pos - (output) the position of the sensor
+ */
+void lighthouseGeometryGetSensorPosition(const vec3d cfPos, const arm_matrix_instance_f32 *R, vec3d sensorPosition, vec3d pos);
+
+/**
+ * @brief Calculate the angle between two vectors. The vectors are assumed to be in a plane defined by
+ * a normal and represent the distance between intersection points and sensor points on a lighthouse deck.
+ *
+ * @param ipv - vector between intersection points
+ * @param spv - vector between sensor points
+ * @param n - normal to the plane (normalized)
+ * @param yawDelta - (output) the angle between the vectors
+ *
+ * @return true if the angle could be calculated
+*/
+bool lighthouseGeometryYawDelta(const vec3d ipv, const vec3d spv, const vec3d n, float* yawDelta);
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/ootx_decoder.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/ootx_decoder.h
new file mode 100644
index 0000000..3071df9
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/ootx_decoder.h
@@ -0,0 +1,100 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * ootx_decoder.h - lighthouse positioning ootx (slow) data receiver
+ *
+ */
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+
+#define OOTX_MAX_FRAME_LENGTH 43
+
+// Content from https://github.com/nairol/LighthouseRedox/blob/master/docs/Base%20Station.md#base-station-info-block
+struct ootxDataFrame_s {
+ uint16_t protocolVersion:6;
+ uint16_t firmwareVersion:10;
+ uint32_t id;
+ __fp16 phase0;
+ __fp16 phase1;
+ __fp16 tilt0;
+ __fp16 tilt1;
+ uint8_t unlockCount;
+ uint8_t hwVersion;
+ __fp16 curve0;
+ __fp16 curve1;
+ int8_t accelX;
+ int8_t accelY;
+ int8_t accelZ;
+ __fp16 gibphase0;
+ __fp16 gibphase1;
+ __fp16 gibmag0;
+ __fp16 gibmag1;
+ uint8_t mode;
+ uint8_t faults;
+
+ // Only used in LH 2 that uses a longer data block
+ __fp16 ogeephase0;
+ __fp16 ogeephase1;
+ __fp16 ogeemag0;
+ __fp16 ogeemag1;
+} __attribute__((packed));
+
+typedef struct ootxDecoderState_s {
+ int frameLength;
+ int bytesReceived;
+
+ uint16_t currentWord;
+
+ uint32_t crc32;
+
+ int bitInWord;
+ int wordReceived;
+ bool synchronized;
+ int nZeros;
+ enum {rxLength, rxData, rxCrc0, rxCrc1, rxDone} rxState;
+
+ union {
+ uint16_t data[(OOTX_MAX_FRAME_LENGTH+1) / 2];
+ struct ootxDataFrame_s frame;
+ };
+} ootxDecoderState_t;
+
+/**
+ * @brief Process the next OOTX bit and indicate if a frame has been decoded
+ *
+ * If a frame is decoded, this function returns true and the
+ * frame is available in state->frame
+ *
+ * Currently the CRC32 checksum of the frame is not checked!
+ *
+ * @param state Pointer to the decoder state
+ * @param data OOTX data bit, should be 0 or 1
+ * @return true If a frame has been decoded (ie at the last bit of the frame)
+ * @return false If no frame has been decoded yet
+ */
+bool ootxDecoderProcessBit(ootxDecoderState_t * state, int data);
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor.h
new file mode 100644
index 0000000..d882e94
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor.h
@@ -0,0 +1,299 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * pulse_processor.h - pulse decoding for lighthouse V1 base stations
+ *
+ */
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "ootx_decoder.h"
+#include "lighthouse_calibration.h"
+#include "lighthouse_geometry.h"
+
+#define PULSE_PROCESSOR_N_SWEEPS 2
+#define PULSE_PROCESSOR_N_BASE_STATIONS 2
+#define PULSE_PROCESSOR_N_SENSORS 4
+#define PULSE_PROCRSSOR_N_CONCURRENT_BLOCKS 2
+#define PULSE_PROCESSOR_N_WORKSPACE (PULSE_PROCESSOR_N_SENSORS * PULSE_PROCRSSOR_N_CONCURRENT_BLOCKS)
+
+#define PULSE_PROCESSOR_HISTORY_LENGTH 8
+#define PULSE_PROCESSOR_TIMESTAMP_BITWIDTH 24
+#define PULSE_PROCESSOR_TIMESTAMP_MAX ((1 << PULSE_PROCESSOR_TIMESTAMP_BITWIDTH) - 1)
+#define PULSE_PROCESSOR_TIMESTAMP_BITMASK PULSE_PROCESSOR_TIMESTAMP_MAX
+
+// Utility functions and macros
+
+/**
+ * @brief Difference of two timestamps, truncated to time stamp bit width (PULSE_PROCESSOR_TIMESTAMP_BITWIDTH)
+ *
+ * @param x A timestamp
+ * @param y A teimstamp
+ * @return x - y, truncated
+ */
+inline static uint32_t TS_DIFF(const uint32_t x, const uint32_t y) {
+ return (x - y) & PULSE_PROCESSOR_TIMESTAMP_BITMASK;
+}
+
+/**
+ * @brief Check if abs(a - b) > limit. Works for timestampa where the bitwidth is PULSE_PROCESSOR_TIMESTAMP_BITWIDTH
+ *
+ * @param a A timestamp
+ * @param b A timestamp
+ * @param limit The minimum difference between a nd b
+ * @return true if abs(a - b) > limit
+ */
+inline static uint32_t TS_ABS_DIFF_LARGER_THAN(const uint32_t a, const uint32_t b, const uint32_t limit) {
+ return TS_DIFF(a + limit, b) > (limit * 2);
+}
+
+
+/**
+ * @brief Data for one pulse, detected by one sensor and decoded by the FPGA on the dack.
+ * Used both for lighthouse V1 and V2.
+ *
+ */
+typedef struct {
+ uint8_t sensor;
+ uint32_t timestamp;
+
+ // V1 base station data --------
+ uint16_t width;
+
+ // V2 base station data --------
+ uint32_t beamData;
+ uint32_t offset;
+ // Channel is zero indexed (0-15) here, while it is one indexed in the base station config (1 - 16)
+ uint8_t channel; // Valid if channelFound is true
+ uint8_t slowbit; // Valid if channelFound is true
+ bool channelFound;
+} pulseProcessorFrame_t;
+
+typedef enum {
+ lighthouseBsTypeUnknown = 0,
+ lighthouseBsTypeV1 = 1,
+ lighthouseBsTypeV2 = 2,
+} lighthouseBaseStationType_t;
+
+enum pulseClass_e {unknown, sync0, sync1, sweep};
+
+typedef struct {
+ uint32_t timestamp;
+ int width;
+} pulseProcessorPulse_t;
+
+typedef enum {
+ sweepIdFirst = 0, // The X sweep in LH 1
+ sweepIdSecond = 1 // The Y sweep in LH 1
+} SweepId_t;
+
+typedef enum {
+ sweepStorageStateWaiting = 0,
+ sweepStorageStateValid,
+ sweepStorageStateError,
+} SweepStorageState_t;
+
+/**
+ * @brief Holds data for V1 base station decoding
+ *
+ */
+typedef struct {
+ bool synchronized; // At true if we are currently syncthonized
+ int basestationsSynchronizedCount;
+
+ // Synchronization state
+ pulseProcessorPulse_t pulseHistory[PULSE_PROCESSOR_N_SENSORS][PULSE_PROCESSOR_HISTORY_LENGTH];
+ int pulseHistoryIdx[PULSE_PROCESSOR_N_SENSORS];
+
+
+ // Sync pulse timestamp estimation
+ uint32_t lastSync; // Last sync seen
+ uint64_t currentSyncSum; // Sum of the timestamps of all the close-together sync
+ int nSyncPulses; // Number of sync pulses accumulated
+
+ // Sync pulse timestamps
+ uint32_t currentSync; // Sync currently used for sweep phase measurement
+ uint32_t currentSync0; // Sync0 of the current frame
+ uint32_t currentSync0Width; // Width of sync0 in the current frame
+ uint32_t currentSync1Width; // Width of sync1 in the current frame
+
+ uint32_t currentSync0X;
+ uint32_t currentSync0Y;
+ uint32_t currentSync1X;
+ uint32_t currentSync1Y;
+
+ float frameWidth[2][2];
+
+ // Base station and axis of the current frame
+ int currentBaseStation;
+ SweepId_t currentAxis;
+
+ // Sweep timestamps
+ struct {
+ uint32_t timestamp;
+ SweepStorageState_t state;
+ } sweeps[PULSE_PROCESSOR_N_SENSORS];
+ bool sweepDataStored;
+} pulseProcessorV1_t;
+
+
+/**
+ * @brief Raw pulse data from the sensors. Data for pulses that are close in time and probably
+ * comes from the same sweep. May contain pulse data from multiple base stations.
+ *
+ */
+typedef struct {
+ pulseProcessorFrame_t slots[PULSE_PROCESSOR_N_WORKSPACE];
+ int slotsUsed;
+ uint32_t latestTimestamp;
+} pulseProcessorV2PulseWorkspace_t;
+
+/**
+ * @brief Holds derived data for one sweep through all sensors, derived from the pulses
+ *
+ */
+typedef struct {
+ uint32_t offset[PULSE_PROCESSOR_N_SENSORS];
+ uint32_t timestamp0; // Timestamp of when the rotor has offset 0 (0 degrees)
+ uint8_t channel;
+} pulseProcessorV2SweepBlock_t;
+
+/**
+ * @brief Blocks used when decoding the pulse workspace
+ *
+ */
+typedef struct {
+ pulseProcessorV2SweepBlock_t blocks[PULSE_PROCRSSOR_N_CONCURRENT_BLOCKS];
+} pulseProcessorV2BlockWorkspace_t;
+
+/**
+ * @brief Holds data for V2 base station decoding
+ *
+ */
+typedef struct {
+ pulseProcessorV2PulseWorkspace_t pulseWorkspace;
+ pulseProcessorV2BlockWorkspace_t blockWorkspace;
+
+ // Latest block from each base station. Used to pair both blocks (sweeps) from one rotaion of the rotor.
+ pulseProcessorV2SweepBlock_t blocks[PULSE_PROCESSOR_N_BASE_STATIONS];
+
+ // Timestamp of the rotor zero position for the latest processed slowbit
+ uint32_t ootxTimestamps[PULSE_PROCESSOR_N_BASE_STATIONS];
+} pulseProcessorV2_t;
+
+typedef struct pulseProcessor_s {
+ bool receivedBsSweep[PULSE_PROCESSOR_N_BASE_STATIONS];
+
+ union {
+ struct {
+ pulseProcessorV1_t v1;
+ };
+
+ struct {
+ pulseProcessorV2_t v2;
+ };
+ };
+
+ ootxDecoderState_t ootxDecoder[PULSE_PROCESSOR_N_BASE_STATIONS];
+ lighthouseCalibration_t bsCalibration[PULSE_PROCESSOR_N_BASE_STATIONS];
+ baseStationGeometry_t bsGeometry[PULSE_PROCESSOR_N_BASE_STATIONS];
+ baseStationGeometryCache_t bsGeoCache[PULSE_PROCESSOR_N_BASE_STATIONS];
+
+ // Health check data
+ uint32_t healthFirstSensorTs;
+ uint8_t healthSensorBitField;
+ bool healthDetermined;
+} pulseProcessor_t;
+
+typedef struct {
+ float angles[PULSE_PROCESSOR_N_SWEEPS];
+ float correctedAngles[PULSE_PROCESSOR_N_SWEEPS];
+ int validCount;
+} pulseProcessorBaseStationMeasuremnt_t;
+
+typedef struct {
+ pulseProcessorBaseStationMeasuremnt_t baseStatonMeasurements[PULSE_PROCESSOR_N_BASE_STATIONS];
+} pulseProcessorSensorMeasurement_t;
+
+typedef struct {
+ pulseProcessorSensorMeasurement_t sensorMeasurementsLh1[PULSE_PROCESSOR_N_SENSORS];
+ pulseProcessorSensorMeasurement_t sensorMeasurementsLh2[PULSE_PROCESSOR_N_SENSORS];
+ lighthouseBaseStationType_t measurementType;
+} pulseProcessorResult_t;
+
+/**
+ * @brief Interface for processing of pulse data from the lighthouse
+ *
+ * @param state
+ * @param frameData
+ * @param baseStation
+ * @param axis
+ * @return true, angle, base station and axis are written
+ * @return false, no valid result
+ */
+typedef bool (*pulseProcessorProcessPulse_t)(pulseProcessor_t *state, const pulseProcessorFrame_t* frameData, pulseProcessorResult_t* angles, int *baseStation, int *axis);
+
+/**
+ * @brief Apply calibration correction to all angles of all sensors for a particular baseStation
+ *
+ * @param state
+ * @param angles
+ * @param baseStation
+ */
+void pulseProcessorApplyCalibration(pulseProcessor_t *state, pulseProcessorResult_t* angles, int baseStation);
+
+void pulseProcessorClearOutdated(pulseProcessor_t *appState, pulseProcessorResult_t* angles, int basestation);
+
+/**
+ * @brief Clear the result struct for one base station when the data is processed and converted to measurements
+ *
+ * @param angles The result struct to clear
+ * @param baseStation The base station
+ */
+void pulseProcessorProcessed(pulseProcessorResult_t* angles, int baseStation);
+
+/**
+ * @brief Clear the result struct for one base station when the sensor data invalidated
+ *
+ * @param angles The result struct to clear
+ * @param baseStation The base station
+ */
+void pulseProcessorClear(pulseProcessorResult_t* angles, int baseStation);
+
+/**
+ * @brief Clear result struct when the sensor data is invalidated
+ *
+ * @param angles
+ */
+void pulseProcessorAllClear(pulseProcessorResult_t* angles);
+
+/**
+ * Get quality of angles reception of the basestations.
+ * 0 means no angles, 255 means reception of all angles of all axis of all basestations.
+ */
+uint8_t pulseProcessorAnglesQuality();
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor_v1.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor_v1.h
new file mode 100644
index 0000000..50e7e42
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor_v1.h
@@ -0,0 +1,52 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * pulse_processor_v1.h - pulse decoding for lighthouse V1 base stations
+ *
+ */
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "pulse_processor.h"
+
+
+/**
+ * @brief Process pulse data from a lighthouse V1 system
+ *
+ * @param state
+ * @param frameData
+ * @param baseStation
+ * @param axis
+ * @return true, angle, base station and axis are written
+ * @return false, no valid result
+ */
+bool pulseProcessorV1ProcessPulse(pulseProcessor_t *state, const pulseProcessorFrame_t* frameData, pulseProcessorResult_t* angles, int *baseStation, int *axis);
+
+void pulseProcessorV1ProcessValidAngles(pulseProcessorResult_t* angles, int basestation);
+
+uint8_t pulseProcessorV1AnglesQuality();
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor_v2.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor_v2.h
new file mode 100644
index 0000000..f87e32d
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/lighthouse/pulse_processor_v2.h
@@ -0,0 +1,59 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * pulse_processor_v2.h - pulse decoding for lighthouse V2 base stations
+ *
+ */
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "pulse_processor.h"
+
+
+/**
+ * @brief Process pulse data from a lighthouse V2 system
+ *
+ * @param state
+ * @param frameData
+ * @param baseStation
+ * @param axis
+ * @return true, angle, base station and axis are written
+ * @return false, no valid result
+ */
+bool pulseProcessorV2ProcessPulse(pulseProcessor_t *state, const pulseProcessorFrame_t* frameData, pulseProcessorResult_t* angles, int *baseStation, int *axis);
+
+/**
+ * @brief Convert Lighthouse v2 angles to Lighthouse V1 angles
+ *
+ * @param v2Angle1 First LH V2 angle
+ * @param v2Angle2 Second LH V2 angle
+ * @param v1Angles The resulting V1 angles
+ */
+void pulseProcessorV2ConvertToV1Angles(const float v2Angle1, const float v2Angle2, float* v1Angles);
+
+uint8_t pulseProcessorV2AnglesQuality();
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/num.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/num.h
new file mode 100644
index 0000000..c1e8b07
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/num.h
@@ -0,0 +1,39 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2012-2016 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * num.c - 16bit floating point handling functions
+ */
+
+#ifndef __NUM_H
+#define __NUM_H
+
+#include <stdint.h>
+
+uint16_t single2half(float number);
+float half2single(uint16_t number);
+
+uint16_t limitUint16(int32_t value);
+float constrain(float value, const float minVal, const float maxVal);
+float deadband(float value, const float threshold);
+
+#endif
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/physicalConstants.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/physicalConstants.h
new file mode 100644
index 0000000..c8dfe75
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/physicalConstants.h
@@ -0,0 +1,49 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#pragma once
+
+#define SPEED_OF_LIGHT (299792458.0)
+#define GRAVITY_MAGNITUDE (9.81f)
+
+#ifndef M_PI
+ #define M_PI 3.14159265358979323846
+#endif
+
+#ifndef M_PI_F
+ #define M_PI_F (3.14159265358979323846f)
+#endif
+
+#ifndef M_1_PI_F
+ #define M_1_PI_F (0.31830988618379067154f)
+#endif
+
+#ifndef M_PI_2_F
+ #define M_PI_2_F (1.57079632679f)
+#endif
+
+#ifndef CF_MASS
+ #define CF_MASS (0.027f) // in kg
+#endif
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/rateSupervisor.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/rateSupervisor.h
new file mode 100644
index 0000000..b6ecfc5
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/rateSupervisor.h
@@ -0,0 +1,73 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * rateSupervisor.h - functionality to supervise the rate of modules
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <stdbool.h>
+
+typedef struct {
+ uint32_t count;
+ uint32_t expectedMin;
+ uint32_t expectedMax;
+ uint32_t nextEvaluationTimeMs;
+ uint32_t evaluationIntervalMs;
+ uint32_t latestCount;
+ uint8_t skip;
+} rateSupervisor_t;
+
+/**
+ * @brief Initialize a rateSupervisor_t struct for rate measurements
+ *
+ * @param context The struct to initialize
+ * @param osTimeMs The current os time in ms
+ * @param evaluationIntervalMs How often to evaluate the rate, in ms
+ * @param minCount The minimum number of validations we expect every evaluation interval
+ * @param maxCount The maximum number of validations we expect every evaluation interval
+ * @param skip The number of inital evaluations to ignore failures for. This is a convenient way to let the system warm up a bit before reporting problems.
+ */
+void rateSupervisorInit(rateSupervisor_t* context, const uint32_t osTimeMs, const uint32_t evaluationIntervalMs, const uint32_t minCount, const uint32_t maxCount, const uint8_t skip);
+
+/**
+ * @brief Validate the rate for a process. This function should be called from the process for which the rate
+ * is to be supervised. When the function is called a counter is increased, and if the evaluation period
+ * has passed, the rate is evaluated.
+ *
+ * @param context A rateSupervisor_t
+ * @param osTimeMs The current os time in ms
+ * @return true if the measured rate is within bounds, or we have not yet reached the next evaluation time
+ * @return false if the measured rate is too low or high
+ */
+bool rateSupervisorValidate(rateSupervisor_t* context, const uint32_t osTimeMs);
+
+/**
+ * @brief Get the latest count. Useful to display the count after a failed validation.
+ *
+ * @param context A rateSupervisor_t
+ * @return uint32_t The count at the latest evaluation time
+ */
+uint32_t rateSupervisorLatestCount(rateSupervisor_t* context);
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/sleepus.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/sleepus.h
new file mode 100644
index 0000000..5d46636
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/sleepus.h
@@ -0,0 +1,31 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2012 BitCraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * sleepus.h: Micro second sleep
+ */
+#ifndef __SLEEPNS_H__
+#define __SLEEPNS_H__
+
+void sleepus(uint32_t ns);
+
+#endif // __SLEEPNS_H__
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/statsCnt.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/statsCnt.h
new file mode 100644
index 0000000..3d0a831
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/statsCnt.h
@@ -0,0 +1,124 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * statsCnt.h - utitlity for logging rates
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include "log.h"
+
+/**
+ * @brief A struct used to track event rates
+ */
+typedef struct {
+ uint32_t count;
+ uint32_t latestCount;
+ uint32_t latestAveragingMs;
+ float latestRate;
+ uint32_t intervalMs;
+} statsCntRateCounter_t;
+
+/**
+ * @brief Initialize a statsCntRateLogger_t struct.
+ *
+ * @param logger The rste counter to initialize
+ * @param averagingIntervalMs The interval (in ms) between rate calculations
+ */
+void statsCntRateCounterInit(statsCntRateCounter_t* counter, uint32_t averagingIntervalMs);
+
+/**
+ * @brief A new rate is calculated if the time since the previous calculation is longer
+ * than the configured interval time.
+ *
+ * @param counter The rate counter to update
+ * @param now_ms Current system time in ms
+ * @return float The latest calculated rate
+ */
+float statsCntRateCounterUpdate(statsCntRateCounter_t* counter, uint32_t now_ms);
+
+
+// Log module integration -------------------------------------------------------
+
+/**
+ * @brief Struct to use a rate counter together with the log usb system.
+ */
+typedef struct {
+ // logByFunction_t must be the first element in this struct since pointers
+ // to this struct are cast to logByFunction_t* and used by the log module
+ logByFunction_t logByFunction;
+ statsCntRateCounter_t rateCounter;
+} statsCntRateLogger_t;
+
+/**
+ * @brief Macro to initialize a statsCntRateLogger_t struct.
+ *
+ * @param LOGGER A pointer to a statsCntRateLogger_t
+ * @param INTERVAL_MS The interval (in ms) between calculations of the rate
+ */
+#define STATS_CNT_RATE_INIT(LOGGER, INTERVAL_MS) statsCntRateLoggerInit(LOGGER, INTERVAL_MS)
+
+#define STATS_CNT_RATE_DEFINE(NAME, INTERVAL_MS) statsCntRateLogger_t NAME = {.logByFunction = {.data = &NAME, .aquireFloat = statsCntRateLogHandler}, .rateCounter = {.intervalMs = (INTERVAL_MS), .count = 0, .latestCount = 0, .latestAveragingMs = 0, .latestRate = 0}}
+
+/**
+ * @brief Macro to add an event to a statsCntRateLogger_t, that is to increase the internal counter
+ *
+ * @param LOGGER A pointer to a statsCntRateLogger_t
+ */
+#define STATS_CNT_RATE_EVENT(LOGGER) ((LOGGER)->rateCounter.count++)
+
+/**
+ * @brief Macro to add CNT events to a statsCntRateLogger_t, that is to increase the internal counter with CNT
+ *
+ * @param LOGGER A pointer to a statsCntRateLogger_t
+ * @param CNT Number of counts to add
+ */
+#define STATS_CNT_RATE_MULTI_EVENT(LOGGER, CNT) ((LOGGER)->rateCounter.count += CNT)
+
+/**
+ * @brief Macro to add a statsCntRateLogger_t as a rate log. Used in a similar way as
+ * LOG_ADD() in a LOG_GROUP_START() - LOG_GROUP_STOP() block
+ *
+ * @param LOGGER A pointer to a statsCntRateLogger_t
+ */
+#define STATS_CNT_RATE_LOG_ADD(NAME, LOGGER) LOG_ADD_BY_FUNCTION(LOG_FLOAT, NAME, LOGGER)
+
+/**
+ * @brief Initialize a statsCntRateLogger_t struct.
+ *
+ * @param logger The rste counter to initialize
+ * @param averagingIntervalMs The interval (in ms) between rate calculations
+ */
+void statsCntRateLoggerInit(statsCntRateLogger_t* logger, uint32_t averagingIntervalMs);
+
+/**
+ * @brief Handler function used by the log module to acquire log values.
+ * Calls statsCntRateCounterUpdate() to update the logger and acqure the rate.
+ *
+ * @param timestamp Current system time,in ms
+ * @param data Pointer to a statsCntRateLogger_t
+ * @return float The latest calculated rate
+ */
+float statsCntRateLogHandler(uint32_t timestamp, void* data);
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaEngine.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaEngine.h
new file mode 100644
index 0000000..ab5b223
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaEngine.h
@@ -0,0 +1,24 @@
+#ifndef __TDOA_ENGINE_H__
+#define __TDOA_ENGINE_H__
+
+#include "tdoaStorage.h"
+#include "tdoaStats.h"
+
+typedef void (*tdoaEngineSendTdoaToEstimator)(tdoaMeasurement_t* tdoaMeasurement);
+
+typedef struct {
+ // State
+ tdaoAnchorInfoArray_t anchorInfoArray;
+ tdoaStats_t stats;
+
+ // Configuration
+ tdoaEngineSendTdoaToEstimator sendTdoaToEstimator;
+ double locodeckTsFreq;
+} tdoaEngineState_t;
+
+void tdoaEngineInit(tdoaEngineState_t* state, const uint32_t now_ms, tdoaEngineSendTdoaToEstimator sendTdoaToEstimator, const double locodeckTsFreq);
+
+void tdoaEngineGetAnchorCtxForPacketProcessing(tdoaEngineState_t* engineState, const uint8_t anchorId, const uint32_t currentTime_ms, tdoaAnchorContext_t* anchorCtx);
+void tdoaEngineProcessPacket(tdoaEngineState_t* engineState, tdoaAnchorContext_t* anchorCtx, const int64_t txAn_in_cl_An, const int64_t rxAn_by_T_in_cl_T);
+
+#endif // __TDOA_ENGINE_H__
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaStats.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaStats.h
new file mode 100644
index 0000000..688190f
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaStats.h
@@ -0,0 +1,47 @@
+#ifndef __LPS_TDOA_STATS_H__
+#define __LPS_TDOA_STATS_H__
+
+#include <inttypes.h>
+
+typedef struct {
+ uint32_t packetsReceived;
+ uint32_t packetsToEstimator;
+ uint32_t contextHitCount;
+ uint32_t contextMissCount;
+ uint32_t timeIsGood;
+ uint32_t suitableDataFound;
+
+ // Anchor ids to use for stats
+ uint8_t anchorId; // The id of the anchor to log
+ uint8_t remoteAnchorId; // The id of the remote anchor to log
+
+ // Clock correction for the anchor identified by anchorId
+ float clockCorrection;
+ uint32_t clockCorrectionCount;
+
+ // TOF data from remoteAnchorId to anchorId, measured by anchorId
+ uint16_t tof;
+
+ // TDoA (in meters) between anchorId and remoteAnchorId
+ float tdoa;
+
+
+ uint16_t packetsReceivedRate;
+ uint16_t packetsToEstimatorRate;
+ uint16_t contextHitRate;
+ uint16_t contextMissRate;
+ uint16_t timeIsGoodRate;
+ uint16_t suitableDataFoundRate;
+ uint16_t clockCorrectionRate;
+
+ uint32_t nextStatisticsTime;
+ uint32_t previousStatisticsTime;
+
+ uint8_t newAnchorId; // Used to change anchor to log, set as param
+ uint8_t newRemoteAnchorId; // Used to change remote anchor to log, set as param
+} tdoaStats_t;
+
+void tdoaStatsInit(tdoaStats_t* tdoaStats, uint32_t now_ms);
+void tdoaStatsUpdate(tdoaStats_t* tdoaStats, uint32_t now_ms);
+
+#endif // __LPS_TDOA_STATS_H__
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaStorage.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaStorage.h
new file mode 100644
index 0000000..3a21525
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/tdoa/tdoaStorage.h
@@ -0,0 +1,80 @@
+#ifndef __TDOA_STORAGE_H__
+#define __TDOA_STORAGE_H__
+
+#include "stabilizer_types.h"
+#include "clockCorrectionEngine.h"
+
+#define ANCHOR_STORAGE_COUNT 16
+#define REMOTE_ANCHOR_DATA_COUNT 16
+#define TOF_PER_ANCHOR_COUNT 16
+
+
+typedef struct {
+ uint8_t id; // Id of remote remote anchor
+ uint8_t seqNr; // Sequence number of the packet received in the remote anchor (7 bits)
+ int64_t rxTime; // Receive time of packet from anchor id in the remote anchor, in remote DWM clock
+ uint32_t endOfLife;
+} tdoaRemoteAnchorData_t;
+
+typedef struct {
+ uint8_t id;
+ int64_t tof;
+ uint32_t endOfLife; // Time stamp when the tof data is outdated, local system time in ms
+} tdoaTimeOfFlight_t;
+
+typedef struct {
+ bool isInitialized;
+ uint32_t lastUpdateTime; // The time when this anchor was updated the last time
+ uint8_t id; // Anchor id
+
+ int64_t txTime; // Transmit time of last packet, in remote DWM clock
+ int64_t rxTime; // Receive time of last packet, in local DWM clock
+ uint8_t seqNr; // Sequence nr of last packet (7 bits)
+
+ clockCorrectionStorage_t clockCorrectionStorage;
+
+ point_t position; // The coordinates of the anchor
+
+ tdoaTimeOfFlight_t tof[TOF_PER_ANCHOR_COUNT];
+ tdoaRemoteAnchorData_t remoteAnchorData[REMOTE_ANCHOR_DATA_COUNT];
+} tdoaAnchorInfo_t;
+
+typedef tdoaAnchorInfo_t tdaoAnchorInfoArray_t[ANCHOR_STORAGE_COUNT];
+
+
+// The anchor context is used to pass information about an anchor as well as
+// the current time to functions.
+// The context should not be stored.
+typedef struct {
+ tdoaAnchorInfo_t* anchorInfo;
+ uint32_t currentTime_ms;
+} tdoaAnchorContext_t;
+
+
+void tdoaStorageInitialize(tdoaAnchorInfo_t anchorStorage[]);
+
+bool tdoaStorageGetCreateAnchorCtx(tdoaAnchorInfo_t anchorStorage[], const uint8_t anchor, const uint32_t currentTime_ms, tdoaAnchorContext_t* anchorCtx);
+bool tdoaStorageGetAnchorCtx(tdoaAnchorInfo_t anchorStorage[], const uint8_t anchor, const uint32_t currentTime_ms, tdoaAnchorContext_t* anchorCtx);
+uint8_t tdoaStorageGetListOfAnchorIds(tdoaAnchorInfo_t anchorStorage[], uint8_t unorderedAnchorList[], const int maxListSize);
+uint8_t tdoaStorageGetListOfActiveAnchorIds(tdoaAnchorInfo_t anchorStorage[], uint8_t unorderedAnchorList[], const int maxListSize, const uint32_t currentTime_ms);
+
+uint8_t tdoaStorageGetId(const tdoaAnchorContext_t* anchorCtx);
+int64_t tdoaStorageGetRxTime(const tdoaAnchorContext_t* anchorCtx);
+int64_t tdoaStorageGetTxTime(const tdoaAnchorContext_t* anchorCtx);
+uint8_t tdoaStorageGetSeqNr(const tdoaAnchorContext_t* anchorCtx);
+uint32_t tdoaStorageGetLastUpdateTime(const tdoaAnchorContext_t* anchorCtx);
+clockCorrectionStorage_t* tdoaStorageGetClockCorrectionStorage(const tdoaAnchorContext_t* anchorCtx);
+bool tdoaStorageGetAnchorPosition(const tdoaAnchorContext_t* anchorCtx, point_t* position);
+void tdoaStorageSetAnchorPosition(tdoaAnchorContext_t* anchorCtx, const float x, const float y, const float z);
+void tdoaStorageSetRxTxData(tdoaAnchorContext_t* anchorCtx, int64_t rxTime, int64_t txTime, uint8_t seqNr);
+double tdoaStorageGetClockCorrection(const tdoaAnchorContext_t* anchorCtx);
+int64_t tdoaStorageGetRemoteRxTime(const tdoaAnchorContext_t* anchorCtx, const uint8_t remoteAnchor);
+void tdoaStorageSetRemoteRxTime(tdoaAnchorContext_t* anchorCtx, const uint8_t remoteAnchor, const int64_t remoteRxTime, const uint8_t remoteSeqNr);
+void tdoaStorageGetRemoteSeqNrList(const tdoaAnchorContext_t* anchorCtx, int* remoteCount, uint8_t seqNr[], uint8_t id[]);
+int64_t tdoaStorageGetTimeOfFlight(const tdoaAnchorContext_t* anchorCtx, const uint8_t otherAnchor);
+void tdoaStorageSetTimeOfFlight(tdoaAnchorContext_t* anchorCtx, const uint8_t remoteAnchor, const int64_t tof);
+
+// Mainly for test
+bool tdoaStorageIsAnchorInStorage(tdoaAnchorInfo_t anchorStorage[], const uint8_t anchor);
+
+#endif // __TDOA_STORAGE_H__
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/test_support.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/test_support.h
new file mode 100644
index 0000000..658c80b
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/test_support.h
@@ -0,0 +1,36 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2018 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * Utilities to simplify unit testing
+ *
+ */
+
+#pragma once
+
+// UNIT_TEST_MODE is defined by the unit test framework when unit tests are running
+
+#if UNIT_TEST_MODE
+ #define TESTABLE_STATIC
+#else
+ #define TESTABLE_STATIC static
+#endif
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/interface/version.h b/Firmware/esp-drone/components/core/crazyflie/utils/interface/version.h
new file mode 100644
index 0000000..c98e92a
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/interface/version.h
@@ -0,0 +1,33 @@
+/**
+ *
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * Version.h - Firmware version
+ */
+#ifndef __VERSION_H__
+#define __VERSION_H__
+
+#include <stdbool.h>
+
+extern const char * V_SLOCAL_REVISION;
+extern const char * V_SREVISION;
+extern const char * V_STAG;
+extern const bool V_MODIFIED;
+extern const bool V_PRODUCTION_RELEASE;
+
+#endif /* __VERSION_H__ */
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/FreeRTOS-openocd.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/FreeRTOS-openocd.c
new file mode 100644
index 0000000..567e710
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/FreeRTOS-openocd.c
@@ -0,0 +1,20 @@
+/*
+ * Since at least FreeRTOS V7.5.3 uxTopUsedPriority is no longer
+ * present in the kernel, so it has to be supplied by other means for
+ * OpenOCD's threads awareness.
+ *
+ * Add this file to your project, and, if you're using --gc-sections,
+ * ``--undefined=uxTopUsedPriority'' (or
+ * ``-Wl,--undefined=uxTopUsedPriority'' when using gcc for final
+ * linking) to your LDFLAGS; same with all the other symbols you need.
+ */
+
+#include "FreeRTOS.h"
+
+#ifdef __GNUC__
+#define USED __attribute__((used))
+#else
+#define USED
+#endif
+
+const int USED uxTopUsedPriority = configMAX_PRIORITIES;
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/abort.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/abort.c
new file mode 100644
index 0000000..d7d4e1e
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/abort.c
@@ -0,0 +1,14 @@
+/**
+ *
+ * abort.c: Simple abort function.
+ *
+ * Newer versions of newlibc always use unwind functions which do need an
+ * implementation of abort(). So in order to link without standard libraries
+ * (-nostdlib) we have to provide abort().
+ */
+
+void abort(void)
+{
+ while (1)
+ ;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/cfassert.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/cfassert.c
new file mode 100644
index 0000000..80e3fca
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/cfassert.c
@@ -0,0 +1,179 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+*
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * cfassert.c - Assert implementation
+ */
+
+#define DEBUG_MODULE "SYS"
+
+#include <stdint.h>
+#include "FreeRTOS.h"
+#include "cfassert.h"
+#include "led.h"
+#include "power_distribution.h"
+#include "debug_cf.h"
+
+#define MAGIC_ASSERT_INDICATOR 0x2f8a001f
+
+enum snapshotType_e
+{
+ SnapshotTypeNone = 0,
+ SnapshotTypeFile = 1,
+ SnapshotTypeHardFault = 2,
+ SnapshotTypeText = 3,
+};
+
+typedef struct SNAPSHOT_DATA {
+ uint32_t magicNumber;
+ enum snapshotType_e type;
+ union {
+ struct {
+ const char* fileName;
+ int line;
+ } file;
+ struct {
+ unsigned int r0;
+ unsigned int r1;
+ unsigned int r2;
+ unsigned int r3;
+ unsigned int r12;
+ unsigned int lr;
+ unsigned int pc;
+ unsigned int psr;
+ } hardfault;
+ struct {
+ const char* text;
+ } text;
+ };
+} SNAPSHOT_DATA;
+
+// The .nzds section is not cleared at startup, data here will survive a
+// reset (by the watch dog for instance)
+SNAPSHOT_DATA snapshot = { // __attribute__((section(".nzds"))) = {
+ .magicNumber = 0,
+ .type = SnapshotTypeNone,
+};
+
+
+void assertFail(char *exp, char *file, int line)
+{
+ portDISABLE_INTERRUPTS();
+ storeAssertFileData(file, line);
+ DEBUG_PRINTE("Assert failed %s:%d\n", file, line);
+
+ ledClearAll();
+ ledSet(ERR_LED1, 1);
+ //ledSet(ERR_LED2, 1);
+ powerStop();
+
+ while (1);
+}
+
+void storeAssertFileData(const char *file, int line)
+{
+ snapshot.magicNumber = MAGIC_ASSERT_INDICATOR;
+ snapshot.type = SnapshotTypeFile;
+ snapshot.file.fileName = file;
+ snapshot.file.line = line;
+}
+
+void storeAssertHardfaultData(
+ unsigned int r0,
+ unsigned int r1,
+ unsigned int r2,
+ unsigned int r3,
+ unsigned int r12,
+ unsigned int lr,
+ unsigned int pc,
+ unsigned int psr)
+{
+ snapshot.magicNumber = MAGIC_ASSERT_INDICATOR;
+ snapshot.type = SnapshotTypeHardFault;
+ snapshot.hardfault.r0 = r0;
+ snapshot.hardfault.r1 = r1;
+ snapshot.hardfault.r2 = r2;
+ snapshot.hardfault.r3 = r3;
+ snapshot.hardfault.r12 = r12;
+ snapshot.hardfault.lr = lr;
+ snapshot.hardfault.pc = pc;
+ snapshot.hardfault.psr = psr;
+}
+
+void storeAssertTextData(const char *text)
+{
+ snapshot.magicNumber = MAGIC_ASSERT_INDICATOR;
+ snapshot.type = SnapshotTypeText;
+ snapshot.text.text = text;
+}
+
+static void clearAssertData() {
+ snapshot.type = SnapshotTypeNone;
+}
+
+void printAssertSnapshotData()
+{
+ if (MAGIC_ASSERT_INDICATOR == snapshot.magicNumber) {
+ switch (snapshot.type) {
+ case SnapshotTypeFile:
+ DEBUG_PRINT_LOCAL("Assert failed at %s:%d\n", snapshot.file.fileName, snapshot.file.line);
+ break;
+ case SnapshotTypeHardFault:
+ DEBUG_PRINT_LOCAL("Hardfault. r0: %X, r1: %X, r2: %X, r3: %X, r12: %X, lr: %X, pc: %X, psr: %X\n",
+ snapshot.hardfault.r0,
+ snapshot.hardfault.r1,
+ snapshot.hardfault.r2,
+ snapshot.hardfault.r3,
+ snapshot.hardfault.r12,
+ snapshot.hardfault.lr,
+ snapshot.hardfault.pc,
+ snapshot.hardfault.psr);
+ break;
+ case SnapshotTypeText:
+ DEBUG_PRINT_LOCAL("Assert failed: %s\n", snapshot.text.text);
+ break;
+ default:
+ DEBUG_PRINT_LOCAL("Assert failed, but unknown type\n");
+ break;
+ }
+ } else {
+ DEBUG_PRINT_LOCAL( "No assert information found\n");
+ }
+}
+
+static bool isAssertRegistered() {
+ return (MAGIC_ASSERT_INDICATOR == snapshot.magicNumber) && (snapshot.type != SnapshotTypeNone);
+}
+
+bool cfAssertNormalStartTest(void) {
+ bool wasNormalStart = true;
+
+ if (isAssertRegistered()) {
+ wasNormalStart = false;
+ DEBUG_PRINT("The system resumed after a failed assert [WARNING]\n");
+ printAssertSnapshotData();
+ clearAssertData();
+ }
+
+ return wasNormalStart;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/clockCorrectionEngine.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/clockCorrectionEngine.c
new file mode 100644
index 0000000..2dee318
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/clockCorrectionEngine.c
@@ -0,0 +1,133 @@
+#include "clockCorrectionEngine.h"
+
+#define MAX_CLOCK_DEVIATION_SPEC 10e-6
+#define CLOCK_CORRECTION_SPEC_MIN (1.0 - MAX_CLOCK_DEVIATION_SPEC * 2)
+#define CLOCK_CORRECTION_SPEC_MAX (1.0 + MAX_CLOCK_DEVIATION_SPEC * 2)
+
+#define CLOCK_CORRECTION_ACCEPTED_NOISE 0.03e-6
+#define CLOCK_CORRECTION_FILTER 0.1
+#define CLOCK_CORRECTION_BUCKET_MAX 4
+
+/**
+ Logging all the clock correction information requires scaling the values repeatedly, which is computer intense. Thus, the logging functionality is enabled at compile time with the CLOCK_CORRECTION_ENABLE_LOGGING flag.
+ */
+#ifdef CLOCK_CORRECTION_ENABLE_LOGGING
+#include "log.h"
+
+static float logMinAcceptedNoiseLimit = 0;
+static float logMaxAcceptedNoiseLimit = 0;
+static float logMinSpecLimit = 0;
+static float logMaxSpecLimit = 0;
+static float logClockCorrection = 0;
+static float logClockCorrectionCandidate = 0;
+
+static float scaleValueForLogging(double value) {
+ return (float)((value - 1) * (1 / MAX_CLOCK_DEVIATION_SPEC) * 1000);
+}
+#endif
+
+/**
+ Obtains the clock correction from a clockCorrectionStorage_t object. This is the recommended public API to obtain the clock correction, instead of getting it directly from the storage object.
+ */
+double clockCorrectionEngineGet(const clockCorrectionStorage_t* storage) {
+ return storage->clockCorrection;
+}
+
+/**
+ Truncates a timestamp to the number of bits of the mask. This truncation ensures that the value returned is a valid time event, even if the time counter wrapped around.
+ */
+static uint64_t truncateTimeStamp(uint64_t timeStamp, uint64_t mask) {
+ return timeStamp & mask;
+}
+
+/**
+ Implementation of the leaky bucket algorithm. See: https://en.wikipedia.org/wiki/Leaky_bucket
+ */
+static void fillClockCorrectionBucket(clockCorrectionStorage_t* storage) {
+ if (storage->clockCorrectionBucket < CLOCK_CORRECTION_BUCKET_MAX) {
+ storage->clockCorrectionBucket++;
+ }
+}
+
+/**
+ Implementation of the leaky bucket algorithm. See: https://en.wikipedia.org/wiki/Leaky_bucket
+ */
+static bool emptyClockCorrectionBucket(clockCorrectionStorage_t* storage) {
+ if (storage->clockCorrectionBucket > 0) {
+ storage->clockCorrectionBucket--;
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ Calculates the clock correction between a reference clock and another clock (x).
+
+ @param new_t_in_cl_reference The newest time of occurrence for an event (t), measured by the clock of reference
+ @param old_t_in_cl_reference An older time of occurrence for an event (t), measured by the clock of reference
+ @param new_t_in_cl_x The newest time of occurrence for an event (t), measured by clock x
+ @param old_t_in_cl_x The previous time of occurrence for an event (t), measured by clock x
+ @param mask A mask as long as the number of bits used to represent the timestamps. Used to calculate a valid timestamp, even if wrapped arounds of the time counter happened at some point
+ @return The necessary clock correction to apply to timestamps measured by clock x, in order to obtain their value like if the measurement was done by the reference clock. Or -1 if it was not possible to perform the computation. Example: timestamp_in_cl_reference = clockCorrection * timestamp_in_cl_x
+ */
+double clockCorrectionEngineCalculate(const uint64_t new_t_in_cl_reference, const uint64_t old_t_in_cl_reference, const uint64_t new_t_in_cl_x, const uint64_t old_t_in_cl_x, const uint64_t mask) {
+ const uint64_t tickCount_in_cl_reference = truncateTimeStamp(new_t_in_cl_reference - old_t_in_cl_reference, mask);
+ const uint64_t tickCount_in_cl_x = truncateTimeStamp(new_t_in_cl_x - old_t_in_cl_x, mask);
+
+ if (tickCount_in_cl_x == 0) {
+ return -1;
+ }
+
+ return (double)tickCount_in_cl_reference / (double)tickCount_in_cl_x;
+}
+
+/**
+ Updates the clock correction only if the provided value follows certain conditions. This is used to discard wrong clock correction measurements.
+ @return True if the provided clock correction sample ir reliable, false otherwise. A sample is reliable when it is in the accepted noise level (which means that we already have two or more samples that are similar) and has been LP filtered.
+ */
+bool clockCorrectionEngineUpdate(clockCorrectionStorage_t* storage, const double clockCorrectionCandidate) {
+ bool sampleIsReliable = false;
+
+ const double currentClockCorrection = storage->clockCorrection;
+ const double difference = clockCorrectionCandidate - currentClockCorrection;
+
+#ifdef CLOCK_CORRECTION_ENABLE_LOGGING
+ logMinAcceptedNoiseLimit = scaleValueForLogging(currentClockCorrection - CLOCK_CORRECTION_ACCEPTED_NOISE);
+ logMaxAcceptedNoiseLimit = scaleValueForLogging(currentClockCorrection + CLOCK_CORRECTION_ACCEPTED_NOISE);
+ logMinSpecLimit = scaleValueForLogging(CLOCK_CORRECTION_SPEC_MIN);
+ logMaxSpecLimit = scaleValueForLogging(CLOCK_CORRECTION_SPEC_MAX);
+ logClockCorrection = scaleValueForLogging(currentClockCorrection);
+ logClockCorrectionCandidate = scaleValueForLogging(clockCorrectionCandidate);
+#endif
+
+ if (-CLOCK_CORRECTION_ACCEPTED_NOISE < difference && difference < CLOCK_CORRECTION_ACCEPTED_NOISE) {
+ // Simple low pass filter
+ const double newClockCorrection = currentClockCorrection * CLOCK_CORRECTION_FILTER + clockCorrectionCandidate * (1.0 - CLOCK_CORRECTION_FILTER);
+
+ sampleIsReliable = true;
+ fillClockCorrectionBucket(storage);
+ storage->clockCorrection = newClockCorrection;
+ } else {
+ const bool shouldAcceptANewClockReference = emptyClockCorrectionBucket(storage);
+ if (shouldAcceptANewClockReference) {
+ if (CLOCK_CORRECTION_SPEC_MIN < clockCorrectionCandidate && clockCorrectionCandidate < CLOCK_CORRECTION_SPEC_MAX) {
+ // We do not fill the bucket and accept the clock correction sample as reliable: a sample is reliable when it is in the accepted noise level (which means that we already have two or more samples that are similar) and has been LP filtered. See: https://github.com/bitcraze/crazyflie-firmware/pull/328
+ storage->clockCorrection = clockCorrectionCandidate;
+ }
+ }
+ }
+
+ return sampleIsReliable;
+}
+
+#ifdef CLOCK_CORRECTION_ENABLE_LOGGING
+LOG_GROUP_START(CkCorrection)
+LOG_ADD(LOG_FLOAT, minNoise, &logMinAcceptedNoiseLimit)
+LOG_ADD(LOG_FLOAT, maxNoise, &logMaxAcceptedNoiseLimit)
+LOG_ADD(LOG_FLOAT, minSpec, &logMinSpecLimit)
+LOG_ADD(LOG_FLOAT, maxSpec, &logMaxSpecLimit)
+LOG_ADD(LOG_FLOAT, actualValue, &logClockCorrection)
+LOG_ADD(LOG_FLOAT, candidate, &logClockCorrectionCandidate)
+LOG_GROUP_STOP(CkCorrection)
+#endif
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/configblockeeprom.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/configblockeeprom.c
new file mode 100644
index 0000000..e08b6fc
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/configblockeeprom.c
@@ -0,0 +1,314 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+*
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * configblock.c - Simple static implementation of the config block
+ */
+#define DEBUG_MODULE "CFGBLK"
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <string.h>
+
+#include "config.h"
+#include "debug_cf.h"
+#include "i2cdev.h"
+#include "configblock.h"
+#include "eeprom.h"
+
+
+/* Internal format of the config block */
+#define MAGIC 0x43427830
+#define VERSION 1
+#define HEADER_SIZE_BYTES 5 // magic + version
+#define OVERHEAD_SIZE_BYTES (HEADER_SIZE_BYTES + 1) // + cksum
+
+// Old versions
+struct configblock_v0_s {
+ /* header */
+ uint32_t magic;
+ uint8_t version;
+ /* Content */
+ uint8_t radioChannel;
+ uint8_t radioSpeed;
+ float calibPitch;
+ float calibRoll;
+ /* Simple modulo 256 checksum */
+ uint8_t cksum;
+} __attribute__((__packed__));
+
+// Current version
+struct configblock_v1_s {
+ /* header */
+ uint32_t magic;
+ uint8_t version;
+ /* Content */
+ uint8_t radioChannel;
+ uint8_t radioSpeed;
+ float calibPitch;
+ float calibRoll;
+ uint8_t radioAddress_upper;
+ uint32_t radioAddress_lower;
+ /* Simple modulo 256 checksum */
+ uint8_t cksum;
+} __attribute__((__packed__));
+
+// Set version 1 as current version
+typedef struct configblock_v1_s configblock_t;
+
+static configblock_t configblock;
+static configblock_t configblockDefault =
+{
+ .magic = MAGIC,
+ .version = VERSION,
+ .radioChannel = RADIO_CHANNEL,
+ .radioSpeed = RADIO_DATARATE,
+ .calibPitch = 0.0,
+ .calibRoll = 0.0,
+ .radioAddress_upper = ((uint64_t)RADIO_ADDRESS >> 32),
+ .radioAddress_lower = (RADIO_ADDRESS & 0xFFFFFFFFULL),
+};
+
+static const uint32_t configblockSizes[] =
+{
+ sizeof(struct configblock_v0_s),
+ sizeof(struct configblock_v1_s),
+};
+
+static bool isInit = false;
+static bool cb_ok = false;
+
+static bool configblockCheckMagic(configblock_t *configblock);
+static bool configblockCheckVersion(configblock_t *configblock);
+static bool configblockCheckChecksum(configblock_t *configblock);
+static bool configblockCheckDataIntegrity(uint8_t *data, uint8_t version);
+static bool configblockWrite(configblock_t *configblock);
+static bool configblockCopyToNewVersion(configblock_t *configblockSaved, configblock_t *configblockNew);
+
+static uint8_t calculate_cksum(void* data, size_t len)
+{
+ unsigned char* c = data;
+ int i;
+ unsigned char cksum=0;
+
+ for (i=0; i<len; i++)
+ cksum += *(c++);
+
+ return cksum;
+}
+
+int configblockInit(void)
+{
+ if(isInit)
+ return 0;
+
+ i2cdevInit(I2C1_DEV);
+ eepromInit(I2C1_DEV);
+
+ // Because of strange behavior from I2C device during expansion port test
+ // the first read needs to be discarded
+ eepromTestConnection();
+
+ if (eepromTestConnection())
+ {
+ if (eepromReadBuffer((uint8_t *)&configblock, 0, sizeof(configblock)))
+ {
+ //Verify the config block
+ if (configblockCheckMagic(&configblock))
+ {
+ if (configblockCheckVersion(&configblock))
+ {
+ if (configblockCheckChecksum(&configblock))
+ {
+ // Everything is fine
+ DEBUG_PRINTD("v%d, verification [OK]\n", configblock.version);
+ cb_ok = true;
+ }
+ else
+ {
+ DEBUG_PRINTD("Verification [FAIL]\n");
+ cb_ok = false;
+ }
+ }
+ else // configblockCheckVersion
+ {
+ // Check data integrity of old version data
+ if (configblock.version <= VERSION &&
+ configblockCheckDataIntegrity((uint8_t *)&configblock, configblock.version))
+ {
+ // Not the same version, try to upgrade
+ if (configblockCopyToNewVersion(&configblock, &configblockDefault))
+ {
+ // Write updated config block to eeprom
+ if (configblockWrite(&configblock))
+ {
+ cb_ok = true;
+ }
+ }
+ }
+ else
+ {
+ // Can't copy old version due to bad data.
+ cb_ok = false;
+ }
+ }
+ }
+ }
+ }
+
+ if (cb_ok == false)
+ {
+ // Copy default data to used structure.
+ memcpy((uint8_t *)&configblock, (uint8_t *)&configblockDefault, sizeof(configblock));
+ // Write default configuration to eeprom
+ if (configblockWrite(&configblockDefault))
+ {
+ cb_ok = true;
+ }
+ else
+ {
+ return -1;
+ }
+ }
+
+ isInit = true;
+
+ return 0;
+}
+
+bool configblockTest(void)
+{
+ return eepromTest();
+}
+
+static bool configblockCheckMagic(configblock_t *configblock)
+{
+ return (configblock->magic == MAGIC);
+}
+
+static bool configblockCheckVersion(configblock_t *configblock)
+{
+ return (configblock->version == VERSION);
+}
+
+static bool configblockCheckChecksum(configblock_t *configblock)
+{
+ return (configblock->cksum == calculate_cksum(configblock, sizeof(configblock_t) - 1));
+}
+
+static bool configblockCheckDataIntegrity(uint8_t *data, uint8_t version)
+{
+ bool status = false;
+
+ if (version == 0)
+ {
+ struct configblock_v0_s *v0 = ( struct configblock_v0_s *)data;
+ status = (v0->cksum == calculate_cksum(data, sizeof(struct configblock_v0_s) - 1));
+ }
+ else if (version == 1)
+ {
+ struct configblock_v1_s *v1 = ( struct configblock_v1_s *)data;
+ status = (v1->cksum == calculate_cksum(data, sizeof(struct configblock_v1_s) - 1));
+ }
+
+ return status;
+}
+
+static bool configblockWrite(configblock_t *configblock)
+{
+ // Write default configuration to eeprom
+ configblock->cksum = calculate_cksum(configblock, sizeof(configblock_t) - 1);
+ if (!eepromWriteBuffer((uint8_t *)configblock, 0, sizeof(configblock_t)))
+ {
+ return false;
+ }
+
+ return true;
+}
+
+static bool configblockCopyToNewVersion(configblock_t *configblockSaved, configblock_t *configblockNew)
+{
+ configblock_t configblockTmp;
+
+ // Copy new data to temp config memory
+ memcpy((uint8_t *)&configblockTmp, (uint8_t *)configblockNew, sizeof(configblock_t));
+
+ if (configblockSaved->version <= VERSION &&
+ sizeof(configblock_t) >= configblockSizes[configblockSaved->version])
+ {
+ // Copy old saved eeprom data to new structure
+ memcpy((uint8_t *)&configblockTmp + HEADER_SIZE_BYTES,
+ (uint8_t *)configblockSaved + HEADER_SIZE_BYTES,
+ configblockSizes[configblockSaved->version] - OVERHEAD_SIZE_BYTES);
+ // Copy updated block to saved structure
+ memcpy((uint8_t *)configblockSaved, (uint8_t *)&configblockTmp, sizeof(configblock_t));
+ }
+ else
+ {
+ return false;
+ }
+
+ return true;
+}
+
+/* Static accessors */
+int configblockGetRadioChannel(void)
+{
+ if (cb_ok)
+ return configblock.radioChannel;
+ else
+ return RADIO_CHANNEL;
+}
+
+int configblockGetRadioSpeed(void)
+{
+ if (cb_ok)
+ return configblock.radioSpeed;
+ else
+ return RADIO_DATARATE;
+}
+
+uint64_t configblockGetRadioAddress(void)
+{
+ if (cb_ok)
+ return ((uint64_t)configblock.radioAddress_upper << 32) | (uint64_t)configblock.radioAddress_lower;
+ else
+ return RADIO_ADDRESS;
+}
+
+float configblockGetCalibPitch(void)
+{
+ if (cb_ok)
+ return configblock.calibPitch;
+ else
+ return 0;
+}
+
+float configblockGetCalibRoll(void)
+{
+ if (cb_ok)
+ return configblock.calibRoll;
+ else
+ return 0;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/configblockflash.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/configblockflash.c
new file mode 100644
index 0000000..d890ef5
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/configblockflash.c
@@ -0,0 +1,126 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * configblock.c - Simple static implementation of the config block
+ */
+#define DEBUG_MODULE "CFGBLK"
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <unistd.h>
+
+#include "config.h"
+#include "configblock.h"
+#include "debug_cf.h"
+
+/* Internal format of the config block */
+#define MAGIC 0x43427830
+#define VERSION 0
+struct configblock_s {
+ /* header */
+ uint32_t magic;
+ uint8_t version;
+ /* Content */
+ uint8_t radioChannel;
+ uint8_t radioSpeed;
+ float calibPitch;
+ float calibRoll;
+ /* Simple modulo 256 checksum */
+ uint8_t cksum;
+} __attribute__((__packed__));
+
+static struct configblock_s *configblock;
+
+static bool cb_ok=false;
+
+static uint8_t calculate_cksum(void* data, size_t len)
+{
+ unsigned char* c = data;
+ int i;
+ unsigned char cksum=0;
+
+ for (i=0; i<len; i++)
+ cksum += *(c++);
+
+ return cksum;
+}
+
+int configblockInit(void)
+{
+ configblock = (void*)CONFIG_BLOCK_ADDRESS;
+
+ //Verify the config block
+ if (configblock->magic!=MAGIC || configblock->version!= VERSION ||
+ calculate_cksum(configblock, sizeof(*configblock)) )
+ {
+ DEBUG_PRINT("Verification [FAIL]\n");
+ return -1;
+ }
+ else
+ {
+ DEBUG_PRINT("v%d, verification [OK]\n", configblock->version);
+ cb_ok = true;
+ }
+
+
+ return 0;
+}
+
+bool configblockTest(void)
+{
+ return true;
+}
+
+/* Static accessors */
+int configblockGetRadioChannel(void)
+{
+ if (cb_ok)
+ return configblock->radioChannel;
+ else
+ return RADIO_CHANNEL;
+}
+
+int configblockGetRadioSpeed(void)
+{
+ if (cb_ok)
+ return configblock->radioSpeed;
+ else
+ return RADIO_DATARATE;
+}
+
+float configblockGetCalibPitch(void)
+{
+ if (cb_ok)
+ return configblock->calibPitch;
+ else
+ return 0;
+}
+
+float configblockGetCalibRoll(void)
+{
+ if (cb_ok)
+ return configblock->calibRoll;
+ else
+ return 0;
+}
+
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/cpuid.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/cpuid.c
new file mode 100644
index 0000000..91e0f7a
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/cpuid.c
@@ -0,0 +1,37 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+*
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * cpuid.c - CPU ID functions
+ */
+#include "cpuid.h"
+
+unsigned char * cpuidGetId()
+{
+ return (unsigned char *)(0x1FFFF7E8);
+}
+
+int cpuIdGetFlashSize()
+{
+ return *((short*)(4*1024*1024));
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/crc.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/crc.c
new file mode 100644
index 0000000..22dd5e3
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/crc.c
@@ -0,0 +1,227 @@
+/**********************************************************************
+ *
+ * Filename: crc.c
+ *
+ * Description: Slow and fast implementations of the CRC standards.
+ *
+ * Notes: The parameters for each supported CRC standard are
+ * defined in the header file crc.h. The implementations
+ * here should stand up to further additions to that list.
+ *
+ * Modified by Bitcraze: made static local variables and
+ * used stdint.h types where relevant.
+ *
+ * Copyright (c) 2012 Bitcraze AB
+ * Copyright (c) 2000 by Michael Barr. This software is placed into
+ * the public domain and may be used for any purpose. However, this
+ * notice must not be changed or removed and no warranty is either
+ * expressed or implied by its publication or distribution.
+ **********************************************************************/
+
+#include "crc.h"
+
+/*
+ * Derive parameters from the standard-specific parameters in crc.h.
+ */
+#define WIDTH (8 * sizeof(crc))
+#define TOPBIT (1 << (WIDTH - 1))
+
+#if (REFLECT_DATA == TRUE)
+#undef REFLECT_DATA
+#define REFLECT_DATA(X) ((unsigned char) reflect((X), 8))
+#else
+#undef REFLECT_DATA
+#define REFLECT_DATA(X) (X)
+#endif
+
+#if (REFLECT_REMAINDER == TRUE)
+#undef REFLECT_REMAINDER
+#define REFLECT_REMAINDER(X) ((crc) reflect((X), WIDTH))
+#else
+#undef REFLECT_REMAINDER
+#define REFLECT_REMAINDER(X) (X)
+#endif
+
+/*********************************************************************
+ *
+ * Function: reflect()
+ *
+ * Description: Reorder the bits of a binary sequence, by reflecting
+ * them about the middle position.
+ *
+ * Notes: No checking is done that nBits <= 32.
+ *
+ * Returns: The reflection of the original data.
+ *
+ *********************************************************************/
+static unsigned long reflect(unsigned long data, unsigned char nBits)
+{
+ unsigned long reflection = 0x00000000;
+ unsigned char bit;
+
+ /*
+ * Reflect the data about the center bit.
+ */
+ for (bit = 0; bit < nBits; ++bit)
+ {
+ /*
+ * If the LSB bit is set, set the reflection of it.
+ */
+ if (data & 0x01)
+ {
+ reflection |= (1 << ((nBits - 1) - bit));
+ }
+
+ data = (data >> 1);
+ }
+
+ return (reflection);
+
+} /* reflect() */
+
+/*********************************************************************
+ *
+ * Function: crcSlow()
+ *
+ * Description: Compute the CRC of a given message.
+ *
+ * Notes:
+ *
+ * Returns: The CRC of the message.
+ *
+ *********************************************************************/
+crc crcSlow(void * datas, int nBytes)
+{
+ crc remainder = INITIAL_REMAINDER;
+ unsigned char * message = datas;
+ int byte;
+ unsigned char bit;
+
+ /*
+ * Perform modulo-2 division, a byte at a time.
+ */
+ for (byte = 0; byte < nBytes; ++byte)
+ {
+ /*
+ * Bring the next byte into the remainder.
+ */
+ remainder ^= (REFLECT_DATA(message[byte]) << (WIDTH - 8));
+
+ /*
+ * Perform modulo-2 division, a bit at a time.
+ */
+ for (bit = 8; bit > 0; --bit)
+ {
+ /*
+ * Try to divide the current data bit.
+ */
+ if (remainder & TOPBIT)
+ {
+ remainder = (remainder << 1) ^ POLYNOMIAL;
+ }
+ else
+ {
+ remainder = (remainder << 1);
+ }
+ }
+ }
+
+ /*
+ * The final remainder is the CRC result.
+ */
+ return (REFLECT_REMAINDER(remainder) ^ FINAL_XOR_VALUE);
+
+} /* crcSlow() */
+
+#ifdef CRC_FAST
+static crc crcTable[256];
+
+/*********************************************************************
+ *
+ * Function: crcInit()
+ *
+ * Description: Populate the partial CRC lookup table.
+ *
+ * Notes: This function must be rerun any time the CRC standard
+ * is changed. If desired, it can be run "offline" and
+ * the table results stored in an embedded system's ROM.
+ *
+ * Returns: None defined.
+ *
+ *********************************************************************/
+void crcInit(void)
+{
+ crc remainder;
+ int dividend;
+ unsigned char bit;
+
+ /*
+ * Compute the remainder of each possible dividend.
+ */
+ for (dividend = 0; dividend < 256; ++dividend)
+ {
+ /*
+ * Start with the dividend followed by zeros.
+ */
+ remainder = dividend << (WIDTH - 8);
+
+ /*
+ * Perform modulo-2 division, a bit at a time.
+ */
+ for (bit = 8; bit > 0; --bit)
+ {
+ /*
+ * Try to divide the current data bit.
+ */
+ if (remainder & TOPBIT)
+ {
+ remainder = (remainder << 1) ^ POLYNOMIAL;
+ }
+ else
+ {
+ remainder = (remainder << 1);
+ }
+ }
+
+ /*
+ * Store the result into the table.
+ */
+ crcTable[dividend] = remainder;
+ }
+
+} /* crcInit() */
+
+/*********************************************************************
+ *
+ * Function: crcFast()
+ *
+ * Description: Compute the CRC of a given message.
+ *
+ * Notes: crcInit() must be called first.
+ *
+ * Returns: The CRC of the message.
+ *
+ *********************************************************************/
+crc crcFast(void * datas, int nBytes)
+{
+ crc remainder = INITIAL_REMAINDER;
+ unsigned char * message = datas;
+ unsigned char data;
+ int byte;
+
+ /*
+ * Divide the message by the polynomial, a byte at a time.
+ */
+ for (byte = 0; byte < nBytes; ++byte)
+ {
+ data = REFLECT_DATA(message[byte]) ^ (remainder >> (WIDTH - 8));
+ remainder = crcTable[data] ^ (remainder << 8);
+ }
+
+ /*
+ * The final remainder is the CRC.
+ */
+ return (REFLECT_REMAINDER(remainder) ^ FINAL_XOR_VALUE);
+
+} /* crcFast() */
+#endif
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/crc_bosch.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/crc_bosch.c
new file mode 100644
index 0000000..d0d2220
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/crc_bosch.c
@@ -0,0 +1,107 @@
+/**
+ * Copyright (C) 2017 Bosch Sensortec GmbH
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * Neither the name of the copyright holder nor the names of the
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ * OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ * The information provided is believed to be accurate and reliable.
+ * The copyright holder assumes no responsibility
+ * for the consequences of use
+ * of such information nor for any infringement of patents or
+ * other rights of third parties which may result from its use.
+ * No license is granted by implication or otherwise under any patent or
+ * patent rights of the copyright holder.
+ */
+
+#include "crc_bosch.h"
+
+/* bit-wise crc calculation */
+crc crcByBit(const uint8_t* message, uint32_t bytesToProcess,
+ crc remainder, crc finalxor)
+{
+ for (unsigned int byte = 0; byte < bytesToProcess; ++byte)
+ {
+#if REFLECT
+ remainder ^= *(message+byte);
+#else
+ remainder ^= ( *(message+byte) << (WIDTH - 8) );
+#endif
+
+ for(uint8_t bit = 8; bit > 0; --bit)
+ {
+#if REFLECT
+ /* reflect is realized by mirroring algorithm
+ * LSB is first to be processed */
+ if (remainder & 1)
+ remainder = (remainder >> 1) ^ POLYNOMIAL;
+ else
+ remainder = (remainder >> 1);
+#else
+ /* MSB is first to be processed */
+ if (remainder & TOPBIT)
+ remainder = (remainder << 1) ^ POLYNOMIAL;
+ else
+ remainder = (remainder << 1);
+#endif
+ }
+ }
+ return (remainder ^ finalxor);
+}
+
+/* byte-wise crc calculation, requires an initialized crcTable
+ * this is factor 8 faster and should be used if multiple crcs
+ * have to be calculated */
+crc crcByByte(const uint8_t* message, uint32_t bytesToProcess,
+ crc remainder, crc finalxor, crc* crcTable)
+{
+ static uint8_t data;
+ for (int byte = 0; byte < bytesToProcess; ++byte)
+ {
+#if REFLECT
+ data = (*(message+byte) ^ remainder);
+ remainder = *(crcTable+data) ^ (remainder >> 8);
+#else
+ data = ( *(message+byte) ^ (remainder >> (WIDTH - 8)) );
+ remainder = *(crcTable+data) ^ (remainder << 8);
+#endif
+ }
+ return (remainder ^ finalxor);
+}
+
+/* creates a lookup-table which is necessary for the crcByByte function */
+void crcTableInit(crc* crcTable)
+{
+ uint8_t dividend = ~0;
+ /* fill the table by bit-wise calculations of checksums
+ * for each possible dividend */
+ do {
+ *(crcTable+dividend) = crcByBit(&dividend, 1, 0, 0);
+ } while(dividend-- > 0);
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/debug_cf.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/debug_cf.c
new file mode 100644
index 0000000..ff79650
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/debug_cf.c
@@ -0,0 +1,35 @@
+/*
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * debug.c - Debugging utility functions
+ */
+#include "debug_cf.h"
+
+void debugInit(void)
+{
+#ifdef DEBUG_PRINT_ON_SEGGER_RTT
+ SEGGER_RTT_Init();
+ SEGGER_RTT_ConfigUpBuffer(0, NULL, NULL, 0, SEGGER_RTT_MODE_NO_BLOCK_TRIM);
+#endif
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/eprintf.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/eprintf.c
new file mode 100644
index 0000000..a825c04
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/eprintf.c
@@ -0,0 +1,318 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (c) 2012 Bitcraze AB
+ *
+ * eprintf.c: Memory-friendly ultra-limited embedded implementation of printf
+ *
+ * This implementation trades CPU cycle for data memory eficiency
+ * (No malloc, no unecessary buffers, etc...)
+ *
+ * Functionality: Implements %s, %d, %x, %X and %f without print size settings.
+ * The float handling is verry limited and without exponential notation (ie.
+ * works good for number around 0 and within int32 value range).
+ *
+ * To use this printf a 'putc' function shall be implemented with the prototype
+ * 'int putc(int)'. Then a macro calling eprintf can be created. For example:
+ * int consolePutc(int c);
+ * #define consolePrintf(FMT, ...) eprintf(consolePutc, FMT, ## __VA_ARGS__)
+ */
+#include "eprintf.h"
+
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <ctype.h>
+
+static const char digit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+ 'A', 'B', 'C', 'D', 'E', 'F'};
+
+static int getIntLen (long int value)
+{
+ int l = 1;
+ while(value > 9)
+ {
+ l++;
+ value /= 10;
+ }
+ return l;
+}
+
+int power(int a, int b)
+{
+ int i;
+ int x = a;
+
+ for (i = 1; i < b; i++)
+ {
+ x *= a;
+ }
+
+ return x;
+}
+
+static int itoa10Unsigned(putc_t putcf, unsigned long long int num)
+{
+ int len = 0;
+
+ if (num == 0)
+ {
+ putcf('0');
+ return 1;
+ }
+
+ unsigned long long int i = 1;
+
+ while ((num / i) > 9)
+ {
+ i *= 10L;
+ }
+
+ do
+ {
+ putcf(digit[(num / i) % 10L]);
+ len++;
+ }
+ while (i /= 10L);
+
+ return len;
+}
+
+static int itoa10(putc_t putcf, long long int num, int precision)
+{
+ int len = 0;
+
+ if (num == 0)
+ {
+ putcf('0');
+ return 1;
+ }
+
+ long long unsigned int n = num;
+ if (num < 0)
+ {
+ n = -num;
+ putcf('-');
+ len++;
+ }
+
+ int numLenght = getIntLen(num);
+ if (numLenght < precision)
+ {
+ int fillWithZero = precision - numLenght;
+ while (fillWithZero > 0)
+ {
+ putcf('0');
+ len++;
+ fillWithZero--;
+ }
+ }
+
+ return itoa10Unsigned(putcf, n) + len;
+}
+
+static int itoa16(putc_t putcf, uint64_t num, int width, char padChar)
+{
+ int len = 0;
+ bool foundFirst = false;
+
+ for (int i = 15; i >= 0; i--)
+ {
+ int shift = i * 4;
+ uint64_t mask = (uint64_t)0x0F << shift;
+ uint64_t val = (num & mask) >> shift;
+
+ if (val > 0)
+ {
+ foundFirst = true;
+ }
+
+ if (foundFirst || i < width)
+ {
+ if (foundFirst)
+ {
+ putcf(digit[val]);
+ }
+ else
+ {
+ putcf(padChar);
+ }
+
+ len++;
+ }
+ }
+
+ return len;
+}
+
+static int handleLongLong(putc_t putcf, char** fmt, unsigned long long int val, int width, char padChar)
+{
+ int len = 0;
+
+ switch(*((*fmt)++))
+ {
+ case 'i':
+ case 'd':
+ len = itoa10(putcf, (long long int)val, 0);
+ break;
+ case 'u':
+ len = itoa10Unsigned(putcf, val);
+ break;
+ case 'x':
+ case 'X':
+ len = itoa16(putcf, val, width, padChar);
+ break;
+ default:
+ // Nothing here
+ break;
+ }
+
+ return len;
+}
+
+static int handleLong(putc_t putcf, char** fmt, unsigned long int val, int width, char padChar)
+{
+ int len = 0;
+
+ switch(*((*fmt)++))
+ {
+ case 'i':
+ case 'd':
+ len = itoa10(putcf, (long int)val, 0);
+ break;
+ case 'u':
+ len = itoa10Unsigned(putcf, val);
+ break;
+ case 'x':
+ case 'X':
+ len = itoa16(putcf, val, width, padChar);
+ break;
+ default:
+ // Nothing here
+ break;
+ }
+
+ return len;
+}
+
+int evprintf(putc_t putcf, char * fmt, va_list ap)
+{
+ int len=0;
+ float num;
+ char* str;
+ int precision;
+ int width;
+ char padChar;
+
+ while (*fmt)
+ {
+ if (*fmt == '%')
+ {
+ precision = 6;
+ padChar = ' ';
+ width = 0;
+
+ fmt++;
+ while ('0' == *fmt)
+ {
+ padChar = '0';
+ fmt++;
+ }
+
+ while(isdigit((unsigned)*fmt))
+ {
+ width *= 10;
+ width += *fmt - '0';
+ fmt++;
+ }
+
+ while (!isalpha((unsigned) *fmt))
+ {
+ if (*fmt == '.')
+ {
+ fmt++;
+ if (isdigit((unsigned)*fmt))
+ {
+ precision = *fmt - '0';
+ fmt++;
+ }
+ }
+ }
+ switch (*fmt++)
+ {
+ case 'i':
+ case 'd':
+ len += itoa10(putcf, va_arg(ap, int), 0);
+ break;
+ case 'u':
+ len += itoa10Unsigned(putcf, va_arg(ap, unsigned int));
+ break;
+ case 'x':
+ case 'X':
+ len += itoa16(putcf, va_arg(ap, unsigned int), width, padChar);
+ break;
+ case 'l':
+ // Look ahead for ll
+ if (*fmt == 'l') {
+ fmt++;
+ len += handleLongLong(putcf, &fmt, va_arg(ap, unsigned long long int), width, padChar);
+ } else {
+ len += handleLong(putcf, &fmt, va_arg(ap, unsigned long int), width, padChar);
+ }
+
+ break;
+ case 'f':
+ num = va_arg(ap, double);
+ if(num<0)
+ {
+ putcf('-');
+ num = -num;
+ len++;
+ }
+ len += itoa10(putcf, (int)num, 0);
+ putcf('.'); len++;
+ len += itoa10(putcf, (num - (int)num) * power(10,precision), precision);
+ break;
+ case 's':
+ str = va_arg(ap, char* );
+ while(*str)
+ {
+ putcf(*str++);
+ len++;
+ }
+ break;
+ case 'c':
+ putcf((char)va_arg(ap, int));
+ len++;
+ break;
+ default:
+ break;
+ }
+ }
+ else
+ {
+ putcf(*fmt++);
+ len++;
+ }
+ }
+
+ return len;
+}
+
+int eprintf(putc_t putcf, char * fmt, ...)
+{
+ va_list ap;
+ int len;
+
+ va_start(ap, fmt);
+ len = evprintf(putcf, fmt, ap);
+ va_end(ap);
+
+ return len;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/filter.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/filter.c
new file mode 100644
index 0000000..60fc650
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/filter.c
@@ -0,0 +1,109 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * filter.h - Filtering functions
+ */
+
+#include <math.h>
+#include <stdlib.h>
+
+#include "filter.h"
+#include "physicalConstants.h"
+
+/**
+ * IIR filter the samples.
+ */
+int16_t iirLPFilterSingle(int32_t in, int32_t attenuation, int32_t* filt)
+{
+ int32_t inScaled;
+ int32_t filttmp = *filt;
+ int16_t out;
+
+ if (attenuation > (1<<IIR_SHIFT))
+ {
+ attenuation = (1<<IIR_SHIFT);
+ }
+ else if (attenuation < 1)
+ {
+ attenuation = 1;
+ }
+
+ // Shift to keep accuracy
+ inScaled = in << IIR_SHIFT;
+ // Calculate IIR filter
+ filttmp = filttmp + (((inScaled-filttmp) >> IIR_SHIFT) * attenuation);
+ // Scale and round
+ out = (filttmp >> 8) + ((filttmp & (1 << (IIR_SHIFT - 1))) >> (IIR_SHIFT - 1));
+ *filt = filttmp;
+
+ return out;
+}
+
+/**
+ * 2-Pole low pass filter
+ */
+void lpf2pInit(lpf2pData* lpfData, float sample_freq, float cutoff_freq)
+{
+ if (lpfData == NULL || cutoff_freq <= 0.0f) {
+ return;
+ }
+
+ lpf2pSetCutoffFreq(lpfData, sample_freq, cutoff_freq);
+}
+
+void lpf2pSetCutoffFreq(lpf2pData* lpfData, float sample_freq, float cutoff_freq)
+{
+ float fr = sample_freq/cutoff_freq;
+ float ohm = tanf(M_PI_F/fr);
+ float c = 1.0f+2.0f*cosf(M_PI_F/4.0f)*ohm+ohm*ohm;
+ lpfData->b0 = ohm*ohm/c;
+ lpfData->b1 = 2.0f*lpfData->b0;
+ lpfData->b2 = lpfData->b0;
+ lpfData->a1 = 2.0f*(ohm*ohm-1.0f)/c;
+ lpfData->a2 = (1.0f-2.0f*cosf(M_PI_F/4.0f)*ohm+ohm*ohm)/c;
+ lpfData->delay_element_1 = 0.0f;
+ lpfData->delay_element_2 = 0.0f;
+}
+
+float lpf2pApply(lpf2pData* lpfData, float sample)
+{
+ float delay_element_0 = sample - lpfData->delay_element_1 * lpfData->a1 - lpfData->delay_element_2 * lpfData->a2;
+ if (!isfinite(delay_element_0)) {
+ // don't allow bad values to propigate via the filter
+ delay_element_0 = sample;
+ }
+
+ float output = delay_element_0 * lpfData->b0 + lpfData->delay_element_1 * lpfData->b1 + lpfData->delay_element_2 * lpfData->b2;
+
+ lpfData->delay_element_2 = lpfData->delay_element_1;
+ lpfData->delay_element_1 = delay_element_0;
+ return output;
+}
+
+float lpf2pReset(lpf2pData* lpfData, float sample)
+{
+ float dval = sample / (lpfData->b0 + lpfData->b1 + lpfData->b2);
+ lpfData->delay_element_1 = dval;
+ lpfData->delay_element_2 = dval;
+ return lpf2pApply(lpfData, sample);
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/kve/kve.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/kve/kve.c
new file mode 100644
index 0000000..b49dc2a
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/kve/kve.c
@@ -0,0 +1,166 @@
+
+#include "kve/kve.h"
+#include "kve/kve_storage.h"
+
+#include "debug.h"
+
+#include <stdbool.h>
+#include <string.h>
+
+#define VERSION_ADDRESS (0)
+#define FIRST_ITEM_ADDRESS (1)
+
+// Current version of the KVE table is 1
+#define KVE_VERSION (1)
+
+static size_t min(size_t a, size_t b)
+{
+ if (a < b) {
+ return a;
+ } else {
+ return b;
+ }
+}
+
+// Utility function
+static bool appendItemToEnd(kveMemory_t *kve, size_t address, const char* key, const void* buffer, size_t length) {
+ size_t itemAddress = kveStorageFindEnd(kve, address);
+
+ // If it is over the end of the memory, table corrupted
+ // Do not write anything ...
+ if (KVE_STORAGE_IS_VALID(itemAddress) == false) {
+ DEBUG_PRINT("Error: table corrupted!\n");
+ return false;
+ }
+
+ // Test that there is enough space to write the item
+ if ((itemAddress + sizeof(kveItemHeader_t) + strlen(key) + length + END_TAG_LENDTH) < kve->memorySize) {
+ itemAddress += kveStorageWriteItem(kve, itemAddress, key, buffer, length);
+ kveStorageWriteEnd(kve, itemAddress);
+ } else {
+ // Otherwise, defrag and try to insert again!
+ kveDefrag(kve);
+
+ itemAddress = kveStorageFindEnd(kve, FIRST_ITEM_ADDRESS);
+
+ if ((itemAddress + sizeof(kveItemHeader_t) + strlen(key) + length + END_TAG_LENDTH) < kve->memorySize) {
+ itemAddress += kveStorageWriteItem(kve, itemAddress, key, buffer, length);
+ kveStorageWriteEnd(kve, itemAddress);
+ } else {
+ // Memory full!
+ DEBUG_PRINT("Error: memory full!");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+// Public API
+
+void kveDefrag(kveMemory_t *kve) {
+ size_t holeAddress = kveStorageFindHole(kve, FIRST_ITEM_ADDRESS);
+ size_t itemAddress;
+ size_t nextHoleAddress;
+
+ while(KVE_STORAGE_IS_VALID(holeAddress)) {
+ itemAddress = kveStorageFindNextItem(kve, holeAddress);
+
+ if (KVE_STORAGE_IS_VALID(itemAddress) == false) {
+ // This hole is at the end, lets crop it
+ kveStorageWriteEnd(kve, holeAddress);
+ break;
+ }
+
+ nextHoleAddress = kveStorageFindHole(kve, itemAddress);
+
+ if(KVE_STORAGE_IS_VALID(nextHoleAddress) == false) {
+ // If there is the end after this group of item, lets copy up to the end
+ nextHoleAddress = kveStorageFindEnd(kve, itemAddress);
+ }
+
+ size_t lenghtToMove = nextHoleAddress - itemAddress;
+
+ kveStorageMoveMemory(kve, itemAddress, holeAddress, lenghtToMove);
+
+ kveStorageWriteHole(kve, holeAddress + lenghtToMove, itemAddress - holeAddress);
+
+ holeAddress = holeAddress + lenghtToMove;
+ }
+}
+
+bool kveStore(kveMemory_t *kve, char* key, const void* buffer, size_t length) {
+ size_t itemAddress;
+
+ // Search if the key is already present in the table
+ itemAddress = kveStorageFindItemByKey(kve, FIRST_ITEM_ADDRESS, key);
+ if (KVE_STORAGE_IS_VALID(itemAddress) == false) {
+ // Item does not exit, find the end of the table to insert it
+ return appendItemToEnd(kve, FIRST_ITEM_ADDRESS, key, buffer, length);
+ } else {
+ // Item exist, verify that the data has the same size
+ kveItemHeader_t currentItem = kveStorageGetItemInfo(kve, itemAddress);
+ uint16_t newLength = length + 3 + strlen(key);
+ if (currentItem.full_length != newLength) {
+ // If not, delete the item and find the end of the table
+ kveStorageWriteHole(kve, itemAddress, currentItem.full_length);
+ return appendItemToEnd(kve, FIRST_ITEM_ADDRESS, key, buffer, length);
+ } else {
+ kveStorageWriteItem(kve, itemAddress, key, buffer, length);
+ }
+ }
+
+ return true;
+}
+
+
+size_t kveFetch(kveMemory_t *kve, const char* key, void* buffer, size_t bufferLength)
+{
+ size_t itemAddress = kveStorageFindItemByKey(kve, FIRST_ITEM_ADDRESS, key);
+
+ if (KVE_STORAGE_IS_VALID(itemAddress)) {
+ kveItemHeader_t header = kveStorageGetItemInfo(kve, itemAddress);
+ const size_t storeSize = header.full_length - header.key_length - sizeof(header);
+ size_t readLength = min(storeSize, bufferLength);
+ return kveStorageGetBuffer(kve, itemAddress, header, buffer, readLength);
+ }
+ return 0;
+}
+
+bool kveDelete(kveMemory_t *kve, char* key) {
+ size_t itemAddress = kveStorageFindItemByKey(kve, FIRST_ITEM_ADDRESS, key);
+
+ if (KVE_STORAGE_IS_VALID(itemAddress)) {
+ kveItemHeader_t itemInfo = kveStorageGetItemInfo(kve, itemAddress);
+ kveStorageWriteHole(kve, itemAddress, itemInfo.full_length);
+ return true;
+ }
+
+ return false;
+}
+
+void kveFormat(kveMemory_t *kve) {
+ uint8_t version = KVE_VERSION;
+ kve->write(VERSION_ADDRESS, &version, 1);
+ kveStorageWriteEnd(kve, FIRST_ITEM_ADDRESS);
+}
+
+bool kveCheck(kveMemory_t *kve) {
+
+ // Check version
+ uint8_t version;
+ kve->read(VERSION_ADDRESS, &version, 1);
+ if (version != KVE_VERSION) {
+ return false;
+ }
+
+ // Check table consistency
+ size_t endAddress = kveStorageFindEnd(kve, FIRST_ITEM_ADDRESS);
+
+ // If it is not possible to get to the end tag, the table is corupted
+ if (!KVE_STORAGE_IS_VALID(endAddress)) {
+ return false;
+ }
+
+ return true;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/kve/kve_storage.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/kve/kve_storage.c
new file mode 100644
index 0000000..32f83ab
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/kve/kve_storage.c
@@ -0,0 +1,233 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * kveStorage.c - Low level storage functions
+ *
+ */
+
+#include "kve/kve_storage.h"
+
+#include <stdint.h>
+#include <string.h>
+
+static size_t min(size_t a, size_t b)
+{
+ if (a < b) {
+ return a;
+ } else {
+ return b;
+ }
+}
+
+#define END_TAG (0xffffu)
+
+int kveStorageWriteItem(kveMemory_t *kve, size_t address, const char* key, const void* buffer, size_t length)
+{
+ kveItemHeader_t header;
+ header.key_length = strlen(key);
+ header.full_length = 2 + 1 + header.key_length + length;
+
+ // Write full_length, key_length, key and buffer
+ kve->write(address, &header, sizeof(header));
+ kve->write(address + sizeof(header), key, header.key_length);
+ kve->write(address + sizeof(header) + header.key_length, buffer, length);
+
+ kve->flush();
+
+ return header.full_length;
+}
+
+uint16_t kveStorageWriteHole(kveMemory_t *kve, size_t address, size_t full_length) {
+ kveItemHeader_t header;
+ header.full_length = full_length;
+ header.key_length = 0;
+
+ kve->write(address, &header, sizeof(header));
+ kve->flush();
+
+ return full_length;
+}
+
+uint16_t kveStorageWriteEnd(kveMemory_t *kve, size_t address) {
+ uint16_t endTag = END_TAG;
+
+ kve->write(address, &endTag, 2);
+
+ kve->flush();
+
+ return 2;
+}
+
+void kveStorageMoveMemory(kveMemory_t *kve, size_t sourceAddress, size_t destinationAddress, size_t length)
+{
+ static char moveBuffer[32];
+ size_t leftToMove = length;
+
+ while (leftToMove > 0) {
+ size_t moving = min(leftToMove, (size_t)32);
+ kve->read(sourceAddress, moveBuffer, moving);
+ kve->write(destinationAddress, moveBuffer, moving);
+
+ sourceAddress += moving;
+ destinationAddress += moving;
+ leftToMove -= moving;
+ }
+
+ kve->flush();
+}
+
+size_t kveStorageFindItemByKey(kveMemory_t *kve, size_t address, const char * key) {
+ char searchBuffer[255];
+ size_t currentAddress = address;
+ uint16_t length;
+ uint8_t keyLength;
+ uint8_t searchedKeyLength = strlen(key);
+
+
+ while (currentAddress < (kve->memorySize - 3)) {
+ kve->read(currentAddress, searchBuffer, 3);
+ length = searchBuffer[0] + (searchBuffer[1]<<8);
+ keyLength = searchBuffer[2];
+
+ if (length == END_TAG) {
+ return SIZE_MAX;
+ }
+
+ if (keyLength == searchedKeyLength) {
+ kve->read(currentAddress + 3, &searchBuffer, searchedKeyLength);
+ if (!memcmp(key, searchBuffer, keyLength)) {
+ return currentAddress;
+ }
+ }
+
+ currentAddress += length;
+ }
+
+ return SIZE_MAX;
+}
+
+size_t kveStorageFindEnd(kveMemory_t *kve, size_t address) {
+ size_t currentAddress = address;
+ kveItemHeader_t header;
+
+ while (currentAddress < (kve->memorySize - 2)) {
+ kve->read(currentAddress, &header, sizeof(header));
+ if (header.full_length == END_TAG) {
+ return currentAddress;
+ }
+
+ // An item must at least have a key of len>=1
+ if (header.full_length < (sizeof(header) + 1)) {
+ return KVE_STORAGE_INVALID_ADDRESS;
+ }
+ currentAddress += header.full_length;
+ }
+
+ // This is a corrupted table!
+ return KVE_STORAGE_INVALID_ADDRESS;
+}
+
+size_t kveStorageFindHole(kveMemory_t *kve, size_t address) {
+ size_t currentAddress = address;
+ kveItemHeader_t header;
+
+ while (currentAddress < (kve->memorySize - 2)) {
+ kve->read(currentAddress, &header, sizeof(header));
+ if (header.key_length == 0) {
+ return currentAddress;
+ }
+ currentAddress += header.full_length;
+ }
+
+ // This is a corrupted table!
+ return KVE_STORAGE_INVALID_ADDRESS;
+}
+
+
+size_t kveStorageFindNextItem(kveMemory_t *kve, size_t address)
+{
+ size_t currentAddress = address;
+ kveItemHeader_t header;
+
+ // Jump over the current item
+ kve->read(currentAddress, &header, sizeof(header));
+ if (header.full_length == END_TAG) {
+ return KVE_STORAGE_INVALID_ADDRESS;
+ }
+ currentAddress += header.full_length;
+
+ while (currentAddress < (kve->memorySize - 3)) {
+ kve->read(currentAddress, &header, sizeof(header));
+
+
+ if (header.full_length == END_TAG) {
+ return KVE_STORAGE_INVALID_ADDRESS;
+ }
+
+ if (header.key_length != 0) {
+ return currentAddress;
+ }
+
+ currentAddress += header.full_length;
+ }
+
+ return KVE_STORAGE_INVALID_ADDRESS;
+}
+
+kveItemHeader_t kveStorageGetItemInfo(kveMemory_t *kve, size_t address)
+{
+ kveItemHeader_t header;
+
+ kve->read(address, &header, sizeof(header));
+
+ return header;
+}
+
+size_t kveStorageGetKeyLength(kveItemHeader_t header)
+{
+ return header.key_length;
+}
+
+size_t kveStorageGetBufferLength(kveItemHeader_t header)
+{
+ return header.full_length - sizeof(header) - header.key_length;
+}
+
+size_t kveStorageGetKey(kveMemory_t *kve, size_t address, kveItemHeader_t header, char* key, size_t maxLength)
+{
+ size_t sizeToRead = min(maxLength, header.key_length);
+
+ kve->read(address + sizeof(header), key, sizeToRead);
+
+ return sizeToRead;
+}
+
+size_t kveStorageGetBuffer(kveMemory_t *kve, size_t address, kveItemHeader_t header, void* buffer, size_t maxLength)
+{
+ size_t sizeToRead = min(kveStorageGetBufferLength(header), maxLength);
+
+ kve->read(address + sizeof(header) + header.key_length, buffer, sizeToRead);
+
+ return sizeToRead;
+}
\ No newline at end of file
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/lighthouse_calibration.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/lighthouse_calibration.c
new file mode 100644
index 0000000..312f537
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/lighthouse_calibration.c
@@ -0,0 +1,111 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2018 Bitcraze AB
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * lighthouse_calibration.c: lighthouse positioning angle calibration
+ */
+
+#include "lighthouse_calibration.h"
+
+#include <math.h>
+
+// Enable to use only phase for calibration. The more complex calibration does not
+// seem to give as good results as the simple one(!)
+#define USE_SIMPLE_CALIBRATION
+
+void lighthouseCalibrationInitFromFrame(lighthouseCalibration_t *calib, struct ootxDataFrame_s *frame)
+{
+ calib->axis[0].phase = frame->phase0;
+ calib->axis[0].tilt = frame->tilt0;
+ calib->axis[0].curve = frame->curve0;
+ calib->axis[0].gibmag = frame->gibmag0;
+ calib->axis[0].gibphase = frame->gibphase0;
+
+ calib->axis[1].phase = frame->phase1;
+ calib->axis[1].tilt = frame->tilt1;
+ calib->axis[1].curve = frame->curve1;
+ calib->axis[1].gibmag = frame->gibmag1;
+ calib->axis[1].gibphase = frame->gibphase1;
+
+ calib->valid = true;
+}
+
+#ifndef USE_SIMPLE_CALIBRATION
+// Calibration function inspired from https://github.com/cnlohr/libsurvive/issues/18#issuecomment-386190279
+
+// Given a predicted sensor position in the lighthouse frame, predict the perturbed measurements
+static void predict(const lighthouseCalibration_t* calib, float const* xy, float* ang) {
+ float tiltX = calib->axis[0].tilt;
+ float phaseX = calib->axis[0].phase;
+ float curveX = calib->axis[0].curve;
+ float gibmagX = calib->axis[0].gibmag;
+ float gibphaseX = calib->axis[0].gibphase;
+
+ float tiltY = calib->axis[1].tilt;
+ float phaseY = calib->axis[1].phase;
+ float curveY = calib->axis[1].curve;
+ float gibmagY = calib->axis[1].gibmag;
+ float gibphaseY = calib->axis[1].gibphase;
+
+ ang[0] = atanf(xy[0] - (tiltX + curveX * xy[1]) * xy[1]);
+ ang[1] = atanf(xy[1] - (tiltY + curveY * xy[0]) * xy[0]);
+ ang[0] -= phaseX + gibmagX * sinf(ang[0] + gibphaseX);
+ ang[1] -= phaseY + gibmagY * sinf(ang[1] + gibphaseY);
+}
+
+// Given the perturbed lighthouse angle, predict the ideal angle
+static void correct(const lighthouseCalibration_t* calib, const float * angle, float * corrected) {
+ float ideal[2], pred[2], xy[2];
+ ideal[0] = angle[0];
+ ideal[1] = angle[1];
+ for (int i = 0; i < 10; i++) {
+ xy[0] = tanf(ideal[0]);
+ xy[1] = tanf(ideal[1]);
+ predict(calib, xy, pred);
+ ideal[0] += (angle[0] - pred[0]);
+ ideal[1] += (angle[1] - pred[1]);
+ }
+ corrected[0] = ideal[0];
+ corrected[1] = ideal[1];
+}
+#endif
+
+void lighthouseCalibrationApply(lighthouseCalibration_t* calib, float rawAngles[2], float correctedAngles[2])
+{
+ if (calib->valid) {
+ #ifdef USE_SIMPLE_CALIBRATION
+ correctedAngles[0] = rawAngles[0] + calib->axis[0].phase;
+ correctedAngles[1] = rawAngles[1] + calib->axis[1].phase;
+ #else
+ correct(calib, rawAngles, correctedAngles);
+ #endif
+ } else {
+ correctedAngles[0] = rawAngles[0];
+ correctedAngles[1] = rawAngles[1];
+ }
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/lighthouse_geometry.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/lighthouse_geometry.c
new file mode 100644
index 0000000..308eeca
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/lighthouse_geometry.c
@@ -0,0 +1,228 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Code addapted from ashtuchkin's Vive DIY position sensor
+ * see https://github.com/ashtuchkin/vive-diy-position-sensor/
+ *
+ * Copyright (c) 2016 Alexander Shtuchkin
+ * Copyright (C) 2018 Bitcraze AB
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * lighthouseGeometry.c: lighthouse tracking system geometry functions
+ */
+
+#include "lighthouse_geometry.h"
+
+static void vec_cross_product(const vec3d a, const vec3d b, vec3d res) {
+ res[0] = a[1]*b[2] - a[2]*b[1];
+ res[1] = a[2]*b[0] - a[0]*b[2];
+ res[2] = a[0]*b[1] - a[1]*b[0];
+}
+
+static float vec_dot(const vec3d a, const vec3d b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+
+static void vec_add(const vec3d a, const vec3d b, vec3d r) {
+ r[0] = a[0] + b[0];
+ r[1] = a[1] + b[1];
+ r[2] = a[2] + b[2];
+}
+
+static float vec_length(const vec3d vec) {
+ float pow = vec_dot(vec, vec);
+
+ float res;
+ arm_sqrt_f32(pow, &res);
+ return res;
+}
+
+static bool intersect_lines(vec3d orig1, vec3d vec1, vec3d orig2, vec3d vec2, vec3d res, float *dist) {
+ // Algoritm: http://geomalgorithms.com/a07-_distance.html#Distance-between-Lines
+
+ vec3d w0 = {};
+ arm_sub_f32(orig1, orig2, w0, vec3d_size);
+
+ float a, b, c, d, e;
+ arm_dot_prod_f32(vec1, vec1, vec3d_size, &a);
+ arm_dot_prod_f32(vec1, vec2, vec3d_size, &b);
+ arm_dot_prod_f32(vec2, vec2, vec3d_size, &c);
+ arm_dot_prod_f32(vec1, w0, vec3d_size, &d);
+ arm_dot_prod_f32(vec2, w0, vec3d_size, &e);
+
+ float denom = a * c - b * b;
+ if (fabsf(denom) < 1e-5f)
+ return false;
+
+ // Closest point to 2nd line on 1st line
+ float t1 = (b * e - c * d) / denom;
+ vec3d pt1 = {};
+ arm_scale_f32(vec1, t1, pt1, vec3d_size);
+ arm_add_f32(pt1, orig1, pt1, vec3d_size);
+
+ // Closest point to 1st line on 2nd line
+ float t2 = (a * e - b * d) / denom;
+ vec3d pt2 = {};
+ arm_scale_f32(vec2, t2, pt2, vec3d_size);
+ arm_add_f32(pt2, orig2, pt2, vec3d_size);
+
+ // Result is in the middle
+ vec3d tmp = {};
+ arm_add_f32(pt1, pt2, tmp, vec3d_size);
+ arm_scale_f32(tmp, 0.5f, res, vec3d_size);
+
+ // Dist is distance between pt1 and pt2
+ arm_sub_f32(pt1, pt2, tmp, vec3d_size);
+ *dist = vec_length(tmp);
+
+ return true;
+}
+
+bool lighthouseGeometryGetPositionFromRayIntersection(baseStationGeometry_t baseStations[2], float angles1[2], float angles2[2], vec3d position, float *position_delta)
+{
+ static vec3d ray1, ray2, origin1, origin2;
+
+ lighthouseGeometryGetRay(&baseStations[0], angles1[0], angles1[1], ray1);
+ lighthouseGeometryGetBaseStationPosition(&baseStations[0], origin1);
+
+ lighthouseGeometryGetRay(&baseStations[1], angles2[0], angles2[1], ray2);
+ lighthouseGeometryGetBaseStationPosition(&baseStations[1], origin2);
+
+ return intersect_lines(origin1, ray1, origin2, ray2, position, position_delta);
+}
+
+void lighthouseGeometryGetBaseStationPosition(baseStationGeometry_t* bs, vec3d baseStationPos) {
+ // TODO: Make geometry adjustments within base station.
+ vec3d rotated_origin_delta = {};
+ //vec3d base_origin_delta = {-0.025f, -0.025f, 0.f}; // Rotors are slightly off center in base station.
+ // arm_matrix_instance_f32 origin_vec = {3, 1, base_origin_delta};
+ // arm_matrix_instance_f32 origin_rotated_vec = {3, 1, rotated_origin_delta};
+ // arm_mat_mult_f32(&source_rotation_matrix, &origin_vec, &origin_rotated_vec);
+ arm_add_f32(bs->origin, rotated_origin_delta, baseStationPos, vec3d_size);
+}
+
+void lighthouseGeometryGetRay(const baseStationGeometry_t* baseStationGeometry, const float angleH, const float angleV, vec3d ray) {
+ vec3d a = {arm_sin_f32(angleH), -arm_cos_f32(angleH), 0}; // Normal vector to X plane
+ vec3d b = {-arm_sin_f32(angleV), 0, arm_cos_f32(angleV)}; // Normal vector to Y plane
+
+ vec3d raw_ray = {};
+ vec_cross_product(b, a, raw_ray); // Intersection of two planes -> ray vector.
+ float len = vec_length(raw_ray);
+ arm_scale_f32(raw_ray, 1 / len, raw_ray, vec3d_size); // Normalize raw ray length.
+
+ arm_matrix_instance_f32 source_rotation_matrix = {3, 3, (float32_t *)baseStationGeometry->mat};
+ arm_matrix_instance_f32 ray_vec = {3, 1, raw_ray};
+ arm_matrix_instance_f32 ray_rotated_vec = {3, 1, ray};
+ arm_mat_mult_f32(&source_rotation_matrix, &ray_vec, &ray_rotated_vec);
+}
+
+bool lighthouseGeometryIntersectionPlaneVector(const vec3d linePoint, const vec3d lineVec, const vec3d planePoint, const vec3d PlaneNormal, vec3d intersectionPoint) {
+ float p = -vec_dot(lineVec, PlaneNormal);
+ if (p == 0.0f) {
+ // Line and plane is parallel, no intersection point
+ return false;
+ }
+
+ vec3d lp = {linePoint[0] - planePoint[0], linePoint[1] - planePoint[1], linePoint[2] - planePoint[2]};
+ float t = vec_dot(PlaneNormal, lp) / p;
+
+ intersectionPoint[0] = linePoint[0] + lineVec[0] * t;
+ intersectionPoint[1] = linePoint[1] + lineVec[1] * t;
+ intersectionPoint[2] = linePoint[2] + lineVec[2] * t;
+
+ return true;
+}
+
+void lighthouseGeometryGetSensorPosition(const vec3d cfPos, const arm_matrix_instance_f32 *R, vec3d sensorPosition, vec3d pos) {
+ arm_matrix_instance_f32 LOCAL_POS = {3, 1, sensorPosition};
+
+ vec3d rotatedPos = {0};
+ arm_matrix_instance_f32 ROTATED_POS = {1, 3, rotatedPos};
+ arm_mat_mult_f32(R, &LOCAL_POS, &ROTATED_POS);
+
+ vec_add(cfPos, rotatedPos, pos);
+}
+
+bool lighthouseGeometryYawDelta(const vec3d ipv, const vec3d spv, const vec3d n, float* yawDelta) {
+ float spvn = vec_length(spv);
+ float ipvn = vec_length(ipv);
+
+ const float minIntersectionVectorLength = 0.0001f;
+ if (ipvn < minIntersectionVectorLength) {
+ return false;
+ }
+
+ // Angle between vectors
+ float a = vec_dot(spv, ipv) / (spvn * ipvn);
+
+ // Handle rouding errors
+ if (a > 1.0f) {
+ a = 1.0f;
+ }
+ if (a < -1.0f) {
+ a = -1.0f;
+ }
+
+ float delta = acosf(a);
+
+ // Figure our the sign of the angle by looking at the cross product of the vectors in relation to the normal
+ float nt[3];
+ vec_cross_product(spv, ipv, nt);
+
+ if (vec_dot(n, nt) > 0.0f) {
+ delta = -delta;
+ }
+
+ *yawDelta = delta;
+ return true;
+}
+
+void lighthouseGeometryCalculateAnglesFromRotationMatrix(baseStationGeometry_t* baseStationGeometry, baseStationEulerAngles_t* baseStationEulerAngles) {
+
+ /*
+ * roll pitch yaw Rotation matrix
+ *
+ R = | R00 R01 R02 |
+ | R10 R11 R12 |
+ | R20 R21 R22 |
+ */
+
+ float32_t R00 = (float32_t)baseStationGeometry->mat[0][0];
+ float32_t R01 = (float32_t)baseStationGeometry->mat[0][1];
+ float32_t R02 = (float32_t)baseStationGeometry->mat[0][2];
+ float32_t R12 = (float32_t)baseStationGeometry->mat[1][2];
+ float32_t R22 = (float32_t)baseStationGeometry->mat[2][2];
+
+
+ float pitchBaseStation = asin(R02);
+ float yawBaseStation = -1.0*atan2(R01,R00);
+ float rollBaseStation = -1.0*atan2(R12,R22);
+
+ baseStationEulerAngles->roll=rollBaseStation;
+ baseStationEulerAngles->pitch=pitchBaseStation;
+ baseStationEulerAngles->yaw=yawBaseStation;
+
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/ootx_decoder.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/ootx_decoder.c
new file mode 100644
index 0000000..8995ecd
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/ootx_decoder.c
@@ -0,0 +1,123 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2018 Bitcraze AB
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * lighthouse_ootx.c: lighthouse positioning ootx (slow) data receiver
+ */
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "ootx_decoder.h"
+
+// #include "debug_cf.h"
+
+uint16_t betole(uint16_t value)
+{
+ return ((value&0xff00u)>>8) | ((value&0xffu)<<8);
+}
+
+// Frame format described there: https://github.com/nairol/LighthouseRedox/blob/master/docs/Light%20Emissions.md#ootx-frame
+bool ootxDecoderProcessBit(ootxDecoderState_t * state, int data)
+{
+ data &= 1;
+
+ // Synchronization finder
+ if (state->nZeros == 17 && data == 1) {
+ state->synchronized = true;
+ state->bitInWord = 0;
+ state->wordReceived = 0;
+ state->rxState = rxLength;
+ // DEBUG_PRINT("Synchronized!\n");
+ return false;
+ }
+ if (data == 0) {
+ state->nZeros += 1;
+ } else {
+ state->nZeros = 0;
+ }
+
+ if (state->synchronized) {
+ // Detect the stuffing bit
+ if (state->bitInWord == 16) {
+ // If the stuffing bit is ==0 -> framing error
+ if (data == 0) {
+ // DEBUG_PRINT("Unsynchronized!\n");
+ state->synchronized = false;
+ return false;
+ }
+ state->bitInWord = 0;
+
+ // At the stuffing bit after CRC1, we are done!
+ // TODO: Check CRC!
+ if (state->rxState == rxDone) {
+ state->synchronized = false;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ state->currentWord = (state->currentWord<<1) | data;
+ state->bitInWord += 1;
+
+ // One word received
+ if (state->bitInWord == 16) {
+ switch (state->rxState) {
+ case rxLength:
+ state->frameLength = betole(state->currentWord);
+ // DEBUG_PRINT("Length %0d\n", state->frameLength);
+ if (state->frameLength > OOTX_MAX_FRAME_LENGTH) {
+ state->synchronized = false;
+ return false;
+ }
+ state->rxState = rxData;
+ break;
+ case rxData:
+ // DEBUG_PRINT("data[%d]\n", state->wordReceived);
+ state->data[state->wordReceived] = betole(state->currentWord);
+ state->wordReceived += 1;
+ if (2*state->wordReceived >= state->frameLength) {
+ state->rxState = rxCrc0;
+ }
+ break;
+ case rxCrc0:
+ // DEBUG_PRINT("CRC0\n");
+ state->crc32 = betole(state->currentWord);
+ state->rxState = rxCrc1;
+ break;
+ case rxCrc1:
+ // DEBUG_PRINT("CRC1\n");
+ state->crc32 |= (betole(state->currentWord)<<16ul);
+ state->rxState = rxDone;
+ break;
+ case rxDone: break;
+ }
+ }
+ }
+ return false;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor.c
new file mode 100644
index 0000000..c099d71
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor.c
@@ -0,0 +1,50 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * pulse_processor.c - pulse decoding for lighthouse V1 base stations
+ *
+ */
+
+#include "pulse_processor.h"
+
+
+void pulseProcessorApplyCalibration(pulseProcessor_t *state, pulseProcessorResult_t* angles, int baseStation)
+{
+ for (int sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {
+ pulseProcessorBaseStationMeasuremnt_t* bsMeasurement = &angles->sensorMeasurements[sensor].baseStatonMeasurements[baseStation];
+ lighthouseCalibrationApply(&state->bsCalibration[baseStation], bsMeasurement->angles, bsMeasurement->correctedAngles);
+ }
+}
+
+/**
+ * @brief Clear result struct
+ *
+ * @param angles
+ */
+void pulseProcessorClear(pulseProcessorResult_t* angles, int baseStation)
+{
+ for (size_t sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {
+ angles->sensorMeasurements[sensor].baseStatonMeasurements[baseStation].validCount = 0;
+ }
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor_v1.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor_v1.c
new file mode 100644
index 0000000..536e927
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor_v1.c
@@ -0,0 +1,497 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 - 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * pulse_processor_v1.c - pulse decoding for lighthouse V1 base stations
+ *
+ */
+
+#include "pulse_processor_v1.h"
+
+#include <string.h>
+#include <math.h>
+#include "test_support.h"
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+// Decoding contants
+// Times are expressed in a 24MHz clock
+#define FRAME_LENGTH 200000 // 8.333ms
+#define SWEEP_MAX_WIDTH 512 // 20us
+
+#define SYNC_DIVIDER 250
+#define SYNC_BASE_WIDTH (1250 + (SYNC_DIVIDER / 2))
+#define SYNC_MIN_WIDTH (1250 - SYNC_DIVIDER)
+#define SYNC_MAX_WIDTH (1250 + SYNC_DIVIDER * 8)
+
+#define SYNC_SEPARATION 10000
+#define SYNC_SEPARATION_MAX_DISPERSION 2500
+#define SYNC_MIN_SEPARATION (SYNC_SEPARATION - SYNC_SEPARATION_MAX_DISPERSION)
+#define SYNC_MAX_SEPARATION (SYNC_SEPARATION + SYNC_SEPARATION_MAX_DISPERSION)
+
+#define SENSOR_MAX_DISPERTION 10
+#define MAX_FRAME_LENGTH_NOISE 400
+
+#define FRAME_WIDTH_MIN 395000
+#define FRAME_WIDTH_MAX 405000
+
+
+TESTABLE_STATIC int findSyncTime(const pulseProcessorPulse_t pulseHistory[], uint32_t *sync0Time);
+TESTABLE_STATIC bool getSystemSyncTime(const uint32_t syncTimes[], size_t nSyncTimes, uint32_t *syncTime);
+
+static void resetPulseHistory(pulseProcessor_t *state) {
+ memset(state->pulseHistoryIdx, 0, sizeof(state->pulseHistoryIdx));
+}
+
+static void synchronize(pulseProcessor_t *state, int sensor, uint32_t timestamp, uint32_t width)
+{
+ state->pulseHistory[sensor][state->pulseHistoryIdx[sensor]].timestamp = timestamp;
+ state->pulseHistory[sensor][state->pulseHistoryIdx[sensor]].width = width;
+
+ state->pulseHistoryIdx[sensor] += 1;
+
+ // As soon as one of the history buffers is full, run the synchronization algorithm!
+ if (state->pulseHistoryIdx[sensor] >= PULSE_PROCESSOR_HISTORY_LENGTH) {
+ static uint32_t sync0Times[PULSE_PROCESSOR_N_SENSORS];
+ size_t syncTimeCount = 0;
+
+ for (int i=0; i<PULSE_PROCESSOR_N_SENSORS; i++) {
+ const int bsSyncsFound = findSyncTime(state->pulseHistory[i], &sync0Times[syncTimeCount]);
+ if (bsSyncsFound >= state->basestationsSynchronizedCount) {
+ state->basestationsSynchronizedCount = bsSyncsFound;
+ syncTimeCount += 1;
+ }
+
+ uint32_t validSync0Time = 0;
+ if (getSystemSyncTime(sync0Times, syncTimeCount, &validSync0Time)) {
+ state->synchronized = true;
+ state->currentSync0 = validSync0Time;
+ state->lastSync = validSync0Time;
+ break;
+ }
+ }
+
+ resetPulseHistory(state);
+ }
+}
+
+static bool isSweep(pulseProcessor_t *state, unsigned int timestamp, int width)
+{
+ uint32_t delta = TS_DIFF(timestamp, state->lastSync);
+ return ((delta > SYNC_MAX_SEPARATION) && (delta < (FRAME_LENGTH - (2*SYNC_MAX_SEPARATION)))) || (width < SWEEP_MAX_WIDTH);
+}
+
+TESTABLE_STATIC bool isSync(pulseProcessor_t *state, unsigned int timestamp)
+{
+ uint32_t delta = TS_DIFF(timestamp, state->currentSync0);
+ int deltaModulo = delta % FRAME_LENGTH;
+
+ // We expect a modulo close to 0, detect and handle wrapping around FRAME_LENGTH
+ if (deltaModulo > (FRAME_LENGTH/2)) {
+ deltaModulo -= FRAME_LENGTH;
+ }
+
+ if ((deltaModulo > -1*MAX_FRAME_LENGTH_NOISE) && (deltaModulo < SYNC_MAX_SEPARATION)) {
+ return true;
+ }
+ return false;
+}
+
+/**
+ * @brief Get the Base Station Id
+ *
+ * This function looks at the pulse position modulo FRAME_LENGTH in relation to
+ * the latest sync0. Values ~0 means a Sync0 pulse, ~19200 means a Sync1.
+ *
+ * @param state State of the pulse processor
+ * @param timestamp Timestamp of the syn to process
+ * @return 0 for Sync0, 1 for Sync1
+ */
+TESTABLE_STATIC int getBaseStationId(pulseProcessor_t *state, unsigned int timestamp) {
+ int baseStation = 0;
+
+ uint32_t delta = TS_DIFF(timestamp, state->currentSync0);
+ int deltaModulo = delta % FRAME_LENGTH;
+
+ // We expect a modulo close to 0, detect and handle wrapping around FRAME_LENGTH
+ if (deltaModulo > (FRAME_LENGTH/2)) {
+ deltaModulo -= FRAME_LENGTH;
+ }
+
+ if (deltaModulo > (SYNC_SEPARATION/2)) {
+ baseStation = 1;
+ }
+
+ return baseStation;
+}
+
+static SweepDirection getAxis(int width) {
+ SweepDirection result = sweepDirection_x;
+
+ if ((((width-SYNC_BASE_WIDTH)/SYNC_DIVIDER)&0x01) != 0) {
+ result = sweepDirection_y;
+ }
+
+ return result;
+}
+
+TESTABLE_STATIC bool isSweepActiveThisFrame(int width) {
+ return (((width-SYNC_BASE_WIDTH)/SYNC_DIVIDER)&0x04) == 0;
+}
+
+static int getOotxDataBit(int width)
+{
+ return (((width-SYNC_BASE_WIDTH)/SYNC_DIVIDER)&0x02) >> 1;
+}
+
+static void storeSweepData(pulseProcessor_t *state, int sensor, unsigned int timestamp) {
+ if (state->sweeps[sensor].state == sweepStorageStateWaiting) {
+ state->sweeps[sensor].timestamp = timestamp;
+ state->sweeps[sensor].state = sweepStorageStateValid;
+ } else {
+ state->sweeps[sensor].state = sweepStorageStateError;
+ }
+
+ state->sweepDataStored = true;
+}
+
+static void resetSweepData(pulseProcessor_t *state) {
+ for (size_t sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {
+ state->sweeps[sensor].state = sweepStorageStateWaiting;
+ }
+ state->sweepDataStored = false;
+}
+
+static void resetSynchronization(pulseProcessor_t *state)
+{
+ resetSweepData(state);
+ state->synchronized = false;
+}
+
+static bool processPreviousFrame(pulseProcessor_t *state, pulseProcessorResult_t* result, int *baseStation, int *axis) {
+ bool anglesMeasured = false;
+
+ if (state->sweepDataStored) {
+ for (size_t sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {
+ if (state->sweeps[sensor].state == sweepStorageStateValid) {
+ int delta = TS_DIFF(state->sweeps[sensor].timestamp, state->currentSync);
+ if (delta < FRAME_LENGTH) {
+ float frameWidth = state->frameWidth[state->currentBaseStation][state->currentAxis];
+
+ if ((frameWidth < FRAME_WIDTH_MIN) || (frameWidth > FRAME_WIDTH_MAX)) {
+ return false;
+ }
+
+ float center = frameWidth/4.0f;
+ float angle = (delta - center)*2*(float)M_PI/frameWidth;
+
+ *baseStation = state->currentBaseStation;
+ *axis = state->currentAxis;
+
+ pulseProcessorBaseStationMeasuremnt_t* bsMeasurement = &result->sensorMeasurements[sensor].baseStatonMeasurements[state->currentBaseStation];
+ bsMeasurement->angles[state->currentAxis] = angle;
+ bsMeasurement->validCount++;
+
+ anglesMeasured = true;
+ }
+ }
+ }
+
+ resetSweepData(state);
+ }
+
+ return anglesMeasured;
+}
+
+static void storeSyncData(pulseProcessor_t *state, int baseStation, unsigned int timestamp, unsigned int width) {
+ if (0 == baseStation) {
+ state->currentSync0 = timestamp;
+ state->currentSync0Width = width;
+ if (getAxis(width) == sweepDirection_x) {
+ uint32_t prevSync0X = state->currentSync0X;
+ state->currentSync0X = timestamp;
+ state->frameWidth[0][0] = TS_DIFF(state->currentSync0X, prevSync0X);
+ } else {
+ uint32_t prevSync0Y = state->currentSync0Y;
+ state->currentSync0Y = timestamp;
+ state->frameWidth[0][1] = TS_DIFF(state->currentSync0Y, prevSync0Y);
+ }
+ } else {
+ state->currentSync1Width = width;
+ if (getAxis(width) == sweepDirection_x) {
+ uint32_t prevSync1X = state->currentSync1X;
+ state->currentSync1X = timestamp;
+ state->frameWidth[1][0] = TS_DIFF(state->currentSync1X, prevSync1X);
+ } else {
+ uint32_t prevSync1Y = state->currentSync1Y;
+ state->currentSync1Y = timestamp;
+ state->frameWidth[1][1] = TS_DIFF(state->currentSync1Y, prevSync1Y);
+ }
+
+ state->currentSync0 = TS_DIFF(timestamp, SYNC_SEPARATION);
+ }
+
+ state->lastSync = timestamp;
+
+ if (isSweepActiveThisFrame(width)) {
+ state->currentBaseStation = baseStation;
+ state->currentAxis = getAxis(width);
+ state->currentSync = timestamp;
+ }
+}
+
+TESTABLE_STATIC bool isNewSync(uint32_t timestamp, uint32_t lastSync) {
+ const uint32_t min = (1 << PULSE_PROCESSOR_TIMESTAMP_BITWIDTH) - SENSOR_MAX_DISPERTION;
+ const uint32_t max = SENSOR_MAX_DISPERTION;
+
+ uint32_t diff = TS_DIFF(timestamp, lastSync);
+ return (diff > max) && (diff < min);
+}
+
+#ifndef UNIT_TEST_MODE
+#include "debug_cf.h"
+#else
+#include <stdio.h>
+#define DEBUG_PRINT printf
+#endif
+
+static void printBSInfo(struct ootxDataFrame_s *frame)
+{
+ DEBUG_PRINT("Got calibration from %08X\n", (unsigned int)frame->id);
+ DEBUG_PRINT(" phase0: %f\n", (double)frame->phase0);
+ DEBUG_PRINT(" phase1: %f\n", (double)frame->phase1);
+}
+
+static void decodeAndApplyBaseStationCalibrationData(pulseProcessor_t *state) {
+ if (!state->bsCalibration[0].valid &&
+ ootxDecoderProcessBit(&state->ootxDecoder0, getOotxDataBit(state->currentSync0Width))) {
+ printBSInfo(&state->ootxDecoder0.frame);
+ lighthouseCalibrationInitFromFrame(&state->bsCalibration[0], &state->ootxDecoder0.frame);
+ }
+ if (!state->bsCalibration[1].valid &&
+ ootxDecoderProcessBit(&state->ootxDecoder1, getOotxDataBit(state->currentSync1Width))) {
+ printBSInfo(&state->ootxDecoder1.frame);
+ lighthouseCalibrationInitFromFrame(&state->bsCalibration[1], &state->ootxDecoder1.frame);
+ }
+}
+
+static bool processSync(pulseProcessor_t *state, unsigned int timestamp, unsigned int width, pulseProcessorResult_t* angles, int *baseStation, int *axis) {
+ bool anglesMeasured = false;
+
+ if (isNewSync(timestamp, state->lastSync)) {
+ if (isSync(state, timestamp)) {
+ anglesMeasured = processPreviousFrame(state, angles, baseStation, axis);
+
+ if (anglesMeasured) {
+ decodeAndApplyBaseStationCalibrationData(state);
+ }
+
+ int baseStation = getBaseStationId(state, timestamp);
+
+ if (baseStation == 1 && state->basestationsSynchronizedCount < 2) {
+ resetSynchronization(state);
+ } else {
+ storeSyncData(state, baseStation, timestamp, width);
+ }
+ } else {
+ // Expected a sync but something is wrong, re-synchronize.
+ resetSynchronization(state);
+ }
+ }
+
+ return anglesMeasured;
+}
+
+static bool processWhenSynchronized(pulseProcessor_t *state, int sensor, unsigned int timestamp, unsigned int width, pulseProcessorResult_t* angles, int *baseStation, int *axis) {
+ bool anglesMeasured = false;
+
+ if (isSweep(state, timestamp, width)) {
+ storeSweepData(state, sensor, timestamp);
+ } else {
+ anglesMeasured = processSync(state, timestamp, width, angles, baseStation, axis);
+ }
+
+ return anglesMeasured;
+}
+
+
+bool pulseProcessorV1ProcessPulse(pulseProcessor_t *state, const pulseProcessorFrame_t* frameData, pulseProcessorResult_t* angles, int *baseStation, int *axis)
+{
+ bool anglesMeasured = false;
+
+ if (!state->synchronized) {
+ synchronize(state, frameData->sensor, frameData->timestamp, frameData->width);
+ } else {
+ anglesMeasured = processWhenSynchronized(state, frameData->sensor, frameData->timestamp, frameData->width, angles, baseStation, axis);
+ }
+
+ return anglesMeasured;
+}
+
+static bool isPulseASync(const pulseProcessorPulse_t* pulse) {
+ return (pulse->width > SYNC_MIN_WIDTH) && (pulse->width < SYNC_MAX_WIDTH);
+}
+
+static bool isPulseASweep(const pulseProcessorPulse_t* pulse) {
+ return pulse->width < SWEEP_MAX_WIDTH;
+}
+
+
+/**
+ * @brief Find the timestamp of the first sync0 pulse in the pulseHistory. Supports one and two
+ * base stations.
+ *
+ * @param pulseHistory PULSE_PROCESSOR_HISTORY_LENGTH pulses
+ * @param[out] sync0Time Timestamp of the first Sync0 written in this variable
+ * @return The nr of base stations with sync pulses that were found. 0 if no sync could be detected.
+ */
+TESTABLE_STATIC int findSyncTime(const pulseProcessorPulse_t pulseHistory[], uint32_t *sync0Time)
+{
+ int nFoundSync0 = 0;
+ int nFoundSync1 = 0;
+ uint32_t foundTimes[2];
+
+ bool wasPreviousPulseASweep = false;
+ if (isPulseASync(&pulseHistory[0])) {
+ wasPreviousPulseASweep = false;
+ } else if (isPulseASweep(&pulseHistory[0])) {
+ wasPreviousPulseASweep = true;
+ } else {
+ return 0;
+ }
+
+ for (int i=1; i<PULSE_PROCESSOR_HISTORY_LENGTH; i++) {
+ if (isPulseASync(&pulseHistory[i])) {
+ if (wasPreviousPulseASweep) {
+ foundTimes[nFoundSync0] = pulseHistory[i].timestamp;
+ nFoundSync0++;
+
+ if (nFoundSync0 == 2) {
+ break;
+ }
+ } else {
+ if (nFoundSync0 > 0) {
+ uint32_t syncSeparation = TS_DIFF(pulseHistory[i].timestamp, foundTimes[nFoundSync0 - 1]);
+ if (syncSeparation > SYNC_MIN_SEPARATION && syncSeparation < SYNC_MAX_SEPARATION) {
+ nFoundSync1++;
+ } else {
+ return 0;
+ }
+ }
+ }
+
+ wasPreviousPulseASweep = false;
+ } else if (isPulseASweep(&pulseHistory[i])) {
+ wasPreviousPulseASweep = true;
+ } else {
+ return 0;
+ }
+ }
+
+ int result = 0;
+ if (nFoundSync0 == 2) {
+ uint32_t frameLength = TS_DIFF(foundTimes[1], foundTimes[0]);
+ bool isFrameLengthWithinBoundaries = (frameLength < (FRAME_LENGTH + MAX_FRAME_LENGTH_NOISE) && frameLength > (FRAME_LENGTH - MAX_FRAME_LENGTH_NOISE));
+ if (isFrameLengthWithinBoundaries) {
+ *sync0Time = foundTimes[0];
+ result = 1;
+ if (nFoundSync1 > 0) {
+ result = 2;
+ }
+ }
+ }
+
+ return result;
+}
+
+/**
+ * @brief Get the System Sync time from sampled Sync0 time from multiple sensors
+ *
+ * This function places the Sync0 timestamps modulo the lighthouse V1 frame length
+ * to estimate if they can possibly be coming from the same lighthouse system.
+ * This allows to check that the sampling done on multiple receiving sensor is
+ * consistent.
+ *
+ * @param syncTimes Array of Sync0 timestamps
+ * @param nSyncTimes Number of timestamps in syncTimes array
+ * @param[out] syncTime Pointer to the variable where the resulting sync time is written
+ * @return true If an acceptable sync time could be calculated
+ * @return false If the sampled Sync0 timestamps do not make sense
+ */
+TESTABLE_STATIC bool getSystemSyncTime(const uint32_t syncTimes[], size_t nSyncTimes, uint32_t *syncTime)
+{
+ if (nSyncTimes == 0) {
+ return false;
+ }
+
+ // Detect if samples are wrapping
+ // If the samples are wrapping, all samples bellow PULSE_PROCESSOR_TIMESTAMP_MAX/2 will
+ // be pushed by (1<<TIMESTAMP_BITWIDTH) to correct the wrapping
+ bool isWrapping = false;
+ int wref = syncTimes[0];
+ for (size_t i=0; i<nSyncTimes; i++) {
+ if (abs(wref - (int)syncTimes[i]) > (PULSE_PROCESSOR_TIMESTAMP_MAX/2)) {
+ isWrapping = true;
+ }
+ }
+
+ int32_t differenceSum = 0;
+ int32_t reference = syncTimes[0] % FRAME_LENGTH;
+ if (isWrapping && syncTimes[0] < (PULSE_PROCESSOR_TIMESTAMP_MAX/2)) {
+ reference = (syncTimes[0] + (1<<PULSE_PROCESSOR_TIMESTAMP_BITWIDTH)) % FRAME_LENGTH;
+ }
+
+ int minDiff = INT32_MAX;
+ int maxDiff = INT32_MIN;
+
+ for (size_t i=1; i<nSyncTimes; i++) {
+ int diff;
+
+ if (isWrapping && (syncTimes[i] < (PULSE_PROCESSOR_TIMESTAMP_MAX/2))) {
+ diff = ((syncTimes[i] + (1<<PULSE_PROCESSOR_TIMESTAMP_BITWIDTH)) % FRAME_LENGTH) - reference;
+ } else {
+ diff = (syncTimes[i] % FRAME_LENGTH) - reference;
+ }
+
+
+ if (diff < minDiff) {
+ minDiff = diff;
+ }
+ if (diff > maxDiff) {
+ maxDiff = diff;
+ }
+
+ differenceSum += diff;
+ }
+
+ if ((maxDiff - minDiff) > MAX_FRAME_LENGTH_NOISE) {
+ return false;
+ }
+
+ *syncTime = ((int)syncTimes[0] + ((int)differenceSum / (int)nSyncTimes)) & (PULSE_PROCESSOR_TIMESTAMP_MAX);
+
+
+ return true;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor_v2.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor_v2.c
new file mode 100644
index 0000000..199b660
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/lighthouse/pulse_processor_v2.c
@@ -0,0 +1,233 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * pulse_processor_v2.c - pulse decoding for lighthouse V2 base stations
+ *
+ */
+
+#include "pulse_processor_v2.h"
+
+#include <string.h>
+#include <math.h>
+#include "math3d.h"
+#include "test_support.h"
+
+static const uint32_t MAX_TICKS_SENSOR_TO_SENSOR = 10000;
+static const uint32_t MAX_TICKS_BETWEEN_SWEEPS = 220000;
+static const uint8_t NO_CHANNEL = 0xff;
+static const int NO_SENSOR = -1;
+static const uint32_t NO_OFFSET = 0;
+
+#define V2_N_CHANNELS 16
+
+// The cycle times come from the base stations and are expressed in a 48 MHz clock, we use 24 MHz clock hence the "/ 2".
+static const uint32_t CYCLE_PERIODS[V2_N_CHANNELS] = {
+ 959000 / 2, 957000 / 2, 953000 / 2, 949000 / 2,
+ 947000 / 2, 943000 / 2, 941000 / 2, 939000 / 2,
+ 937000 / 2, 929000 / 2, 919000 / 2, 911000 / 2,
+ 907000 / 2, 901000 / 2, 893000 / 2, 887000 / 2
+};
+
+TESTABLE_STATIC bool processBlock(const pulseProcessorV2PulseWorkspace_t* pulseWorkspace, pulseProcessorV2SweepBlock_t* block) {
+ // Check we have data for all sensors
+ for (int i = 0; i < PULSE_PROCESSOR_N_SENSORS; i++) {
+ if (! pulseWorkspace->sensors[i].isSet) {
+ // The sensor data is missing - discard
+ return false;
+ }
+ }
+
+ // Channel - should all be the same except one that is not set
+ int channel_count = 0;
+ block->channel = NO_CHANNEL;
+ for (int i = 0; i < PULSE_PROCESSOR_N_SENSORS; i++) {
+ const pulseProcessorV2Pulse_t* sensor = &pulseWorkspace->sensors[i];
+
+ if (sensor->channelFound) {
+ channel_count++;
+
+ if (block->channel == NO_CHANNEL) {
+ block->channel = sensor->channel;
+ block->slowbit = sensor->slowbit;
+ }
+
+ if (block->channel != sensor->channel) {
+ // Multiple channels in the block - discard
+ return false;
+ }
+
+ if (block->slowbit != sensor->slowbit) {
+ // Multiple slowbits in the block - discard
+ return false;
+ }
+ }
+ }
+
+ if (channel_count != (PULSE_PROCESSOR_N_SENSORS - 1)) {
+ // Channel is missing - discard
+ return false;
+ }
+
+ // Offset - should be offset on one and only one sensor
+ int indexWithOffset = NO_SENSOR;
+ for (int i = 0; i < PULSE_PROCESSOR_N_SENSORS; i++) {
+ const pulseProcessorV2Pulse_t* sensor = &pulseWorkspace->sensors[i];
+ if (sensor->offset != NO_OFFSET) {
+ if (indexWithOffset == NO_SENSOR) {
+ indexWithOffset = i;
+ } else {
+ // Duplicate offsets - discard
+ return false;
+ }
+ }
+ }
+
+ if (indexWithOffset == NO_SENSOR) {
+ // No offset found - discard
+ return false;
+ }
+
+ // Calculate offsets for all sensors
+ const pulseProcessorV2Pulse_t* baseSensor = &pulseWorkspace->sensors[indexWithOffset];
+ for (int i = 0; i < PULSE_PROCESSOR_N_SENSORS; i++) {
+ const pulseProcessorV2Pulse_t* sensor = &pulseWorkspace->sensors[i];
+ if (i == indexWithOffset) {
+ block->offset[i] = sensor->offset;
+ } else {
+ uint32_t timestamp_delta = TS_DIFF(baseSensor->timestamp, sensor->timestamp);
+ block->offset[i] = TS_DIFF(baseSensor->offset, timestamp_delta);
+ }
+ }
+
+ block->timestamp = pulseWorkspace->sensors[0].timestamp;
+
+ return true;
+}
+
+static bool storePulse(const pulseProcessorFrame_t* frameData, pulseProcessorV2PulseWorkspace_t* pulseWorkspace) {
+ const uint8_t sensor = frameData->sensor;
+ pulseProcessorV2Pulse_t* storage = &pulseWorkspace->sensors[sensor];
+
+ bool result = false;
+ if (! storage->isSet) {
+ storage->timestamp = frameData->timestamp;
+ storage->offset = frameData->offset;
+ storage->channel = frameData->channel;
+ storage->slowbit = frameData->slowbit;
+ storage->channelFound = frameData->channelFound;
+
+ storage->isSet = true;
+ result = true;
+ }
+
+ return result;
+}
+
+TESTABLE_STATIC void clearWorkspace(pulseProcessorV2PulseWorkspace_t* pulseWorkspace) {
+ for (int i = 0; i < PULSE_PROCESSOR_N_SENSORS; i++) {
+ pulseWorkspace->sensors[i].isSet = false;
+ }
+}
+
+static bool processFrame(const pulseProcessorFrame_t* frameData, pulseProcessorV2PulseWorkspace_t* pulseWorkspace, pulseProcessorV2SweepBlock_t* block) {
+ bool result = false;
+
+ uint32_t delta = TS_DIFF(frameData->timestamp, pulseWorkspace->latestTimestamp);
+ bool isEndOfPreviuosBlock = (delta > MAX_TICKS_SENSOR_TO_SENSOR);
+ if (isEndOfPreviuosBlock) {
+ result = processBlock(pulseWorkspace, block);
+ clearWorkspace(pulseWorkspace);
+ }
+
+ pulseWorkspace->latestTimestamp = frameData->timestamp;
+
+ if (! storePulse(frameData, pulseWorkspace)) {
+ clearWorkspace(pulseWorkspace);
+ }
+
+ return result;
+}
+
+static void calculateAzimuthElevation(const float firstBeam, const float secondBeam, float* angles) {
+ const float a120 = M_PI_F * 120.0f / 180.0f;
+ const float tan_p_2 = 0.5773502691896258f; // tan(60 / 2)
+
+ angles[0] = ((firstBeam + secondBeam) / 2.0f) - M_PI_F;
+ float beta = (secondBeam - firstBeam) - a120;
+ angles[1] = atan(sinf(beta / 2.0f) / tan_p_2);
+}
+
+static void calculateAngles(const pulseProcessorV2SweepBlock_t* latestBlock, const pulseProcessorV2SweepBlock_t* previousBlock, pulseProcessorResult_t* angles) {
+ const uint8_t channel = latestBlock->channel;
+
+ for (int i = 0; i < PULSE_PROCESSOR_N_SENSORS; i++) {
+ uint32_t firstOffset = previousBlock->offset[i];
+ uint32_t secondOffset = latestBlock->offset[i];
+ uint32_t period = CYCLE_PERIODS[channel];
+
+ float firstBeam = firstOffset * 2 * M_PI_F / period;
+ float secondBeam = secondOffset * 2 * M_PI_F / period;
+
+ calculateAzimuthElevation(firstBeam, secondBeam, angles->sensorMeasurements[i].baseStatonMeasurements[channel].angles);
+ angles->sensorMeasurements[i].baseStatonMeasurements[channel].validCount = 2;
+ }
+}
+
+TESTABLE_STATIC bool isBlockPairGood(const pulseProcessorV2SweepBlock_t* latest, pulseProcessorV2SweepBlock_t* storage) {
+ if (latest->channel != storage->channel) {
+ return false;
+ }
+
+ if (latest->offset[0] < storage->offset[0]) {
+ return false;
+ }
+
+ if (TS_DIFF(latest->timestamp, storage->timestamp) > MAX_TICKS_BETWEEN_SWEEPS) {
+ return false;
+ }
+
+ return true;
+}
+
+bool pulseProcessorV2ProcessPulse(pulseProcessor_t *state, const pulseProcessorFrame_t* frameData, pulseProcessorResult_t* angles, int *baseStation, int *axis) {
+ bool anglesMeasured = false;
+ pulseProcessorV2SweepBlock_t block;
+ if (processFrame(frameData, &state->pulseWorkspace, &block)) {
+ const uint8_t channel = block.channel;
+ if (channel < PULSE_PROCESSOR_N_BASE_STATIONS) {
+ pulseProcessorV2SweepBlock_t* previousBlock = &state->blocksV2[channel];
+ if (isBlockPairGood(&block, previousBlock)) {
+ calculateAngles(&block, previousBlock, angles);
+
+ *baseStation = block.channel;
+ *axis = sweepDirection_y;
+ anglesMeasured = true;
+ } else {
+ memcpy(previousBlock, &block, sizeof(block));
+ }
+ }
+ }
+
+ return anglesMeasured;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/num.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/num.c
new file mode 100644
index 0000000..deeaf9b
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/num.c
@@ -0,0 +1,119 @@
+/**
+ *
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2012-2016 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * num.c - 16bit floating point handling functions
+ */
+
+#include <math.h>
+#include <stdint.h>
+
+#include "num.h"
+
+/* Half precision floating point **********************************************
+ *
+ * To not use the GCC implementation, uint16_t is used to carry fp16 values
+ *
+ * FP16 or Half precision floating points is specified by IEEE 754 as binary 16.
+ * (float is specified as binary 32). This implementation is NOT GUARANTEED to
+ * be conform to the ieee 754 specification, it is 'just' good enough for the
+ * Crazyflie usage. For more info about fp16 see
+ * http://en.wikipedia.org/wiki/Half-precision_floating-point_format
+ *
+ * The current implementation has the following limitation:
+ * * No subnormalized number generation
+ * * Rounding seems to give at least 11 bits precision
+ * * Faster and smaller than the GCC implementation
+ */
+
+uint16_t single2half(float number)
+{
+ uint32_t num = *((uint32_t*)&number);
+ uint32_t s = num>>31;
+ uint32_t e = (num>>23)&0x0FF;
+
+ if ((e==255) && (num&0x007fffff))
+ return 0x7E00; // NaN
+ if (e>(127+15))
+ return s?0xFC00:0x7C00; //+/- inf
+ if (e<(127-15))
+ return 0; //Do not handle generating subnormalised representation
+
+ return (s<<15) | ((e-127+15)<<10) | (((num>>13)&0x3FF)+((num>>12)&0x01));
+}
+
+float half2single(uint16_t number)
+{
+ uint32_t fp32;
+ uint32_t s = number>>15;
+ uint32_t e = (number>>10)&0x01F;
+
+ //All binary16 can be mapped in a binary32
+ if(e==0)
+ e=15-127;
+ if (e==0x1F)
+ {
+ if (number&0x03FF)
+ fp32 = 0x7FC00000; // NaN
+ else
+ fp32 = s?0xFF800000:0x7F800000; //+/- inf
+ }
+ else
+ fp32 = (s<<31) | ((e+127-15)<<23) | ((number&0x3ff)<<13);
+
+ return *(float*)&fp32;
+}
+
+
+/*****************************************************************************/
+
+uint16_t limitUint16(int32_t value)
+{
+ if(value > UINT16_MAX)
+ {
+ value = UINT16_MAX;
+ }
+ else if(value < 0)
+ {
+ value = 0;
+ }
+
+ return (uint16_t)value;
+}
+
+float constrain(float value, const float minVal, const float maxVal)
+{
+ return fminf(maxVal, fmaxf(minVal,value));
+}
+
+float deadband(float value, const float threshold)
+{
+ if (fabsf(value) < threshold)
+ {
+ value = 0;
+ }
+ else if (value > 0)
+ {
+ value -= threshold;
+ }
+ else if (value < 0)
+ {
+ value += threshold;
+ }
+ return value;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/rateSupervisor.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/rateSupervisor.c
new file mode 100644
index 0000000..19a282f
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/rateSupervisor.c
@@ -0,0 +1,65 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2020 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * rateSupervisor.c - functionality to supervise the rate of modules
+ */
+
+#include "rateSupervisor.h"
+
+void rateSupervisorInit(rateSupervisor_t* context, const uint32_t osTimeMs, const uint32_t evaluationIntervalMs, const uint32_t minCount, const uint32_t maxCount, const uint8_t skip) {
+ context->count = 0;
+ context->evaluationIntervalMs = evaluationIntervalMs;
+ context->expectedMin = minCount;
+ context->expectedMax = maxCount;
+ context->nextEvaluationTimeMs = osTimeMs + evaluationIntervalMs;
+ context->latestCount = 0;
+ context->skip = skip;
+}
+
+bool rateSupervisorValidate(rateSupervisor_t* context, const uint32_t osTimeMs) {
+ bool result = true;
+
+ context->count += 1;
+ if (osTimeMs > context->nextEvaluationTimeMs) {
+ uint32_t actual = context->count;
+ if (actual < context->expectedMin || actual > context->expectedMax) {
+ result = false;
+ }
+
+ context->latestCount = context->count;
+ context->count = 0;
+ context->nextEvaluationTimeMs = osTimeMs + context->evaluationIntervalMs;
+
+ if (context->skip > 0) {
+ result = true;
+ context->skip -= 1;
+ }
+ }
+
+ return result;
+}
+
+uint32_t rateSupervisorLatestCount(rateSupervisor_t* context) {
+ return context->latestCount;
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/sleepus.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/sleepus.c
new file mode 100644
index 0000000..69ba047
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/sleepus.c
@@ -0,0 +1,55 @@
+/**
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2012 BitCraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * sleepus.h: Micro second sleep
+ */
+#include <stdint.h>
+#include <stdbool.h>
+
+#include "sleepus.h"
+
+#include "config.h"
+
+//#include "stm32f4xx.h"
+
+#include "FreeRTOS.h"
+#include "task.h"
+
+#include "usec_time.h"
+
+#define TICK_PER_US (FREERTOS_MCU_CLOCK_HZ / (8 * 1e6))
+
+static bool isInit = false;
+
+void sleepus(uint32_t us)
+{
+ if (!isInit) {
+ initUsecTimer();
+ isInit = true;
+ }
+
+ uint64_t start = usecTimestamp();
+
+ while ((start+us) > usecTimestamp());
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/statsCnt.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/statsCnt.c
new file mode 100644
index 0000000..cef4039
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/statsCnt.c
@@ -0,0 +1,65 @@
+/**
+ * ,---------, ____ _ __
+ * | ,-^-, | / __ )(_) /_______________ _____ ___
+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie control firmware
+ *
+ * Copyright (C) 2019 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ *
+ * statsCnt.c - utitlity for logging rates
+ */
+
+#include "statsCnt.h"
+#include "debug_cf.h"
+
+
+void statsCntRateCounterInit(statsCntRateCounter_t* counter, uint32_t averagingIntervalMs) {
+ counter->intervalMs = averagingIntervalMs;
+ counter->count = 0;
+ counter->latestCount = 0;
+ counter->latestAveragingMs = 0;
+ counter->latestRate = 0.0f;
+}
+
+float statsCntRateCounterUpdate(statsCntRateCounter_t* counter, uint32_t now_ms) {
+ uint32_t dt_ms = now_ms - counter->latestAveragingMs;
+ if (dt_ms > counter->intervalMs) {
+ float dt_s = dt_ms / 1000.0f;
+ float dv = counter->count - counter->latestCount;
+
+ counter->latestRate = dv / dt_s;
+
+ counter->latestCount = counter->count;
+ counter->latestAveragingMs = now_ms;
+ }
+
+ return counter->latestRate;
+}
+
+void statsCntRateLoggerInit(statsCntRateLogger_t* logger, uint32_t averagingIntervalMs) {
+ statsCntRateCounterInit(&logger->rateCounter, averagingIntervalMs);
+
+ logger->logByFunction.data = (void*)logger;
+ logger->logByFunction.aquireFloat = statsCntRateLogHandler;
+}
+
+float statsCntRateLogHandler(uint32_t timestamp, void* data) {
+ statsCntRateLogger_t* logger = (statsCntRateLogger_t*)data;
+ return statsCntRateCounterUpdate(&logger->rateCounter, timestamp);
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaEngine.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaEngine.c
new file mode 100644
index 0000000..3f445c6
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaEngine.c
@@ -0,0 +1,236 @@
+/*
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie firmware.
+ *
+ * Copyright 2018, Bitcraze AB
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * tdoaEngine.c 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 tdoaEngine.c. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+/*
+Implementation of LPS TDoA Tag functionality
+
+The tag is assumed to move around in a large system of anchors. Any anchor ids
+can be used, and the same anchor id can even be used by multiple anchors as long
+as they are not visible in the same area. It is assumed that the anchor density
+is evenly distributed in the covered volume and that 5-20 anchors are visible
+in every point. The tag is attached to a physical object and the expected
+velocity is a few m/s, this means that anchors are within range for a time
+period of seconds.
+
+The implementation must handle
+1. An infinite number of anchors, where around 20 are visible at one time
+2. Any anchor ids
+3. Dynamically changing visibility of anchors over time
+4. Random TX times from anchors with possible packet collisions and packet loss
+
+*/
+
+#include <string.h>
+
+#define DEBUG_MODULE "TDOA_ENGINE"
+#include "debug_cf.h"
+
+#include "tdoaEngine.h"
+#include "tdoaStats.h"
+#include "clockCorrectionEngine.h"
+#include "physicalConstants.h"
+
+#define MEASUREMENT_NOISE_STD 0.15f
+
+void tdoaEngineInit(tdoaEngineState_t* engineState, const uint32_t now_ms, tdoaEngineSendTdoaToEstimator sendTdoaToEstimator, const double locodeckTsFreq, const tdoaEngineMatchingAlgorithm_t matchingAlgorithm) {
+ tdoaStorageInitialize(engineState->anchorInfoArray);
+ tdoaStatsInit(&engineState->stats, now_ms);
+ engineState->sendTdoaToEstimator = sendTdoaToEstimator;
+ engineState->locodeckTsFreq = locodeckTsFreq;
+ engineState->matchingAlgorithm = matchingAlgorithm;
+
+ engineState->matching.offset = 0;
+}
+
+#define TRUNCATE_TO_ANCHOR_TS_BITMAP 0x00FFFFFFFF
+static uint64_t truncateToAnchorTimeStamp(uint64_t fullTimeStamp) {
+ return fullTimeStamp & TRUNCATE_TO_ANCHOR_TS_BITMAP;
+}
+
+static void enqueueTDOA(const tdoaAnchorContext_t* anchorACtx, const tdoaAnchorContext_t* anchorBCtx, double distanceDiff, tdoaEngineState_t* engineState) {
+ tdoaStats_t* stats = &engineState->stats;
+
+ tdoaMeasurement_t tdoa = {
+ .stdDev = MEASUREMENT_NOISE_STD,
+ .distanceDiff = distanceDiff
+ };
+
+ if (tdoaStorageGetAnchorPosition(anchorACtx, &tdoa.anchorPosition[0]) && tdoaStorageGetAnchorPosition(anchorBCtx, &tdoa.anchorPosition[1])) {
+ STATS_CNT_RATE_EVENT(&stats->packetsToEstimator);
+
+ uint8_t idA = tdoaStorageGetId(anchorACtx);
+ uint8_t idB = tdoaStorageGetId(anchorBCtx);
+ if (idA == stats->anchorId && idB == stats->remoteAnchorId) {
+ stats->tdoa = distanceDiff;
+ }
+ if (idB == stats->anchorId && idA == stats->remoteAnchorId) {
+ stats->tdoa = -distanceDiff;
+ }
+
+ engineState->sendTdoaToEstimator(&tdoa, idA, idB);
+ }
+}
+
+static bool updateClockCorrection(tdoaAnchorContext_t* anchorCtx, const int64_t txAn_in_cl_An, const int64_t rxAn_by_T_in_cl_T, tdoaStats_t* stats) {
+ bool sampleIsReliable = false;
+
+ const int64_t latest_rxAn_by_T_in_cl_T = tdoaStorageGetRxTime(anchorCtx);
+ const int64_t latest_txAn_in_cl_An = tdoaStorageGetTxTime(anchorCtx);
+
+ if (latest_rxAn_by_T_in_cl_T != 0 && latest_txAn_in_cl_An != 0) {
+ double clockCorrectionCandidate = clockCorrectionEngineCalculate(rxAn_by_T_in_cl_T, latest_rxAn_by_T_in_cl_T, txAn_in_cl_An, latest_txAn_in_cl_An, TRUNCATE_TO_ANCHOR_TS_BITMAP);
+ sampleIsReliable = clockCorrectionEngineUpdate(tdoaStorageGetClockCorrectionStorage(anchorCtx), clockCorrectionCandidate);
+
+ if (sampleIsReliable){
+ if (tdoaStorageGetId(anchorCtx) == stats->anchorId) {
+ stats->clockCorrection = tdoaStorageGetClockCorrection(anchorCtx);
+ STATS_CNT_RATE_EVENT(&stats->clockCorrectionCount);
+ }
+ }
+ }
+
+ return sampleIsReliable;
+}
+
+static int64_t calcTDoA(const tdoaAnchorContext_t* otherAnchorCtx, const tdoaAnchorContext_t* anchorCtx, const int64_t txAn_in_cl_An, const int64_t rxAn_by_T_in_cl_T) {
+ const uint8_t otherAnchorId = tdoaStorageGetId(otherAnchorCtx);
+
+ const int64_t tof_Ar_to_An_in_cl_An = tdoaStorageGetTimeOfFlight(anchorCtx, otherAnchorId);
+ const int64_t rxAr_by_An_in_cl_An = tdoaStorageGetRemoteRxTime(anchorCtx, otherAnchorId);
+ const double clockCorrection = tdoaStorageGetClockCorrection(anchorCtx);
+
+ const int64_t rxAr_by_T_in_cl_T = tdoaStorageGetRxTime(otherAnchorCtx);
+
+ const int64_t delta_txAr_to_txAn_in_cl_An = (tof_Ar_to_An_in_cl_An + truncateToAnchorTimeStamp(txAn_in_cl_An - rxAr_by_An_in_cl_An));
+ const int64_t timeDiffOfArrival_in_cl_T = truncateToAnchorTimeStamp(rxAn_by_T_in_cl_T - rxAr_by_T_in_cl_T) - delta_txAr_to_txAn_in_cl_An * clockCorrection;
+
+ return timeDiffOfArrival_in_cl_T;
+}
+
+static double calcDistanceDiff(const tdoaAnchorContext_t* otherAnchorCtx, const tdoaAnchorContext_t* anchorCtx, const int64_t txAn_in_cl_An, const int64_t rxAn_by_T_in_cl_T, const double locodeckTsFreq) {
+ const int64_t tdoa = calcTDoA(otherAnchorCtx, anchorCtx, txAn_in_cl_An, rxAn_by_T_in_cl_T);
+ return SPEED_OF_LIGHT * tdoa / locodeckTsFreq;
+}
+
+static bool matchRandomAnchor(tdoaEngineState_t* engineState, tdoaAnchorContext_t* otherAnchorCtx, const tdoaAnchorContext_t* anchorCtx) {
+ engineState->matching.offset++;
+ int remoteCount = 0;
+ tdoaStorageGetRemoteSeqNrList(anchorCtx, &remoteCount, engineState->matching.seqNr, engineState->matching.id);
+
+ uint32_t now_ms = anchorCtx->currentTime_ms;
+
+ // Loop over the candidates and pick the first one that is useful
+ // An offset (updated for each call) is added to make sure we start at
+ // different positions in the list and vary which candidate to choose
+ for (int i = engineState->matching.offset; i < (remoteCount + engineState->matching.offset); i++) {
+ uint8_t index = i % remoteCount;
+ const uint8_t candidateAnchorId = engineState->matching.id[index];
+ if (tdoaStorageGetCreateAnchorCtx(engineState->anchorInfoArray, candidateAnchorId, now_ms, otherAnchorCtx)) {
+ if (engineState->matching.seqNr[index] == tdoaStorageGetSeqNr(otherAnchorCtx) && tdoaStorageGetTimeOfFlight(anchorCtx, candidateAnchorId)) {
+ return true;
+ }
+ }
+ }
+
+ otherAnchorCtx->anchorInfo = 0;
+ return false;
+}
+
+static bool matchYoungestAnchor(tdoaEngineState_t* engineState, tdoaAnchorContext_t* otherAnchorCtx, const tdoaAnchorContext_t* anchorCtx) {
+ int remoteCount = 0;
+ tdoaStorageGetRemoteSeqNrList(anchorCtx, &remoteCount, engineState->matching.seqNr, engineState->matching.id);
+
+ uint32_t now_ms = anchorCtx->currentTime_ms;
+ uint32_t youmgestUpdateTime = 0;
+ int bestId = -1;
+
+ for (int index = 0; index < remoteCount; index++) {
+ const uint8_t candidateAnchorId = engineState->matching.id[index];
+ if (tdoaStorageGetTimeOfFlight(anchorCtx, candidateAnchorId)) {
+ if (tdoaStorageGetCreateAnchorCtx(engineState->anchorInfoArray, candidateAnchorId, now_ms, otherAnchorCtx)) {
+ uint32_t updateTime = otherAnchorCtx->anchorInfo->lastUpdateTime;
+ if (updateTime > youmgestUpdateTime) {
+ if (engineState->matching.seqNr[index] == tdoaStorageGetSeqNr(otherAnchorCtx)) {
+ youmgestUpdateTime = updateTime;
+ bestId = candidateAnchorId;
+ }
+ }
+ }
+ }
+ }
+
+ if (bestId >= 0) {
+ tdoaStorageGetCreateAnchorCtx(engineState->anchorInfoArray, bestId, now_ms, otherAnchorCtx);
+ return true;
+ }
+
+ otherAnchorCtx->anchorInfo = 0;
+ return false;
+}
+
+static bool findSuitableAnchor(tdoaEngineState_t* engineState, tdoaAnchorContext_t* otherAnchorCtx, const tdoaAnchorContext_t* anchorCtx) {
+ bool result = false;
+
+ if (tdoaStorageGetClockCorrection(anchorCtx) > 0.0) {
+ switch(engineState->matchingAlgorithm) {
+ case TdoaEngineMatchingAlgorithmRandom:
+ result = matchRandomAnchor(engineState, otherAnchorCtx, anchorCtx);
+ break;
+
+ case TdoaEngineMatchingAlgorithmYoungest:
+ result = matchYoungestAnchor(engineState, otherAnchorCtx, anchorCtx);
+ break;
+
+ default:
+ // Do nothing
+ break;
+ }
+ }
+
+ return result;
+}
+
+void tdoaEngineGetAnchorCtxForPacketProcessing(tdoaEngineState_t* engineState, const uint8_t anchorId, const uint32_t currentTime_ms, tdoaAnchorContext_t* anchorCtx) {
+ if (tdoaStorageGetCreateAnchorCtx(engineState->anchorInfoArray, anchorId, currentTime_ms, anchorCtx)) {
+ STATS_CNT_RATE_EVENT(&engineState->stats.contextHitCount);
+ } else {
+ STATS_CNT_RATE_EVENT(&engineState->stats.contextMissCount);
+ }
+}
+
+void tdoaEngineProcessPacket(tdoaEngineState_t* engineState, tdoaAnchorContext_t* anchorCtx, const int64_t txAn_in_cl_An, const int64_t rxAn_by_T_in_cl_T) {
+ bool timeIsGood = updateClockCorrection(anchorCtx, txAn_in_cl_An, rxAn_by_T_in_cl_T, &engineState->stats);
+ if (timeIsGood) {
+ STATS_CNT_RATE_EVENT(&engineState->stats.timeIsGood);
+
+ tdoaAnchorContext_t otherAnchorCtx;
+ if (findSuitableAnchor(engineState, &otherAnchorCtx, anchorCtx)) {
+ STATS_CNT_RATE_EVENT(&engineState->stats.suitableDataFound);
+ double tdoaDistDiff = calcDistanceDiff(&otherAnchorCtx, anchorCtx, txAn_in_cl_An, rxAn_by_T_in_cl_T, engineState->locodeckTsFreq);
+ enqueueTDOA(&otherAnchorCtx, anchorCtx, tdoaDistDiff, engineState);
+ }
+ }
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaStats.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaStats.c
new file mode 100644
index 0000000..3278398
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaStats.c
@@ -0,0 +1,75 @@
+/*
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie firmware.
+ *
+ * Copyright 2018, Bitcraze AB
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * lpsTdoaTagStats.c 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 lpsTdoaTagStats.c. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/*
+Log statistics for the tdoa engine
+*/
+
+#include <string.h>
+
+#include "tdoaStats.h"
+
+#define STATS_INTERVAL 500
+
+
+void tdoaStatsInit(tdoaStats_t* tdoaStats, uint32_t now_ms) {
+ memset(tdoaStats, 0, sizeof(tdoaStats_t));
+ tdoaStats->remoteAnchorId = tdoaStats->newRemoteAnchorId = 1;
+
+ tdoaStats->nextStatisticsTime = now_ms + STATS_INTERVAL;
+ tdoaStats->previousStatisticsTime = 0;
+
+ STATS_CNT_RATE_INIT(&tdoaStats->packetsReceived, STATS_INTERVAL);
+ STATS_CNT_RATE_INIT(&tdoaStats->packetsToEstimator, STATS_INTERVAL);
+ STATS_CNT_RATE_INIT(&tdoaStats->clockCorrectionCount, STATS_INTERVAL);
+ STATS_CNT_RATE_INIT(&tdoaStats->contextHitCount, STATS_INTERVAL);
+ STATS_CNT_RATE_INIT(&tdoaStats->contextMissCount, STATS_INTERVAL);
+ STATS_CNT_RATE_INIT(&tdoaStats->timeIsGood, STATS_INTERVAL);
+ STATS_CNT_RATE_INIT(&tdoaStats->suitableDataFound, STATS_INTERVAL);
+}
+
+void tdoaStatsUpdate(tdoaStats_t* tdoaStats, uint32_t now_ms) {
+ if (now_ms > tdoaStats->nextStatisticsTime) {
+ if (tdoaStats->anchorId != tdoaStats->newAnchorId) {
+ tdoaStats->anchorId = tdoaStats->newAnchorId;
+
+ // Reset anchor stats
+ tdoaStats->clockCorrection = 0.0;
+ tdoaStats->tof = 0;
+ tdoaStats->tdoa = 0;
+ }
+
+ if (tdoaStats->remoteAnchorId != tdoaStats->newRemoteAnchorId) {
+ tdoaStats->remoteAnchorId = tdoaStats->newRemoteAnchorId;
+
+ // Reset remote anchor stats
+ tdoaStats->tof = 0;
+ tdoaStats->tdoa = 0;
+ }
+
+ tdoaStats->previousStatisticsTime = now_ms;
+ tdoaStats->nextStatisticsTime = now_ms + STATS_INTERVAL;
+ }
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaStorage.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaStorage.c
new file mode 100644
index 0000000..c5760ed
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/tdoa/tdoaStorage.c
@@ -0,0 +1,310 @@
+/*
+ * || ____ _ __
+ * +------+ / __ )(_) /_______________ _____ ___
+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+ *
+ * Crazyflie firmware.
+ *
+ * Copyright 2018, Bitcraze AB
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * tdoaEngine.c 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 tdoaEngine.c. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+/*
+Data storage encapsulation for the TDoA engine
+*/
+
+#include <string.h>
+
+#define DEBUG_MODULE "TDOA_STORAGE"
+#include "debug_cf.h"
+
+#include "tdoaStorage.h"
+
+// All times in milli seconds
+#define TOF_VALIDITY_PERIOD (2 * 1000)
+#define REMOTE_DATA_VALIDITY_PERIOD 30
+#define ANCHOR_POSITION_VALIDITY_PERIOD (2 * 1000)
+#define ANCHOR_ACTIVE_VALIDITY_PERIOD (2 * 1000)
+
+
+static tdoaAnchorInfo_t* initializeSlot(tdoaAnchorInfo_t anchorStorage[], const uint8_t slot, const uint8_t anchor);
+
+void tdoaStorageInitialize(tdoaAnchorInfo_t anchorStorage[]) {
+ memset(anchorStorage, 0, sizeof(tdoaAnchorInfo_t) * ANCHOR_STORAGE_COUNT);
+}
+
+bool tdoaStorageGetCreateAnchorCtx(tdoaAnchorInfo_t anchorStorage[], const uint8_t anchor, const uint32_t currentTime_ms, tdoaAnchorContext_t* anchorCtx) {
+ anchorCtx->currentTime_ms = currentTime_ms;
+ uint32_t oldestUpdateTime = currentTime_ms;
+ int firstUninitializedSlot = -1;
+ int oldestSlot = 0;
+
+ for (int i = 0; i < ANCHOR_STORAGE_COUNT; i++) {
+ if (anchorStorage[i].isInitialized) {
+ if (anchor == anchorStorage[i].id) {
+ anchorCtx->anchorInfo = &anchorStorage[i];
+ return true;
+ }
+
+ if (anchorStorage[i].lastUpdateTime < oldestUpdateTime) {
+ oldestUpdateTime = anchorStorage[i].lastUpdateTime;
+ oldestSlot = i;
+ }
+ } else {
+ if (firstUninitializedSlot == -1) {
+ firstUninitializedSlot = i;
+ }
+ }
+ }
+
+ // The anchor was not found in storage
+ tdoaAnchorInfo_t* newAnchorInfo = 0;
+ if (firstUninitializedSlot != -1) {
+ newAnchorInfo = initializeSlot(anchorStorage, firstUninitializedSlot, anchor);
+ } else {
+ newAnchorInfo = initializeSlot(anchorStorage, oldestSlot, anchor);
+ }
+
+ anchorCtx->anchorInfo = newAnchorInfo;
+ return false;
+}
+
+bool tdoaStorageGetAnchorCtx(tdoaAnchorInfo_t anchorStorage[], const uint8_t anchor, const uint32_t currentTime_ms, tdoaAnchorContext_t* anchorCtx) {
+ anchorCtx->currentTime_ms = currentTime_ms;
+
+ for (int i = 0; i < ANCHOR_STORAGE_COUNT; i++) {
+ if (anchorStorage[i].isInitialized) {
+ if (anchor == anchorStorage[i].id) {
+ anchorCtx->anchorInfo = &anchorStorage[i];
+ return true;
+ }
+ }
+ }
+
+ anchorCtx->anchorInfo = 0;
+ return false;
+}
+
+uint8_t tdoaStorageGetListOfAnchorIds(tdoaAnchorInfo_t anchorStorage[], uint8_t unorderedAnchorList[], const int maxListSize) {
+ int count = 0;
+
+ for (int i = 0; i < ANCHOR_STORAGE_COUNT && count < maxListSize; i++) {
+ if (anchorStorage[i].isInitialized) {
+ unorderedAnchorList[count] = anchorStorage[i].id;
+ count++;
+ }
+ }
+
+ return count;
+}
+
+uint8_t tdoaStorageGetListOfActiveAnchorIds(tdoaAnchorInfo_t anchorStorage[], uint8_t unorderedAnchorList[], const int maxListSize, const uint32_t currentTime_ms) {
+ int count = 0;
+
+ const uint32_t expiryTime = currentTime_ms - ANCHOR_ACTIVE_VALIDITY_PERIOD;
+ for (int i = 0; i < ANCHOR_STORAGE_COUNT && count < maxListSize; i++) {
+ if (anchorStorage[i].isInitialized && anchorStorage[i].lastUpdateTime > expiryTime) {
+ unorderedAnchorList[count] = anchorStorage[i].id;
+ count++;
+ }
+ }
+
+ return count;
+}
+
+uint8_t tdoaStorageGetId(const tdoaAnchorContext_t* anchorCtx) {
+ return anchorCtx->anchorInfo->id;
+}
+
+int64_t tdoaStorageGetRxTime(const tdoaAnchorContext_t* anchorCtx) {
+ return anchorCtx->anchorInfo->rxTime;
+}
+
+int64_t tdoaStorageGetTxTime(const tdoaAnchorContext_t* anchorCtx) {
+ return anchorCtx->anchorInfo->txTime;
+}
+
+uint8_t tdoaStorageGetSeqNr(const tdoaAnchorContext_t* anchorCtx) {
+ return anchorCtx->anchorInfo->seqNr;
+}
+
+uint32_t tdoaStorageGetLastUpdateTime(const tdoaAnchorContext_t* anchorCtx) {
+ return anchorCtx->anchorInfo->lastUpdateTime;
+}
+
+clockCorrectionStorage_t* tdoaStorageGetClockCorrectionStorage(const tdoaAnchorContext_t* anchorCtx) {
+ return &anchorCtx->anchorInfo->clockCorrectionStorage;
+}
+
+bool tdoaStorageGetAnchorPosition(const tdoaAnchorContext_t* anchorCtx, point_t* position) {
+ uint32_t now = anchorCtx->currentTime_ms;
+
+ int32_t validCreationTime = now - ANCHOR_POSITION_VALIDITY_PERIOD;
+ const tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+ if ((int32_t)anchorInfo->position.timestamp > validCreationTime) {
+ position->timestamp = anchorInfo->position.timestamp;
+ position->x = anchorInfo->position.x;
+ position->y = anchorInfo->position.y;
+ position->z = anchorInfo->position.z;
+ return true;
+ }
+
+ return false;
+}
+
+void tdoaStorageSetAnchorPosition(tdoaAnchorContext_t* anchorCtx, const float x, const float y, const float z) {
+ uint32_t now = anchorCtx->currentTime_ms;
+ tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+
+ anchorInfo->position.timestamp = now;
+ anchorInfo->position.x = x;
+ anchorInfo->position.y = y;
+ anchorInfo->position.z = z;
+}
+
+void tdoaStorageSetRxTxData(tdoaAnchorContext_t* anchorCtx, int64_t rxTime, int64_t txTime, uint8_t seqNr) {
+ uint32_t now = anchorCtx->currentTime_ms;
+ tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+
+ anchorInfo->rxTime = rxTime;
+ anchorInfo->txTime = txTime;
+ anchorInfo->seqNr = seqNr;
+ anchorInfo->lastUpdateTime = now;
+}
+
+double tdoaStorageGetClockCorrection(const tdoaAnchorContext_t* anchorCtx) {
+ return clockCorrectionEngineGet(&anchorCtx->anchorInfo->clockCorrectionStorage);
+}
+
+int64_t tdoaStorageGetRemoteRxTime(const tdoaAnchorContext_t* anchorCtx, const uint8_t remoteAnchor) {
+ const tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+
+ for (int i = 0; i < REMOTE_ANCHOR_DATA_COUNT; i++) {
+ if (remoteAnchor == anchorInfo->remoteAnchorData[i].id) {
+ uint32_t now = anchorCtx->currentTime_ms;
+ if (anchorInfo->remoteAnchorData[i].endOfLife > now) {
+ return anchorInfo->remoteAnchorData[i].rxTime;
+ }
+ break;
+ }
+ }
+
+ return 0;
+}
+
+void tdoaStorageSetRemoteRxTime(tdoaAnchorContext_t* anchorCtx, const uint8_t remoteAnchor, const int64_t remoteRxTime, const uint8_t remoteSeqNr) {
+ tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+
+ int indexToUpdate = 0;
+ uint32_t now = anchorCtx->currentTime_ms;
+ uint32_t oldestTime = 0xFFFFFFFF;
+
+ for (int i = 0; i < REMOTE_ANCHOR_DATA_COUNT; i++) {
+ if (remoteAnchor == anchorInfo->remoteAnchorData[i].id) {
+ indexToUpdate = i;
+ break;
+ }
+
+ if (anchorInfo->remoteAnchorData[i].endOfLife < oldestTime) {
+ oldestTime = anchorInfo->remoteAnchorData[i].endOfLife;
+ indexToUpdate = i;
+ }
+ }
+
+ anchorInfo->remoteAnchorData[indexToUpdate].id = remoteAnchor;
+ anchorInfo->remoteAnchorData[indexToUpdate].rxTime = remoteRxTime;
+ anchorInfo->remoteAnchorData[indexToUpdate].seqNr = remoteSeqNr;
+ anchorInfo->remoteAnchorData[indexToUpdate].endOfLife = now + REMOTE_DATA_VALIDITY_PERIOD;
+}
+
+void tdoaStorageGetRemoteSeqNrList(const tdoaAnchorContext_t* anchorCtx, int* remoteCount, uint8_t seqNr[], uint8_t id[]) {
+ const tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+ uint32_t now = anchorCtx->currentTime_ms;
+
+ int count = 0;
+
+ for (int i = 0; i < REMOTE_ANCHOR_DATA_COUNT; i++) {
+ if (anchorInfo->remoteAnchorData[i].endOfLife > now) {
+ id[count] = anchorInfo->remoteAnchorData[i].id;
+ seqNr[count] = anchorInfo->remoteAnchorData[i].seqNr;
+ count++;
+ }
+ }
+
+ *remoteCount = count;
+}
+
+int64_t tdoaStorageGetTimeOfFlight(const tdoaAnchorContext_t* anchorCtx, const uint8_t otherAnchor) {
+ const tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+
+ for (int i = 0; i < TOF_PER_ANCHOR_COUNT; i++) {
+ if (otherAnchor == anchorInfo->tof[i].id) {
+ uint32_t now = anchorCtx->currentTime_ms;
+ if (anchorInfo->tof[i].endOfLife > now) {
+ return anchorInfo->tof[i].tof;
+ }
+ break;
+ }
+ }
+
+ return 0;
+}
+
+void tdoaStorageSetTimeOfFlight(tdoaAnchorContext_t* anchorCtx, const uint8_t remoteAnchor, const int64_t tof) {
+ tdoaAnchorInfo_t* anchorInfo = anchorCtx->anchorInfo;
+
+ int indexToUpdate = 0;
+ uint32_t now = anchorCtx->currentTime_ms;
+ uint32_t oldestTime = 0xFFFFFFFF;
+
+ for (int i = 0; i < TOF_PER_ANCHOR_COUNT; i++) {
+ if (remoteAnchor == anchorInfo->tof[i].id) {
+ indexToUpdate = i;
+ break;
+ }
+
+ if (anchorInfo->tof[i].endOfLife < oldestTime) {
+ oldestTime = anchorInfo->tof[i].endOfLife;
+ indexToUpdate = i;
+ }
+ }
+
+ anchorInfo->tof[indexToUpdate].id = remoteAnchor;
+ anchorInfo->tof[indexToUpdate].tof = tof;
+ anchorInfo->tof[indexToUpdate].endOfLife = now + TOF_VALIDITY_PERIOD;
+}
+
+bool tdoaStorageIsAnchorInStorage(tdoaAnchorInfo_t anchorStorage[], const uint8_t anchor) {
+ for (int i = 0; i < ANCHOR_STORAGE_COUNT; i++) {
+ if (anchorStorage[i].isInitialized) {
+ if (anchor == anchorStorage[i].id) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+static tdoaAnchorInfo_t* initializeSlot(tdoaAnchorInfo_t anchorStorage[], const uint8_t slot, const uint8_t anchor) {
+ memset(&anchorStorage[slot], 0, sizeof(tdoaAnchorInfo_t));
+ anchorStorage[slot].id = anchor;
+ anchorStorage[slot].isInitialized = true;
+
+ return &anchorStorage[slot];
+}
diff --git a/Firmware/esp-drone/components/core/crazyflie/utils/src/version.c b/Firmware/esp-drone/components/core/crazyflie/utils/src/version.c
new file mode 100644
index 0000000..df24086
--- /dev/null
+++ b/Firmware/esp-drone/components/core/crazyflie/utils/src/version.c
@@ -0,0 +1,44 @@
+/**
+*
+ * ESP-Drone Firmware
+ *
+ * Copyright 2019-2020 Espressif Systems (Shanghai)
+ * Copyright (C) 2011-2012 Bitcraze AB
+ *
+ * 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, in version 3.
+ *
+ * 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, see <http://www.gnu.org/licenses/>.
+ *
+ * version.tmpl - version of the build
+ */
+#include <stdint.h>
+#include <stdbool.h>
+
+#include "config.h"
+#include "param.h"
+
+const char * V_SLOCAL_REVISION="{local_revision}";
+const char * V_SREVISION="{revision}";
+const char * V_STAG="{tag}";
+const char * V_BRANCH="{branch}";
+const bool V_MODIFIED= 0 ;//{modified};
+const bool V_PRODUCTION_RELEASE= 0 ;//{productionRelease};
+
+/* Version recoverable from the ground */
+const uint32_t V_REVISION_0=0;//{irevision0};
+const uint16_t V_REVISION_1=1;//{irevision1};
+
+PARAM_GROUP_START(firmware)
+PARAM_ADD(PARAM_UINT32 | PARAM_RONLY, revision0, &V_REVISION_0)
+PARAM_ADD(PARAM_UINT16 | PARAM_RONLY, revision1, &V_REVISION_1)
+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, modified, &V_MODIFIED)
+PARAM_GROUP_STOP(firmware)
+